Sunteți pe pagina 1din 98

Contents

Chap. I: INTRODUCTION TO JAVA PROGRAMMING .................................................................................. 1


1.1 Introduction ................................................................................................................................... 1
1.2 How to run Java programs ............................................................................................................. 1
Java Development Kit (JDK) .............................................................................................................. 2
1.3 Features of Java ............................................................................................................................. 5
1.4 Language Basics ............................................................................................................................. 6
The Java Keywords........................................................................................................................... 6
Operators ........................................................................................................................................ 6
VARIABLES ..................................................................................................................................... 12
Data Types ..................................................................................................................................... 12
Review questions............................................................................................................................... 17
Chap. II: CONTROL STATEMENTS ........................................................................................................... 18
2.1 Selection statements ................................................................................................................... 18
if statement ................................................................................................................................... 18
Switch Statement .......................................................................................................................... 19
2.2 Iterative Statements .................................................................................................................... 20
2.3 Jump statements ......................................................................................................................... 21
Break Statement ............................................................................................................................ 21
Continue statement ....................................................................................................................... 21
Review questions............................................................................................................................... 27
Chap III. OBJECTS AND CLASSES ............................................................................................................. 28
3.1 An object - oriented philosophy ................................................................................................... 28
3.2 How to design user defined java classes ....................................................................................... 29
A Simple Class................................................................................................................................ 29
3.3 Methods ...................................................................................................................................... 31
3.4 Constructors ................................................................................................................................ 35
3.5 Static Methods and Variables....................................................................................................... 39
Understanding Static Methods and Variables ................................................................................. 39
Review Questions .............................................................................................................................. 40

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY i


Chap IV: CHARACTERS AND STRINGS ..................................................................................................... 41
4.1 Characters ................................................................................................................................... 41
4.2 Strings ......................................................................................................................................... 42
String Length ................................................................................................................................. 42
String Concatenation ..................................................................................................................... 43
String Comparison ......................................................................................................................... 43
Searching Strings ........................................................................................................................... 44
Modifying String ............................................................................................................................ 44
Changing Case ............................................................................................................................... 45
String Buffer .................................................................................................................................. 45
Chap. V: ARRAYS ................................................................................................................................... 47
5.1 One – Dimensional Arrays ...................................................................................................... 47
Arrays of static allocation declaration ............................................................................................ 47
Arrays of dynamic allocation declaration ....................................................................................... 48
To get the input from the user ....................................................................................................... 50
5.2 Multi - Dimensional Arrays ..................................................................................................... 51
5.3 Algorithms for Sorting and Searching Arrays........................................................................... 54
Sorting Arrays ................................................................................................................................ 54
Searching Arrays ............................................................................................................................ 56
Review questions............................................................................................................................... 57
Chap VI: Inheritance .............................................................................................................................. 58
6.1 Inheritance Basics ........................................................................................................................ 58
6.2 Member Access and Inheritance .................................................................................................. 60
6.3 Method Overriding ...................................................................................................................... 61
Rules for method overriding .......................................................................................................... 63
Using the super keyword: .............................................................................................................. 63
Examples ....................................................................................................................................... 64
6.4 Abstract class ............................................................................................................................... 76
Practical example........................................................................................................................... 78
6.5 Encapsulation .............................................................................................................................. 84
Access Control ............................................................................................................................... 86
Review Questions .............................................................................................................................. 86

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY ii


Chap VII: Package and interface ............................................................................................................. 87
7.1 Packages ...................................................................................................................................... 87
Defining a Package......................................................................................................................... 87
Access Protection .......................................................................................................................... 88
An Access Example ........................................................................................................................ 89
Importing Packages........................................................................................................................ 91
7.2 Interfaces..................................................................................................................................... 93
Implementing Interfaces ................................................................................................................ 95

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY iii


Chap. I: INTRODUCTION TO JAVA PROGRAMMING

1.1 Introduction

Java is both a programming language and a platform. Java was conceived by James Gosling,
Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan at Sun Micro Systems in the year
1991. This language was initially called “Oak” but was renamed “Java” in 1995.

Between the initial implementation of Oak in the fall of 1992 and the public announcement of
java in the spring of 1995, many more people contributed to the design and evolution of the
language. Bill Joy, Arthur van Hoff, Jonathan Payne,Frank Yellin and Tim Lindholm were key
contributors to the maturing of the original prototype.

Java is an Object-Oriented, Multi-threaded programming language. It is designed to be small,


simple and portable across both platforms as well as operating systems, at the source and binary
level.

Java Applets and Applications

Java can be used to create two types of programs: applications and applets. An application is a
program that runs on your computer, under the operating systems of that computer. That is, an
application created by Java is more or less like one created using C or C++. When used to create
applications, Java is not much different from any other computer language. Rather, it is Java‟s
ability to create applets that makes it important.

1.2 How to run Java programs

How Java program works

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 1


For different platforms

Java Development Kit (JDK)

In order to write a Java program, an editor, a Java compiler and a Java Runtime Environment are needed.
The easiest way to get a Java compiler and a Java Runtime Environment is to download Sun‟s Java
Development Kit.

Steps to run a java program:

1. Write your java code in a editor like notepad


2. Save the program with an extension .java
3. Compile the program in command mode using javac filename.java
4. Run the program in command mode using java filename

The first program in Java

/* Program for Welcome to KCT */


import java.io.*;
class prog
{
public static void main(String args[ ])
{
System.out.println(“Welcome to KCT”);
}
}

Output: Welcome to KCT

In this program

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 2


• /* … */ statement is used to put comments in the program

 (Comment statements will not be compiled by the compiler)

• import java.io.*;

 import is equivalent to include in C/C++

 java.io.* ; is a package (class or library) which contains the input output classes

• class prog

 class is a keyword (all the programs in java starts with class) and Prog is the class name

• public static void main(String args[ ])

 the main method in java using public static and the arguments passed in to that program
will be considered as Strings

• System.out.println(“Welcome to java”);

 System.out.println() is a method to print the output.

• Java is case sensitive, means that A≠a

• Delimiters (;) are the end of statements in Java

Program Statements

A program statement is where all the action takes place. There are three categories of statements:

• Simple

• Compound

• Comments

Simple and compound statements are compiled and become part of your application‟s binary
image; all compiled statements must end with a semicolon (;). Comments are not compiled and
are visible only in the source code, but they can be invaluable several months later when you (or
someone maintaining your code) are trying to determine the original purpose of that code.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 3


Simple Statements

Simple statements can assign values, perform an action, or call a method.

A method is the term used in Java to indicate any subprogram (subroutine, func tion, or
procedure).

Here are some examples of simple statements:

currpoint = new Point(x,y);

if (i==8) j = 4;

g.drawString(“Hello world!”, 10, 30);

repaint();

Block Statements

You generally can use a block anywhere that a single statement is valid, and the block creates a
new local scope for the statements within it. This means that you can declare and use local
variables within a block, and those variables will cease to exist after the block is finished
executing.

A block statement (or simply, a block) is a group of other program statements surrounded by
braces ({}). This is the same way braces are used in C and C++ and is analogous to the
begin..end pair in Pascal. It is also sometimes known as a compound statement.

Here‟s an example that highlights the differences in scope. In the following method defi-nition, x
is declared for the method as a whole, and y is declared within the block:

void testblock() {
int x = 10;
{
// block begin
int y = 50;
System.out.println(“inside the block:”);
System.out.println(“x:” + x); // prints 10
System.out.println(“y:” + y); // prints 50
} // block end
System.out.println(“outside the block:”);
System.out.println(“x:” + x); // prints 10
System.out.println(“y:” + y); // error, outside the scope
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 4


1.3 Features of Java
Java programming language is designed to support the following features:

• Simple

 Similar to C and C++


 Easy to learn

• Object Oriented

 Supports OOPS concepts


 “Everything is and Object”
 Provides high performance object model

• Robust

 Reliable extension in a variety of systems


 Strictly typed language
 Checks code at compiling time and run time

• Multithreaded

 Code is divided into small segments


 Simultaneous execution of threads
 Multi process synchronization

• Architecture Neutral

 Guarantee exists for your program to run today, tomorrow and ever
 “Write once, run anywhere, anytime forever”

• High Performance

 Enables creation of cross platform programs


 Interpreted by Java Virtual Machine (JVM)
 Performs well on very low power CPU‟s

• Distributed

 Designed to distributed environment for Internet


 Easy handling of TCP/IP protocols
 Executing Remote Procedures in different machines (RMI)

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 5


 Client/Server Programming

• Dynamic

 Dynamically link code in run time


 Code can be updated in a running system

1.4 Language Basics

The Java Keywords

There are 48 reserved keywords currently defined in the Java language (See Table 1). These
keywords, combined with the syntax of the operators and separators, form the definition of the
Java language. These keywords cannot be used as names for a variable, class or method.

abstact const finally int public this

boolean continue float interface return throw

break default for long short throws

byte do goto native static transient

case double if new strictfp try

catch else implements package super void

char extends import private switch volatile

class final instanceof protected synchronized while


Table 1: Java Reserved Keywords

In addition to the keywords , Java reserves the following: true, false and null.
These are values defined by Java. You may not use these words for the names of variables,
classes and so on.

Operators
Operators are special symbols used in expressions. They include arithmetic operators,
assignment operators, increment and decrement operators, logical operators and comparision
operators.
Arithmetic Operators : Java has five basic arithmetic operators. Each of these operators takes
two operands. One on either side of the operator (see table2).

Operator Meaning Example

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 6


+ Addition 3+4

- Subtraction 80-23

* Multiplication 5*7

/ Division 100/20

% Modulus 10%3

Table 2: Arithmetic operators

The subtraction operator is also used to negate a single operand. Integer division results in an
integer. Any remainder due to integer division is ignored. Modulus gives the remainder once the
division has been completed. For integer types, the result is an int regardless of the type of the
operands. If any one or both the operands is of type long, then the result is also long. If one
operand is an int and the other is float, then the result is a float.

Assignment Operators

The main assignment operator is „=‟. Other complex assignment operators used in C and C++ are also
used in Java. A selection of assignment operators is given in the table below.

Expression Meaning
x + =y x=x+y
x - =y x=x-y
x *=y x=x*y
x /=y x=x/y
x %=y x=x%y
Table 3: Assignments Operators

Incrementing and Decrementing


To increment or decrement a value by one, the ++operator and -- operator are used respectively.
The increment and the decrement operators can be prefixed or postfixed. The different increment
and decrement operators can be used as given below:
 ++a (Pre increment Operator): Increment by 1, then use the new value of a in the
expression in which a resides.
 a++ (Post Increment Operator): Use the current value of a in the expression in which
a resides and then increment a by 1.
 --b (Pre decrement operator): Decrement b by 1, then use the new value of b in the
expression in which b resides.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 7


 b-- (Post decrement operator): Use the current value of b in the expression in which b
resides and then decrement b by 1.

Relational operators: The relational operators determine the relationship that one operand has
to the other. Specifically, they determine equality and ordering. The relational operators are
shown here:
Operators Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Table 4: Relational operators

Boolean Logical Operators: The Boolean logical operators shown here operate only on Boolean
operands. All of the binary logical operators combine two Boolean values to form a resultant
Boolean value.

Operator Result
& Logical AND
| Logical OR
Logical XOR(Exclusive
^ OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
!= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else

The logical Boolean operators , &,| and ^ operate on Boolean values in the same way that they operate on
the bits of an integer. The logical ! operator inverts the Boolean state: !true==false and !false=true.

Bitwise Operators

Operator Result
~ Bitwise unary NOT

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 8


& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
!= Bitwise OR assignment
^= Bitwise exclusive OR
assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment

An example program is shown below that demonstrates the different Bit wise operators in java.
class BitwiseOperatorDemo
{
public static void main(String args [])
{

int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1


int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1

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


System.out.println("x | y : "+(x | y));
System.out.println("x ^ y : "+(x ^ y));
System.out.println("~x : "+(~x));
System.out.println("x << y : "+(x << 2));
System.out.println("x >> y : "+(x >> 3));
}
}

The below program demostrates bitwise operators keeping in mind operator precedence

Operator Precedence starting with the highest is: |, ^, &

public class BitwisePrecedenceEx

public static void main (String[] args)

int a = 1 | 2 ^ 3 & 5;

int b = ((1 | 2) ^ 3) & 5;

int c = 1 | (2 ^ (3 & 5));

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 9


System.out.print(“a = ”+ a + ", b = " + b + ", c = " + c);
}
}

The Operator (Ternary operator)


Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the ? , and it works in Java much like it does in C and C++. The
general form is expression1 ? expression2 : expression 3
Here expression1 can be any expression that evaluates to a Boolean value. If expression1 is
true, the expression2 is evaluated; otherwise , expression3 is evaluated.

An example program is shown below that demonstrates the Ternary operator in java.

class ConditionalOperatorsDemo
{
public static void main(String[] args)
{
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 10


Operator Precedence
The following table shows the order of precedence for Java operators, from highest to lowest.

Table 5: The precedence of the Java operators

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 11


VARIABLES

 A variable is an item of data named by an identifier


 Variables can be declared anywhere in the method definition and can be initialized
during their declaration. They are commonly declared before usage at the beginning of
the definition. Variables with the same data type can be declared together. Local
variables must be given a value before usage.
 Variable names in Java can start with a letter, an underscore( _ ) , or a dollar sign ( $ )
but cannot begin with a number. The second character onwards can include any letter or
number. Java is case sensitive.
 There are three ways of variable declarations
 data type variable; // declaration of a variable
int a;
 data type variable=value; // initialization of a variable
int a=5;
 data type variable=expression; // dynamic initialization
int a=b+c;

Data Types

Every variable declared should have a name, a type and a value. Java provides different data
types that include character, double, float, integer, string, boolean etc. These are primitive types
as they are built into the Java language and are not actual objects. New types are declared by a
class definition and objects of this class can be created.

Integer Type
Integers are used for storing integer values. These are four kinds of integer types in Java . Each
of these can hold a different range of values. The values can either be positive or nagative.

The table for the range of values is given below:

Type Size Range


byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
int 32 bits -2,147,483,648 to
2,147,483,647
long 64 bits 9223372036854775808 to
9.22337E+18

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 12


Floating-Point Types

Floating- point numbers also known as real numbers, are used when evaluating expressions that
require fractional precision. For example, calculations such as squareroot, or transcendentals
such as sine and cosine, result in a value whose precision requires a floating-point type.

Type Size Range


double 64 bits 1.7e –308 to 1.7e+308
float 32 bits 3.4e-038 to 3.4e+038

Character
It is used for storing individual characters . The character type has 16 bits of precision and it is
unsigned.

Boolean

Boolean type holds either a true or false value. These are not stored as numeric values and
cannot be used as such.

Example1:

class Second {
public static void main( String args[]) {
int x=90;
short y=4;
float z=10.87f;
System.out.println (“ The integer value is “ + x);
System.out.println (“ The short value is “ + y);
System.out.println (“ The float value is “ + z);
}

Example2:

class AssignmentOperatorsDemo

public static void main(String args[])

//Assigning Primitive Values


int j, k;
j = 10; // j gets the value 10.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 13


j = 5; // j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.
System.out.println("j is : "+j);
System.out.println("k is : "+k);

//Multiple Assignments
k = j = 10; // (k = (j = 10))
System.out.println("j is : "+j);
System.out.println("k is : "+k);

Exapmle 3

class ArithmeticOperatorsDemo

public static void main(String args[])

int x, y = 10, z = 4;

x = y + z;

System.out.println("+ operator resulted in "+x);

x = y - z;

System.out.println("- operator resulted in "+x);

x = y * z;

System.out.println("* operator resulted in "+x);

x = y / z;

System.out.println("/ operator resulted in "+x);

x = y % z;

System.out.println("% operator resulted in "+x);

x = y++;

System.out.println("Postfix ++ operator resulted in "+x);

x = ++z;

System.out.println("Prefix ++ operator resulted in "+x);

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 14


x = -y;

System.out.println("Unary operator resulted in "+x);

//Some examples of special Cases

double d1 = 12/8;

//result: 1 by integer division. d1 gets the value 1.0.

double d2 = 12.0F / 8; // result: 1.5

System.out.println("d1 is "+d1);

System.out.println("d2 is "+d2);

Exapmle 4

class CompoundOperatorsDemo
{
public static void main(String[] args)
{
int x = 0, y = 5;
x += 3;
System.out.println("x = "+x);
y *= x;
System.out.println("y = "+y);
}
}

Exapmle 5
// Text-printing program.

public class Welcome1


{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome to Java Programming!" );

} // end method main

} // end class Welcome1

Exapmle 6
// Printing one line of text with multiple statements.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 15


public class Welcome2
{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );

} // end method main

} // end class Welcome2


Exapmle 7
// Printing multiple lines with a single statement.

public class Welcome3


{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome\nto\nJava\nProgramming!" );

} // end method main

} // end class Welcome3

Exapmle 8

//arithmetic operators example


class Arithmetic {
public static void main ( String args[] ) {
int x=10;
int y=20;
float z=25.98f;
System.out.println( “The value of x+y is “ + (x+y));
System.out.println( “The value of z-y is “ + (z-y));
System.out.println( “The value of x*y is “ + (x*y));
System.out.println( “The value of z/y is “ + (z/y));
System.out.println( “The value of z%y is “ + (z%y));
}
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 16


Review questions

1. What are the various operators available in Java?


2. Define Ternary Operator with example.
3. Explain increment and decrement operators in Java.
4. Explain all bitwise logical operators.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 17


Chap. II: CONTROL STATEMENTS

Java‟s program control statements can be put into the following categories: selection, iteration
and jump.

2.1 Selection statements

Selection statements allow your program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.

if statement
Simple if Statement
if (condtion)
{
true block statements;
}

if…else Statement
if (condtion)
{
true block statements;
}

else
{
false block statements;
}

Nested If Statement
A nested if is an if statement that is the target of another if or else. Nested ifs are very common in
programming. When you nest ifs, the main thing to remember is that an else statement always
refers to the nearest if statement that is, within the same block as the else and that is not already
associated with an else. Here is an example:
if( I == 10 )
{
if( j< 20)
a=b;
if(k>100)
c=d;
else
a=c;
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 18


else
a=d;

The final else is not associated with if (j<20), because it is not in the same block. Rather, the
final else is associated with if (I==10). The inner else refers to if (k>100), because it is the
closest if within the same block.

If- else-if statements


A common programming construct that is based upon a sequence of nested ifs is the if-
else-if. It looks like this:
if (condition)
Statement;
else if (condition)
Statement;
else if (condition)
statement;
else
statement;
Switch Statement

The Switch statement dispatches control to the different parts of the code based on the value of a
single variable or expression. The general form of switch statement is given below.

Switch (expression) {
Case value1 :
// Statement sequence break;
case value2 :
// Statement sequence break
.
.
case valueN :
// statement sequence break;
default :
// default statement sequence

The expression must be of type byte, short, int or char; each of the values specified in the case
statements must be of a type compatible with the expression.

The break statement is used inside the switch to terminate a statement sequence. When a break
statement is encountered, execution branches to the first line of code that follows the entire
switch statement. This has the effect of “ Jumping out “ of the switch.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 19


2.2 Iterative Statements

Java‟s iterative statements are for while and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met.

For loop

The for loop appears as shown :

for(initialization; condition; increment/decrement)

{
set of statements;
}

While loop

Here is its general form :

Initializations;
while (condition)
{
…..
Increment/decrement;
}

The body of the loop will be executed as long as the conditional expression is true.

do .. while

Its general form is:

Initializations;
do
{
…..
Increment/decrement);
} while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 20


conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates.

2.3 Jump statements

These statements transfer control to another part of your program.

Break Statement

The break statement used to terminate the control from any looping structure.

Here is a simple example :

// Using break to exit a loop


class BreakLloop {
public static void main ( String args[] )
{
for( int I=0; I< 100 ; I++ )
{
if( I == 10) break; // terminate loop if I is 10.
System..out.println ( “ I : “ + I );
}
}

Continue statement
When the continue statement executes, it skips the remaining statements in the loop and
continue the next iteration.
Here is a simple example:
class ContinueLoop {
public static void main (String args [] ) {
System.out.println( “ The following numbers are divisable by 5 “ );
for ( int I = 0; I <= 25; I++)
{
if( I % 5 != 0)
continue;
System.out.println( I + “\t”);
}
}

Program Output:

5 10 15 20 25

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 21


Example1:
class IfStatementDemo
{

public static void main(String[] args)


{
int a = 30, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b > a");
}
}

Example 2
class IfElseStatement
{
public static void main(String[] args)
{
int a = 10, b = 20;
if(a > b)
{
System.out.println("a > b");
}
else
{
System.out.println("b > a");
}
}

Example 3
// Assigning Letter Grades Using Multibranch if-else statement

import java.util.Scanner;
class IfNestedDemo
{
public static void main(String[] args)
{
int score;
char grade;
System.out.println("Enter Your score: ");
Scanner keyboard=new Scanner(System.in);
score=keyboard.nextInt();
if (score>=90)
grade='A';
else if(score>=80)
grade='B';
else if(score>=70)
grade='C';
else if(score>=60)

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 22


grade='D';
else
grade='F';
System.out.println("Score = " + score);
System.out.println("Grade = " + grade);
}
}

Example 4
class SwitchCaseDemo
{
public static void main(String[] args)
{
int a = 10, b = 20, c = 30;
int status = -1;
if(a > b && a > c)
{
status = 1;
}
else if(b > c)
{
status = 2;
}
else
{
status = 3;
}

switch(status)
{
case 1:
System.out.println("a is the greatest");
break;
case 2:
System.out.println("b is the greatest");
break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}

Example 5

/*below is an example that creates A Fibonacci sequence controlled by a do-


while loop*/

public class FibonacciDemo


{
public static void main(String[] args)
{
System.out.println("Printing Limited set of Fibonacci Sequence");

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 23


double fib1 = 0;
double fib2 = 1;
double temp = 0;
System.out.println(fib1);
System.out.println(fib2);
do {
temp = fib1 + fib2;
System.out.println(temp);
fib1 = fib2; //Replace 2nd with first number
fib2 = temp; //Replace temp number with 2nd number
} while (fib2 < 5000);
}
}

Example 6
public class ForDemo
{
public static void main(String[] args)
{
int countDown;
for(countDown=3; countDown >= 0; countDown--)
{
System.out.println(countDown);
System.out.println("and counting");
}
System.out.println("Blast off");
}
}

Simple Programs

1. /* Program for simple addition */


import java.io.*;
class prog1
{
public static void main(String args[ ])
{
int a,b,c;
a=5;
b=10;
c=a+b;
System.out.println(“C=”+c);
}
}

2. /* Program to find greatest number */


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

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 24


{
int a,b;
a=5;
b=10;
if (a>b)
System.out.println(“A is Greater”);
else
System.out.println(“B is Greater);
}
}
3. /* Program to print 1 to 10 using for loop*/
import java.io.*;
class prog3
{
public static void main(String args[ ])
{
for(int i=1;i<=10;i++)
System.out.println(“i”);
}
}

4. /* Program to print 1 to 10 using while loop*/


import java.io.*;
class prog4
{
public static void main(String args[ ])
{
int i=1;
while(i<=10)
{
System.out.println(“i”);
i++;
}
}
}

5. /* Program to print 1 to 10 using do..while loop*/


import java.io.*;
class prog5
{
public static void main(String args[ ])
{
int i=1;
do
{
System.out.println(“i”);

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 25


i++;
} while(i<=10);
}
}

6. /* Program to find true or false*/


import java.io.*;
class prog6
{
public static void main(String args[ ])
{
int a=5, b=10;
System.out.println(a>b);
}
}

7. /* Program for type conversion*/


import java.io.*;
class prog7
{
public static void main(String args[ ])
{
int a=5, b;
double c=353.769, d;
d=a;
System.out.println(“Int to Double(Automatic)=”+ d);
b=(int) c;
System.out.println(“Double to Int(External)=”+b);
}
}

8. /* Program for Min, Max value of data types*/


import java.io.*;
class prog8
{
public static void main(String args[ ])
{
System.out.println(“Min value of byte
=”+Byte.MIN_Value);
System.out.println(“Max value of byt
=”+Byte.MAX_Value);
System.out.println(“Min value of Short
=”+Short.MIN_Value);
System.out.println(“Max value of Short
=”+Short.MAx_Value);
System.out.println(“Min value of Long

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 26


=”+Long.MIN_Value);
System.out.println(“Max value of Long
=”+Long.MAx_Value);
System.out.println(“Min value of Int
=”+Integer.MIN_Value);
System.out.println(“Max value of Int
=”+Integer.MAX_Value);
System.out.println(“Min value of Float
=”+Float.MIN_Value);
System.out.println(“Max value of Float
=”+Float.MAX_Value);
System.out.println(“Min value of Double
=”+Double.MIN_Value);
System.out.println(“Max value of Double
=”+Double.MAX_Value);
}

Review questions

1. Define For .. Loop . Give suitable examples.

2. Difference between While & Do .. While loop.

3. Explain Switch .. statement with example

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 27


Chap III. OBJECTS AND CLASSES

3.1 An object - oriented philosophy

Most programming languages provide programmers with a way of describing processes. It has
been said that “one should speak English for business, French for seduction, German for
engineering and Persian for poetry”. A similar quip could be made about programming language.

A fundamental characteristic of object oriented programming is that it allows the base concepts
of the language to be extended to include ideas and terms closer to those of its application. The
fundamental difference between the object oriented system and their traditional counterparts is
the way in which you approach problems.

Most traditional development methodologies are either algorithm centric or data centric. In an
algorithm - centric methodology, you think of an algorithm that can accomplish the task then
build data structure for that algorithm to use. In a data centric methodology you can think how to
structure the data then build the algorithm around that structure.

Objects

The term object means a combination of data and logic that represents some real world entity.
For example, consider a Saab automobile. The Saab can be represents in a computer program as
an object. The “data” part of this object would be the car‟s name, color, number of doors, price
and so forth. The “logic” part of the object could be a collection of the programs. For example
mileage, change mileage, stop, go etc.

Object are grouped in classes

Classes are used to distinguish one type of object from another. In the context object - oriented
systems, a class is a set of objects that share a common structure and common behavior; a single
object is simply an instance of a class. A class is a specification of structure, behavior and
inheritance for objects.

Classes are an important mechanism for classifying objects. The chief role of a class is to define
the properties and procedures and applicability of its instances, there may be many different
classes. Think of a class as an object template. Every object of a given class has the same data
format and responds to the same instructions.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 28


For example, employees, such as Kumar, Ravi and Laks all are instances of the class Employee.
You can create unlimited instances of a given class.

The instructions responded to by each of those instances of employee are managed by class.

3.2 How to design user defined java classes

Class

A class is a collection of objects. A description of a group of objects with same properties.


There are two types of elements of a class:

 A data member is an object of any type


 Member functions (methods) to access or operate on those members

Defining Classes

A class definition is always introduced by the reserved word class. The name of the class is
indicated after the word class.

 The data or variables defined within a class are called instance variables.
 The methods and variables defines within a class are called members.

A Simple Class

A class called Box that defines three instance variables: width, height and depth. Currently, Box
does not contain any methods.

class Box // defining class


{
double width; //
double height; // instance variables
double depth; //
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 29


Declaring Objects

The new operator dynamically allocates (that allocates at run time) memory for an object. Java
supports the objects which are created by new, to destroy automatically and free the memory.

To declare an object of type Box:

Box mybox=new Box(); // allocate a Box object

The first class program

A program that uses the Box Class and one Box objects

class Box {
int width;
int height;
int depth;
}

class BoxProgram {
public static void main(String args[]) {
Box mybox = new Box();
double vol;

//assign values to mybox's instance variables


mybox.width = 5;
mybox.height = 10;
mybox.depth = 15;

//compute volume of box


vol= mybox.width*mybox.height*mybox.depth;
System.out.println("Width = " + mybox.width);
System.out.println("Height = " + mybox.height);
System.out.println("Depth = " + mybox.depth);
System.out.println("Volume = " + vol);
}
}

A program that uses the Box Class and two Box objects:
class Box {
int width;
int height;
int depth;
}

class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 30


//assign values to mybox1's instance variables
mybox1.width = 5;
mybox1.height = 10;
mybox1.depth = 15;

//assign values to mybox2's instance variables


mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

//compute volume of first box


vol= mybox1.width*mybox1.height*mybox1.depth;
System.out.println("Volume = " + vol);

//compute volume of second box


vol= mybox2.width*mybox2.height*mybox2.depth;
System.out.println("Volume = " + vol);
}
}

3.3 Methods
Methods are functions that operate on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other classes. Just as there
are class and instance variables, there are class and instance methods. Instance methods apply
and operate on an instance of the class while class methods operate on the class.

Defining Methods
Method definition has four parts: They are, name of the method, type of object or primitive type
the method returns, a list of parameters and body of the method. Java permits different methods
to have the same name as long as the argument list is different. This is called method
overloading.

Adding method to the Box class

Methods can be defined in the class itself. A method can be called any number of times. The
following program adds a method to the Box class to print the output.

/* Program for class Box with methods */


import java.io.*;

class Box
{
int width;
int height;
int depth;

void show()
{

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 31


System.out.println(“Width=”+ width);
System.out.println(“Height=”+ height);
System.out.println(“Depth=”+ depth);
}

}
class BoxMethods
{
public static void main (String args[ ])
{
Box mybox=new Box();
mybox.width=5;
mybox.height=10;
mybox.depth=15;
mybox.show();
}
}

Output:
Width=5
Height=10
Depth=15

Method with Parameters


Methods can be defined along with the parameters. Parameters allow a method to pass the values
from the calling method. The following program adds a method that takes parameters.

/* Program for class Box with methods and parameters */


import java.io.*;

class Box
{
int width;
int height;
int depth;

void show()
{
System.out.println(“Width=”+width);
System.out.println(“Height=”+height);
System.out.println(“Depth=”+depth);
}

void setvalue(int w, int h, int d)


{

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 32


width=w;
height=h;
depth=d;
}
}

class BoxParams
{
public static void main (String args[ ])
{
Box mybox=new Box();
mybopx.setvalue(1,2,3);
mybox.show();
mybox.setvalue(5,10,15);
mybox.show();
}
}

Output:
Width=1
Height=2
Depth=3

Width=5
Height=10
Depth=15

Overloading Methods
Defining two or more methods within the same class that shares the same name as long as their
parameter declarations are different. The following program uses method overloading to overload
three types of parameter sets.

/* Program for class Box with method overloading */


import java.io.*;

class Box1
{
int width;
int height;
int depth;

void show()
{
System.out.println(“Width=”+width);
System.out.println(“Height=”+height);
System.out.println(“Depth=”+depth);

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 33


}

void setvalue(int w)
{
width=height=depth=w;
}

void setvalue(int w, int h)


{
width=w;
height=h;
depth=30;
}

void setvalue(int w, int h, int d)


{
width=w;
height=h;
depth=d;
}

class BoxMethodOverload
{
public static void main (String args[ ])
{
Box1 mybox=new Box1();
mybopx.setvalue(10);
mybox.show();
mybox.setvalue(10,20);
mybox.show();
mybox.setvalue(100,200,300);
mybox.show();

}
}

Output:
Width=10
Height=10
Depth=10
Width=10
Height=20
Depth=30

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 34


Width=100
Height=200
Depth=300

3.4 Constructors

A constructor method is a special kind of method that determines how an object is initialized
when created. They have the same name as the class and do not have any return type. When the
keyword new is used to create an instance of a class, Java allocates memory for the object,
initializes the instance variables and calls the constructor methods. Constructors can also be
overloaded.

classname()

{
// constructing the class
}

The following program uses a constructor to initialize the dimensions of class Box

/* Program for class Box with constructors */


import java.io.*;

class Box
{
int width;
int height;
int depth;

void show()
{
System.out.println(“Width=”+width);
System.out.println(“Height=”+height);
System.out.println(“Depth=”+depth);
}

Box()
{
width=10;
height=20;
depth=30;
}
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 35


class BoxCons
{
public static void main (String args[ ])
{
Box mybox=new Box();
mybox.show();
}
}

Output:

Width =10
Height=20
Depth=30

Parameterized Constructors
Parameterized constructors are used to set the different values of class members which are
specified by those parameters. The following program shows how parameterized parameters are
used to set the dimension of class Box

/* Program for class Box with constructors and parameters */


import java.io.*;

class Box
{
int width;
int height;
int depth;

void show()
{
System.out.println(“Width=”+width);
System.out.println(“Height=”+height);
System.out.println(“Depth=”+depth);
}

Box( int w, int h, int d)


{
width=w;
height=h;
depth=d;
}
}
class BoxCons

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 36


{
public static void main (String args[ ])
{
Box mybox=new Box(1,2,3);
Box yourbox=new Box(10,20,30);
mybox.show();
yourbox.show();
}
}

Output:

Width =1
Height=2
Depth=3

Width =10
Height=20
Depth=30

Overloading Constructors

The same as method overloading, constructors also overloaded with different set of parameters.
The following program shows the constructor overloading.

//Program for class Box with constructors overloading


import java.io.*;

class Box
{
int width;
int height;
int depth;

void show()
{
System.out.println(“Width=”+width);
System.out.println(“Height=”+height);
System.out.println(“Depth=”+depth);
}
Box()
{
width=10;
height=10;
depth=10;
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 37


Box(int w)
{

width=height=depth=w;
}
Box( int w, int h)
{
width=w;
height=h;
depth=100;
}
Box( int w, int h, int d)
{
width=w;
height=h;
depth=d;
}
}

class BoxCons
{
public static void main (String args[ ])
{
Box mybox1=new Box();
Box mybox2=new Box(50);
Box mybox3=new Box(100,100);
Box mybox4=new Box(100,200,300);
mybox1.show();
mybox2.show();
mybox3.show();
mybox4.show();
}
}

Output:

Width =10
Height=10
Depth=10

Width =50
Height=50
Depth=50

Width =100
Height=100
Depth=100

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 38


Width =100
Height=200
Depth=300

3.5 Static Methods and Variables

Understanding Static Methods and Variables


It is possible to create a member that can be used by itself. To create such a member static is
used. When a member is declared as static, it can be accessed before any objects of its class are
created.

The most common example of a static member is main(). main() is declared as static because it
must be called before any objects exists.

Variables declared as static are like global variables. When objects of class are declared, the
instances of the class share the same name static variable.

The following program shows how static variables and methods are declared.
// demonstrate static variables, methods, and blocks.

import java.io.*;

class UseStatic
{
static int a = 10;
static int b;

static void show()


{
System.out.println("a = " + a);
System.out.println("b = " + b);
}

static
{
System.out.println("Static block initialized.");
b = 20;
}

public static void main(String args[])


{
show();
}
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 39


Output:
a=10
b=20

As soon as the UseStatic class is loaded, all the static statements are run. First a is set to 10, then
the static block executes, and b is set to 20. Then main () is called, which calls the method
show(), it prints the value for a and b.

Using Static outside of the class

 To call a static method from outside its class, classname.method() can be used.
 To call a static member from outside its class, classname.variable can be used.

The following program shows how the static method and static variables called outside of their
class.

/*demonstrate static methods and variables called outside from


the class */
public class StaticDemo {
static int a = 33;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticProg {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Output:
a=33
b=99

Review Questions
1. How can we create classes?
2. What is a method? How can we access a method?
3. What is Overloading? Give examples.
4. What is constructor?
5. Write a java program that illustrates the call of static methods and static variables outside of
their class.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 40


Chap IV: CHARACTERS AND STRINGS

4.1 Characters

The data type used to store characters is char. In Java the range of char is 0 to 65,536. The
standard set of characters known as ASCII ranges 0-127 and extended character set ranges from
0 – 255.

A simple program for char variables:

/* program for char demo*/

import java.io.*;
class chardemo
{
public static void main(String args[])
{
char c=0;
for(int i=0;i<=255;i++)
{
System.out.println("ASCII value for "+c+" is
"+(int) c);
c++;
}
}
}

This program will print the ASCII values from 0 – 255.

Static Methods of Character

Character includes several static methods that categorize characters and alter their case. The
following program demonstrates these methods.

// Demonstrate several Is... methods.


import java.io.*;
class IsDemo
{
public static void main(String args[])
{
char a[] = {'a', 'b', '5', '?', 'A', ' '};

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


if(Character.isDigit(a[i]))
System.out.println(a[i] + " is a digit.");

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 41


if(Character.isLetter(a[i]))
System.out.println(a[i] + " is a letter.");
if(Character.isWhitespace(a[i]))
System.out.println(a[i] + " is whitespace.");

if(Character.isUpperCase(a[i]))
System.out.println(a[i] + " is uppercase.");
if(Character.isLowerCase(a[i]))
System.out.println(a[i] + " is lowercase.");
}
}
}

Output:
a is letter
a is lowercase
b is letter
b is lowercase
5 is digit
A is a letter
A is a uppercase
is a whitespace

4.2 Strings
In Java, a string is a sequence of characters. Java implements strings as object of type String
rather than character arrays. StringBuffer is a companion class to String, whose objects contain
Strings that can be modified.

String and StringBuffer classes are defined in java.lang. Thus they are available to all programs
automatically.

To create an empty string new operator is used.

String S=new String();

String Length

The length of a string is the number of characters that it contains. To obtain this value the int
length() method is used.

char c[]={„a‟,‟b‟,‟c‟};
String s=new String(c);
System.out.println(s.lenght());

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 42


The above fragment prints 3.
String Concatenation

Java allows to chain together a series of + operations. The following fragment concatenates three
strings.

String s1=” Welcomes”;


String s2=”KCT”+s1+” you”;
System.out.println(s2);

This displayes the strings “KCT welcomes you”

Using concat()

To concatenate two strings we can use concat()

String s1=”one”;
String s2=s1.concat(“two”);

This will puts the string “onetwo”

String Comparison

 equals()

To compare two strings for equality, we can use equals ()

String s1=”hai”;
String s2=”hello”;
String s3=”hai”;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));

The output for the above fragment will be

false //where s1 and s2 not equals


true //where s1 and s3 equals

 equalsIgnoreCase()

To compare two strings that ignores case differences, we can use equalsIgnoreCase ()

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 43


String s1=”hai”;
String s2=”HAI”;
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));

The output for the above fragment will be

false //where s1 and s2 not equals (considering case)

true //where s1 and s2 equals (ignoring case)

Searching Strings

The string class provides two methods that allow you to search the specified character or
substring.

 indexOf()
Searches the first occurrence of the character or substring.
 lastIndexOf()
Searches the last occurrence of the character or substring.

String S=”Welcome to the String World in side the Java”;


System.out.println(s.indexOf(„t‟));
System.out.println(s.indexOf(“the”));
System.out.println(s.lastIndexOf(„t‟));
System.out.println(s.lastIndexOf(“the”));

The above fragment will display

8 //„t‟ starts at 8th position


14 // “the” starts at 14th position
36 // „t‟ finishes at 36th position
36 //”the” finishes at 36th position

Modifying String

 replace()

The replace() method replaces all occurrences of one character to a specified one.
String s=”Hello”.replace(„l‟,‟w‟);

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 44


Puts the string “Hewwo” into s.

 trim()

The trim() method returns a copy of string by eliminating leading and trailing whitespaces.

String s=” Hello World “.trim();

Puts the string “Hello World” into s.

Changing Case

 The method toLowerCase() converts all the characters in a sting to lower case
String s=”HELLO WELCOME”;
System.out.println(s.toLowerCase());

This fragment will display “hello welcome”.

 The method toUpperCase() converts all the characters in a sting to upper case
String s=” hello welcome”;
System.out.println(s.toUpperCase());

This fragment will display “HELLO WELCOME”.

String Buffer

StingBuffer is a peer class of String that provides much of the functionality of strings.

 insert()
The insert() method inserts one string into another
StringBuffer sb=new StringBuffer(“I Java”);
sb.insert(2,” like ”);
System.out.println(sb);

This fragment will display “I like Java”.

 delete() and deleteCharAt()


The delete() method deletes a sequence of characters
StringBuffer sb=new StringBuffer(“Welcome to Strings”)
sb.delete(8,10);
System.out.println(sb);

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 45


This fragment will display “Welcome Strings”.

The deletCharAt() method deletes the character by specifying the index


StringBuffer sb=new StringBuffer(“Welcome to Strings”)
sb.deleteCharAt(6);
System.out.println(sb);

This fragment will display “Welcome Strings”.

 reverse()
The reverse() method reverse the characters within the string
StringBuffer sb=new StringBuffer(“Welcome”)
sb.reverse();
System.out.println(sb);
This fragment will display “emocleW”.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 46


Chap. V: ARRAYS

An array is a group of like-typed variables that are referred to by a common name. Arrays of any
type can be created and may have one or more dimensions. A specific element in an array is
accessed by its index. Arrays offer a convenient means of grouping related information.

5.1 One – Dimensional Arrays


Arrays of static allocation declaration
A one-dimensional array is a list of same type of variables. The general form of one-dimensional
array declaration is

type array_name[ ]={values};

Here the type declares the basic type of array. The base type determines the data type of each
element that comprises the array. The following example declares an array named “intarray”
with the type of int.

int intarray[ ]={1,2,3,4,5);

In array, the indexes will be start from 0 and end with (array.length-1). Say for example, to
retrieve the value 3, the subscript used is

Conceptual Diagram for 1D array

Sytem.out.println(intarray[2]);

The above output statement will print 3.

The following program specifies how 1D array are declared with initialization and access those
array elements.

/* program for 1D Arrays */

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

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 47


int intarray[ ]={1,2,3,4,5};
Sytem.out.println(“First Element =”+intarray[0]);
Sytem.out.println(“Second Element =”+intarray[1]);
Sytem.out.println(“Third Element =”+intarray[2]);
Sytem.out.println(“Fourth Element =”+intarray[3]);
Sytem.out.println(“Fifth Element =”+intarray[4]);
}
}

Output:
1
2
3
4
5

Here is one more example that uses one-dimensional arrays

/* Program to calculate average using arrays*/


import java.io.*;

class Average
{
public static void main(String args[])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;

for(i=0; i<5; i++)


result = result + nums[i];

System.out.println("Average is " + result / 5);


}
}

Output:
12.3
Arrays of dynamic allocation declaration

 Dynamic allocation of arrays will be declared by using the new keyword.

 The elements in the array allocated by new will automatically be initialized to zero.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 48


int intarray[ ]=new int[5];

The size of the array can be dynamically received by user input also.

For example
int a;

a will be assigned by some value from the user input now.


int intarray[]=new int[a];

This statement will allocate the array of a size a.

The following program shows how the values been set the array elements

// Demonstrate a one-dimensional array with new.

import java.io.*;
class Array
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + "
days.");
}
}

Output:

April has 30 days.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 49


To get the input from the user

Java is not directly supporting to input the number values by the user. To perform this it has
some indirect methods. The following steps can be made to input a number value from the user.

1. We can use DataInputStream or BufferedReader to get the input.


2. The input values will assign to String variables
3. Using parse method we can convert the strings to required number values

The following program shows how to read the input from the user

// Demonstrate a one-dimensional array with user input.

import java.io.*;
class ArrayInput
{
public static void main(String args[]) throws IOException
{
int n;
String s;
DataInputStream ds=new DataInputStream(System.in);
System.out.println(“Enter the size of the Array=”);
s=ds.readLine();
n=Integer.parseInt(s);
int a[]=new int[n];
System.out.println(“Enter the elements of the Array”);
for(int i=0;i<a.length;i++)
{
s=ds.readLine();
a[i]=Integer.parseInt(s);
}
System.out.println(“The elements of the Array”);
for(int i=0;i<a.length;i++)
System.out.println(a[i]);

}
}

The above program will get the input from the user and according to user specified size the array
will be declared dynamically. According to the values specified by the user, the array will hold
the elements and display the elements.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 50


The same program can be written by using BufferedReader

int a;
String s;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in);
System.out.println(“Enter the size of the Array=”);
s=br.readLine();
a=Integer.parseInt(s);

The above fragment will puts the input value which is entered by the user, into the variable a.

5.2 Multi - Dimensional Arrays

More than one dimensional, the arrays are called as multi-dimensional arrays. In Java multi-
dimensional arrays are actually arrays of arrays.

The following declaration states the two dimensional array

int twoD[ ] [ ]=new int[4] [5];

4 represent the row and 5 represent the column of the array.

Conceptual Diagram for two dimensional arrays

The following program numbers each element in the array from left to right, top to bottom and
displays the values.

// Demonstrate a two-dimensional array.


import java.io.*;
class TwoDArray
{

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 51


public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0;

for(i=0; i<4; i++)


for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}

for(i=0; i<4; i++) {


for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

Output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

Initializing two dimensional arrays

The two dimensional arrays are initialized like one dimensional array with a curly braces. But
here, we use curly braces inside curly braces.

int aa[][]={
{ 1,2,3},
{4,5,6},
{7,8,9}
};

The above declaration initializes the two dimensional arrays with a size of 3x3.

Two dimensional arrays can be initialized with some arithmetic operation like the following
program has.

// Initialize a two-dimensional array.


class Matrix {
public static void main(String args[]) {
double m[][] = {

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 52


{0*0, 1*0, 2*0, 3*0},
{0*1, 1*1, 2*1, 3*1},
{0*2, 1*2, 2*2, 3*2},
{0*3, 1*3, 2*3, 3*3}
};
int i, j;

for(i=0; i<4; i++) {


for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
Output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 53


5.3 Algorithms for Sorting and Searching Arrays

Sorting Arrays

Sorting is the process of putting data in order; either numerically or alphabetically. There
are literally hundreds of different ways to sort arrays. The basic goal of each of these
methods is the same: to compare each array element to another array element and
swap them if they are in the wrong position.

The selection sort

In selection sort during each iteration, the unsorted element with the smallest (or largest) value is
moved to its proper position in the array.

The number of times the sort passes through the array is one less than the number of items in the
array. In the selection sort, the inner loop finds the next smallest (or largest) value and the outer
loop places that value into its proper location.

The following table shows the swap of elements in each iteration. Here each iteration includes
the combination of both loops.

The program (or algorithm) for selection sort:


int [ ] selection_sort(int [ ]array)
{
int i, j, first, temp;
int array_size = array.length( );
for (i=0; i<array.lenth; i++)
{
for (j=i+1; j<a.length; j++) //Find smallest element between the
positions 1 and i.
{
if (array[j] < array[j])
temp = array[i]; //Swap smallest element found

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 54


with one in position i.
array[j] = array[j];
array[j] = temp;
}
}
return array;
}

The following program shows how selection sort can be implemented using class.

//demonstration of selection sort


import java.io.*;
class selection
{
int i,j,temp=0;

int []sortt(int []a)


{
for(i=0;i<a.length;i++)
for(j=i+1;j<a.length;j++)
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
return a;
}
}

class sorting
{
public static void main(String args[])
{
int x[]={84,69,76,86,94,91};
int y[]=new int[x.length];
selection sl=new selection();
y=sl.sortt(x);
for(int s=0;s<y.length;s++)
System.out.println(y[s]);
}
}

Output:
94
91

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 55


86
84
76
69

Searching Arrays

A fast way to search a sorted array is to use a binary search. The idea is to look at the element in
the middle. If the key is equal to that, the search is finished. If the key is less than the middle
element, do a binary search on the first half. If it's greater, do a binary search of the second half.

The program (or algorithm) for binary search:

int AL (int[] array, int seek)


{
int bot = -1;
int top = size;
while (top - bot > 1) {
int mid = (top + bot)/2;
if (array[mid] < seek) bot = mid;
else /* array[mid] >= seek */ top = mid;
}
return top;
}

The implementation of the above algorithm is implemented using class.

//demosntration of binarch algorithm


import java.io.*;
class bsearch
{
int search (int[] array, int seek)
{
int bot = -1;
int top = array[array.length-1];
while (top - bot > 1)
{
int mid = (top + bot)/2;
if (array[mid] < seek) bot = mid;
else top = mid;
}
return top;
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 56


}
class binarysearch
{
public static void main(String args[])
{
int x[]={1,2,3,4,5};
int n=3;
bsearch bs=new bsearch();
int y=bs.search(x,n);
System.out.println("The index of array element
"+n+" = "+y);
}
}

Output:

The index of array element 3 = 2.

Review questions

1 Explain array with examples.


2 Write a program to sort N numbers in ascending order.
3 Write a program to add two matrixes.
4 Write an algorithm for selection sort

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 57


Chap VI: Inheritance

6.1 Inheritance Basics

In java classes can be derived from classes. Basically if you need to create a new class and here
is already a class that has some of the code you require, then it is possible to derive your new
class from the already existing code.

Inheritance is used to inherit the properties from one class to another. The class that is inherited
is called a super class. The class that does inheriting is called a sub class.

The following program creates a super class called A and a subclass B. The keyword extends is
used to create a sub class of A.

// A simple example of inheritance.

// Create a superclass.
class A
{
int i, j; //default access

void showij() {
System.out.println("i and j: " + i + "; " + j);
}
}

// Create a subclass by extending class A.


class B extends A
{
int k;

void showk() {
System.out.println("k: " + k);
}

void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

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

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 58


{
A superOb = new A();
B subOb = new B();

// The superclass may be used by itself.


superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();

System.out.println();

/* The subclass has access to all public, default and


protected members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();

System.out.println("Sum of i, j and k in subOb:");


subOb.sum();
}
}

Output:
Contents of SuperOb:
i and j: 10 20

Contents of SubOb:
i and j: 7 8
k: 9

Sum of I, j and k in subOb:


i+j+k: 24

As you can see, the subclass B includes all of the members of its superclass, A . This is why
subob can access I and j and call showij ( ). Also, inside sum ( ), I and j can be referred to
directly, as if they were part of B. Even though A is a superclass for B, it is also a completely
independent.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 59


6.2 Member Access and Inheritance

Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private . For example, consider the
following simple class hierarchy:
/ * In a class hierarchy, private members remain private to their
class. This program contains an error and will not compile */
// Create a superclass

class A {
int i; // public by default
private int j; // private to A
void setij ( int x, int y) {
i = x;
j = y;

}
}

// A‟s j is not accessible here


class B extends A {
int total ;
void sum ( ) {
total =i + j ; // Error, j is not accessible here
}
}
class Access {
public static void main ( String args[ ] ) {
B subob = new B ( );
subob.setij (10, 12 );
subob.sum( );

System.out.println ( “ Total is “ + subob.total );


}
}
This program will not compile because the reference to j inside the sum( ) method of B causes an
access violation. Since j is declared as private, it is only accessible by other members of its own
class. Subclasses have no access to it.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 60


6.3 Method Overriding

In object oriented terms, overriding means to override the functionality of any existing method.

Example:

Let us look at an example.

class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){


System.out.println("Dogs can walk and run");
}
}

public class TestDog{

public static void main(String args[]){


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class


}
}

This would produce following result:

Animals can move


Dogs can walk and run

In the above example you can see that even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In compile time the check is made on the
reference type. However in the runtime JVM figures out the object type and would run the
method that belongs to that particular object.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 61


Therefore in the above example, the program will compile properly since Animal class has the
method move. Then at the runtime it runs the method specific for that object.

Consider the following example:

class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){


System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}

public class TestDog{

public static void main(String args[]){


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class


b.move();//Runs the method in Dog class
b.bark();
}
}

This would produce following result:

TestDog.java:30: cannot find symbol


symbol : method bark()
location: class Animal
b.bark();
^

This program will throw a compile time error since b's reference type Animal doesn't have a
method by the name of bark.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 62


Rules for method overriding

 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the super class.
 The access level cannot be more restrictive than the overridden method's access level. For
example: if the super class method is declared public then the overriding method in the
sub class cannot be either private or public. However the access level can be less
restrictive than the overridden method's access level.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public
or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overridden method should not
throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden method.
 Constructors cannot be overridden.

Using the super keyword:

When invoking a superclass version of an overridden method the super keyword is used.

class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){


super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 63


public class TestDog{

public static void main(String args[]){

Animal b = new Dog(); // Animal reference but Dog object


b.move();//Runs the method in Dog class

}
}

This would produce following result:

Animals can move


Dogs can walk and run

Examples:1

Example1
// CommissionEmployee class represents a commission employee.
public class CommissionEmployee extends Object {
private String firstName;
private String lastName;
private String socialSecurityNumber;
private double grossSales; // gross weekly sales
private double commissionRate; // commission percentage

// five-argument constructor
public CommissionEmployee(String first, String last, String ssn,
double sales, double rate) {
// implicit call to Object constructor occurs here
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
setGrossSales(sales); // validate and store gross sales
setCommissionRate(rate); // validate and store commission rate
} // end five-argument CommissionEmployee constructor

// set first name


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

// return first name


public String getFirstName() {
return firstName;
} // end method getFirstName

1
Java™ How to Program, Seventh Edition, Deitel Deitel, page 427

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 64


// set last name
public void setLastName(String last) {
lastName = last;
} // end method setLastName

// return last name


public String getLastName() {
return lastName;
} // end method getLastName

// set social security number


public void setSocialSecurityNumber(String ssn) {
socialSecurityNumber = ssn; // should validate
} // end method setSocialSecurityNumber

// return social security number


public String getSocialSecurityNumber() {
return socialSecurityNumber;
} // end method getSocialSecurityNumber

// set commission employee's gross sales amount


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

// return commission employee's gross sales amount


public double getGrossSales() {
return grossSales;
} // end method getGrossSales

// set commission employee's rate


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

// return commission employee's rate


public double getCommissionRate() {
return commissionRate;
} // end method getCommissionRate

// calculate commission employee's pay


public double earnings() {
return commissionRate * grossSales;
} // end method earnings

// return String representation of CommissionEmployee object


public String toString() {
return String.format("%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f",
"commission employee", firstName, lastName,
"social security number", socialSecurityNumber,
"gross sales",
grossSales, "commission rate", commissionRate);
} // end method toString
}// end class CommissionEmployee

Example2

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 65


// Testing class CommissionEmployee.
public class CommissionEmployeeTest {
public static void main(String args[]) {
// instantiate CommissionEmployee object
CommissionEmployee employee = new CommissionEmployee("Habimana",
"John", "222-22-2222", 10000, .06);

// get commission employee data


System.out.println("Employee information obtained by get methods:
\n");
System.out.printf("%s %s\n", "First name is",
employee.getFirstName());
System.out.printf("%s %s\n", "Last name is",
employee.getLastName());
System.out.printf("%s %s\n", "Social security number is",
employee
.getSocialSecurityNumber());
System.out.printf("%s %.2f\n", "Gross sales is", employee
.getGrossSales());
System.out.printf("%s %.2f\n", "Commission rate is", employee
.getCommissionRate());

employee.setGrossSales(500); // set gross sales


employee.setCommissionRate(.1); // set commission rate

System.out.printf("\n%s:\n\n%s\n",
"Updated employee information obtained by toString",
employee);
} // end main
} // end class CommissionEmployeeTest

Example3

// BasePlusCommissionEmployee class represents an employee that


receives
// a base salary in addition to commission.

public class BasePlusCommissionEmployee {


private String firstName;
private String lastName;
private String socialSecurityNumber;
private double grossSales; // gross weekly sales
private double commissionRate; // commission percentage
private double baseSalary; // base salary per week

// six-argument constructor
public BasePlusCommissionEmployee(String first, String last,
String ssn,
double sales, double rate, double salary) {
// implicit call to Object constructor occurs here
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
setGrossSales(sales); // validate and store gross sales

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 66


setCommissionRate(rate); // validate and store commission
rate
setBaseSalary(salary); // validate and store base salary
} // end six-argument BasePlusCommissionEmployee constructor

// set first name


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

// return first name


public String getFirstName() {
return firstName;
} // end method getFirstName

// set last name


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

// return last name


public String getLastName() {
return lastName;
} // end method getLastName

// set social security number


public void setSocialSecurityNumber(String ssn) {
socialSecurityNumber = ssn; // should validate
} // end method setSocialSecurityNumber

// return social security number


public String getSocialSecurityNumber() {
return socialSecurityNumber;
} // end method getSocialSecurityNumber

// set gross sales amount


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

// return gross sales amount


public double getGrossSales() {
return grossSales;
} // end method getGrossSales

// set commission rate


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

// return commission rate


public double getCommissionRate() {

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 67


return commissionRate;
} // end method getCommissionRate

// set base salary


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

// return base salary


public double getBaseSalary() {
return baseSalary;
} // end method getBaseSalary

// calculate earnings
public double earnings() {
return baseSalary + (commissionRate * grossSales);
} // end method earnings

// return String representation of BasePlusCommissionEmployee


public String toString() {
return String.format("%s: %s %s\n%s: %s\n%s: %.2f\n%s:
%.2f\n%s: %.2f",
"base-salaried commission employee", firstName,
lastName,
"social security number", socialSecurityNumber,
"gross sales",
grossSales, "commission rate", commissionRate,
"base salary",
baseSalary);
} // end method toString
} // end class BasePlusCommissionEmployee

Example4
// Testing class BasePlusCommissionEmployee.

public class BasePlusCommissionEmployeeTest


{
public static void main( String args[] )
{
// instantiate BasePlusCommissionEmployee object
BasePlusCommissionEmployee employee =
new BasePlusCommissionEmployee(
"Bob", "Lewis", "333-33-3333", 5000, .04, 300 );

// get base-salaried commission employee data


System.out.println(
"Employee information obtained by get methods: \n" );
System.out.printf( "%s %s\n", "First name is",
employee.getFirstName() );
System.out.printf( "%s %s\n", "Last name is",
employee.getLastName() );

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 68


System.out.printf( "%s %s\n", "Social security number is",
employee.getSocialSecurityNumber() );
System.out.printf( "%s %.2f\n", "Gross sales is",
employee.getGrossSales() );
System.out.printf( "%s %.2f\n", "Commission rate is",
employee.getCommissionRate() );
System.out.printf( "%s %.2f\n", "Base salary is",
employee.getBaseSalary() );

employee.setBaseSalary( 1000 ); // set base salary

System.out.printf( "\n%s:\n\n%s\n",
"Updated employee information obtained by toString",
employee.toString() );
} // end main
} // end class BasePlusCommissionEmployeeTest

Example 5
// BasePlusCommissionEmployee2 inherits from class CommissionEmployee.

public class BasePlusCommissionEmployee2 extends CommissionEmployee


{
private double baseSalary; // base salary per week

// six-argument constructor
public BasePlusCommissionEmployee2( String first, String last,
String ssn, double sales, double rate, double salary )
{
// explicit call to superclass CommissionEmployee constructor
super( first, last, ssn, sales, rate );

setBaseSalary( salary ); // validate and store base salary


} // end six-argument BasePlusCommissionEmployee2 constructor

// set base salary


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

// return base salary


public double getBaseSalary()
{
return baseSalary;
} // end method getBaseSalary

// calculate earnings
public double earnings()
{
// not allowed: commissionRate and grossSales private in superclass
return baseSalary + ( commissionRate * grossSales );
} // end method earnings

// return String representation of BasePlusCommissionEmployee2


public String toString()

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 69


{
// not allowed: attempts to access private superclass members
return String.format(
"%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f\n%s: %.2f",
"base-salaried commission employee", firstName, lastName,
"social security number", socialSecurityNumber,
"gross sales", grossSales, "commission rate", commissionRate,
"base salary", baseSalary );
} // end method toString
} // end class BasePlusCommissionEmployee2

Example 6
// CommissionEmployee2 class represents a commission employee.
// CommissionEmployee2 class represents with protected instance variables

public class CommissionEmployee2 {


protected String firstName;
protected String lastName;
protected String socialSecurityNumber;
protected double grossSales; // gross weekly sales
protected double commissionRate; // commission percentage

// five-argument constructor
public CommissionEmployee2(String first, String last, String ssn,
double sales, double rate) {
// implicit call to Object constructor occurs here
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
setGrossSales(sales); // validate and store gross sales
setCommissionRate(rate); // validate and store commission rate
} // end five-argument CommissionEmployee2 constructor

// set first name


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

// return first name


public String getFirstName() {
return firstName;
} // end method getFirstName

// set last name


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

// return last name


public String getLastName() {
return lastName;
} // end method getLastName

// set social security number

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 70


public void setSocialSecurityNumber(String ssn) {
socialSecurityNumber = ssn; // should validate
} // end method setSocialSecurityNumber

// return social security number


public String getSocialSecurityNumber() {
return socialSecurityNumber;
} // end method getSocialSecurityNumber

// set gross sales amount


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

// return gross sales amount


public double getGrossSales() {
return grossSales;
} // end method getGrossSales

// set commission rate


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

// return commission rate


public double getCommissionRate() {
return commissionRate;
} // end method getCommissionRate

// calculate earnings
public double earnings() {
return commissionRate * grossSales;
} // end method earnings

// return String representation of CommissionEmployee2 object


public String toString() {
return String.format("%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f",
"commission employee", firstName, lastName,
"social security number", socialSecurityNumber,
"gross sales",
grossSales, "commission rate", commissionRate);
} // end method toString
} // end class CommissionEmployee2

Example 7
// BasePlusCommissionEmployee3 inherits from CommissionEmployee2 and has
// access to CommissionEmployee2's protected members.

public class BasePlusCommissionEmployee3 extends CommissionEmployee2 {


private double baseSalary; // base salary per week

// six-argument constructor
public BasePlusCommissionEmployee3(String first, String last, String
ssn,
double sales, double rate, double salary) {

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 71


super(first, last, ssn, sales, rate);
setBaseSalary(salary); // validate and store base salary
} // end six-argument BasePlusCommissionEmployee3 constructor

// set base salary


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

// return base salary


public double getBaseSalary() {
return baseSalary;
} // end method getBaseSalary

// calculate earnings
public double earnings() {
return baseSalary + (commissionRate * grossSales);
} // end method earnings

// return String representation of BasePlusCommissionEmployee3


public String toString() {
return String.format("%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f\n%s:
%.2f",
"base-salaried commission employee", firstName,
lastName,
"social security number", socialSecurityNumber,
"gross sales",
grossSales, "commission rate", commissionRate, "base
salary",
baseSalary);
} // end method toString
} // end class BasePlusCommissionEmployee3

Example 8
// Testing class BasePlusCommissionEmployee3.

public class BasePlusCommissionEmployeeTest3


{
public static void main( String args[] )
{
// instantiate BasePlusCommissionEmployee3 object
BasePlusCommissionEmployee3 basePlusCommissionEmployee =
new BasePlusCommissionEmployee3(
"Bob", "Lewis", "333-33-3333", 5000, .04, 300 );

// get base-salaried commission employee data


System.out.println(
"Employee information obtained by get methods: \n" );
System.out.printf( "%s %s\n", "First name is",
basePlusCommissionEmployee.getFirstName() );
System.out.printf( "%s %s\n", "Last name is",
basePlusCommissionEmployee.getLastName() );
System.out.printf( "%s %s\n", "Social security number is",
basePlusCommissionEmployee.getSocialSecurityNumber() );
System.out.printf( "%s %.2f\n", "Gross sales is",

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 72


basePlusCommissionEmployee.getGrossSales() );
System.out.printf( "%s %.2f\n", "Commission rate is",
basePlusCommissionEmployee.getCommissionRate() );
System.out.printf( "%s %.2f\n", "Base salary is",
basePlusCommissionEmployee.getBaseSalary() );

basePlusCommissionEmployee.setBaseSalary( 1000 ); // set base salary

System.out.printf( "\n%s:\n\n%s\n",
"Updated employee information obtained by toString",
basePlusCommissionEmployee.toString() );
} // end main
} // end class BasePlusCommissionEmployeeTest3

Example 9
// CommissionEmployee3 class represents a commission employee.

public class CommissionEmployee3 {


private String firstName;
private String lastName;
private String socialSecurityNumber;
private double grossSales; // gross weekly sales
private double commissionRate; // commission percentage

// five-argument constructor
public CommissionEmployee3(String first, String last, String ssn,
double sales, double rate) {
// implicit call to Object constructor occurs here
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
setGrossSales(sales); // validate and store gross sales
setCommissionRate(rate); // validate and store commission rate
} // end five-argument CommissionEmployee3 constructor

// set first name


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

// return first name


public String getFirstName() {
return firstName;
} // end method getFirstName

// set last name


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

// return last name


public String getLastName() {
return lastName;
} // end method getLastName

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 73


// set social security number
public void setSocialSecurityNumber(String ssn) {
socialSecurityNumber = ssn; // should validate
} // end method setSocialSecurityNumber

// return social security number


public String getSocialSecurityNumber() {
return socialSecurityNumber;
} // end method getSocialSecurityNumber

// set gross sales amount


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

// return gross sales amount


public double getGrossSales() {
return grossSales;
} // end method getGrossSales

// set commission rate


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

// return commission rate


public double getCommissionRate() {
return commissionRate;
} // end method getCommissionRate

// calculate earnings
public double earnings() {
return getCommissionRate() * getGrossSales();
} // end method earnings

// return String representation of CommissionEmployee3 object


public String toString() {
return String.format("%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f",
"commission employee", getFirstName(), getLastName(),
"social security number", getSocialSecurityNumber(),
"gross sales", getGrossSales(), "commission rate",
getCommissionRate());
} // end method toString
} // end class CommissionEmployee3

Example 10
// BasePlusCommissionEmployee4 class inherits from CommissionEmployee3 and
// accesses CommissionEmployee3's private data via CommissionEmployee3's
// public methods.

public class BasePlusCommissionEmployee4 extends CommissionEmployee3 {


private double baseSalary; // base salary per week

// six-argument constructor

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 74


public BasePlusCommissionEmployee4(String first, String last, String
ssn,
double sales, double rate, double salary) {
super(first, last, ssn, sales, rate);
setBaseSalary(salary); // validate and store base salary
} // end six-argument BasePlusCommissionEmployee4 constructor

// set base salary


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

// return base salary


public double getBaseSalary() {
return baseSalary;
} // end method getBaseSalary

// calculate earnings
public double earnings() {
return getBaseSalary() + super.earnings();
} // end method earnings

// return String representation of BasePlusCommissionEmployee4


public String toString() {
return String.format("%s %s\n%s: %.2f", "base-salaried", super
.toString(), "base salary", getBaseSalary());
} // end method toString
} // end class BasePlusCommissionEmployee4

Example 11
// Testing class BasePlusCommissionEmployee4.
public class BasePlusCommissionEmployeeTest4 {
public static void main(String args[]) {
// instantiate BasePlusCommissionEmployee4 object
BasePlusCommissionEmployee4 employee = new
BasePlusCommissionEmployee4(
"Bob", "Lewis", "333-33-3333", 5000, .04, 300);

// get base-salaried commission employee data


System.out.println("Employee information obtained by get methods:
\n");
System.out.printf("%s %s\n", "First name is",
employee.getFirstName());
System.out.printf("%s %s\n", "Last name is",
employee.getLastName());
System.out.printf("%s %s\n", "Social security number is",
employee
.getSocialSecurityNumber());
System.out.printf("%s %.2f\n", "Gross sales is", employee
.getGrossSales());
System.out.printf("%s %.2f\n", "Commission rate is", employee
.getCommissionRate());
System.out.printf("%s %.2f\n", "Base salary is", employee
.getBaseSalary());

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 75


employee.setBaseSalary(1000); // set base salary

System.out.printf("\n%s:\n\n%s\n",
"Updated employee information obtained by toString",
employee
.toString());
} // end main
} // end class BasePlusCommissionEmployeeTest4

6.4 Abstract class

An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its
fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance
of the abstract class.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclassed.
This is typically how abstract classes come about during the design phase. A parent class contains the
common functionality of a collection of child classes, but the parent class itself is too abstract to be used
on its own.

Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration
somewhere before the class keyword.

Examples:
Example 1:

Here is a simple example of a class with an abstract method, followed by a class which implements that
method:

// A simple demonstration of abstract


abstract class A {
abstract void callme( );
// concrete methods are still allowed in abstract classes
void Callmetoo ( ) {
System.out.println ( “ This is a concrete method “ );
}
}
class B extends A {
void callme ( ) {
System.out.,println (“ B‟s implementation of callme. “ );
}
}
class AbstractDemo {

public static void main ( String args[ ] ) {


B b = new B ( );
b. callme ( );

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 76


b.callmetoo( );
}
}

Notice that no objects of class A are declared in the program. As mentioned, it is not possible to
instantiate an abstract class. One other point: class A implements a concrete method called callmetoo( ).
This is perfectly acceptable. Abstract classes can include as much implementation as they see fit.
Although abstract classes cannot be used to instantiate objects, they can be used to create object
references, because Java‟s approach to run-time polymorphism is implemented through the use of
superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be
used to point to a subclass object.

Example 2:
public abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name+ " " +
this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 77


address = newAddress;
}
public int getNumber()
{
return number;
}
}

Notice that nothing is different in this Employee class. The class is now abstract, but it still has
three fields, seven methods, and one constructor.

Now if you would try as follows:

/* File name : AbstractDemo.java */


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

/* Following is not allowed and would raise error */


Employee e = new Employee("George W.", "Houston, TX", 43);

System.out.println("\n Call mailCheck using Employee reference--");


e.mailCheck();
}
}

When you would compile above class then you would get following error:

Employee.java:46: Employee is abstract; cannot be instantiated


Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error1

Practical example

In this program, you have:

 Wolves
 Dogs
 Cats
 Lions
 Tigers.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 78


Those animals have some common properties, and if they common properties, there is
inheritance.

Hence we have a super class, let‟s call it Animal:

Note: in UML the abstract class is italicized

Before coding we have to illustrate what we know.

 Our targets will have a different color and weight. Our classes will have the right to
change these.
 Here, we assume that all our animals eat meat and drink water. The methods eat () and
drink will be defined in the Animal class
 They won‟t cry and move the same way. We will therefore create and declare
polymorphic abstract methods cry () and movement () in the class Animal.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 79


Here a model of our classes:

We can improve a little this architecture, without going into details.

We could have done a subclass carnivore, or Pet and Wild Animal. Her we can consider two subclasses
Canine and Feline that will inherit from Animal and from which our objects inherit. We will redefine
the displacement method () in this class because we will assume that felines and canines move
differently.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 80


Here is the final diagram

Here is the corresponding java code:


abstract class Animal {
/**
* The color of animal
*/
protected String color;
/**
* The weight
*/
protected int weight;

/**
* The method eat
*/
protected void eat() {
System.out.println("I eat meat");
}
/**
* The method drink
*/
protected void drink() {
System.out.println("I drink water !");
}

/**
* The method movement
*/
abstract void movement();

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 81


/**
* The method cry
*/
abstract void cry();

public String toString() {

String str = "I am an object of The " + this.getClass() + ", I am


"
+ this.color + ", I weigh " + this.weight;
return str;
}
}

public abstract class Feline extends Animal {


void movement() {
System.out.println("I move alone !");
}
}

public abstract class Canine extends Animal {

void movement() {
System.out.println("I travel in packs!");
}
}

public class Dog extends Canine {


public Dog(){
System.out.println("Dog race");
System.out.println("---------");
System.out.println("");
}
public Dog(String color, int weight){
this.color = color;
this.weight = weight;
}
void cry() {
System.out.println("I bark without reason! ");
}
}

public class Wolf extends Canine {


public Wolf(){
System.out.println("Wolf race");
System.out.println("---------");
System.out.println("");
}
public Wolf(String color, int weight){
this.color = color;
this.weight = weight;
}
void cry() {
System.out.println("I howl at the moon by making ouhouh ! ! ");
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 82


}

public class Lion extends Feline {


public Lion(){
System.out.println("Lion race");
System.out.println("---------");
System.out.println("");
}
public Lion(String c, int w){
this.color = c;
this.weight = w;
}

void cry() {
System.out.println("I roar in savanna !");

public class Cat extends Feline {


public Cat(){
System.out.println("Cat race");
System.out.println("---------");
System.out.println("");
}public Cat(String color, int weight){
this.color = color;
this.weight = weight;
}

void cry() {
System.out.println("I meows over the roofs !");
}
}

public class Tiger extends Feline {


public Tiger(){
System.out.println("Tiger race");
System.out.println("---------");
System.out.println("");
}
public Tiger(String color, int weight) {
this.color = color;
this.weight = weight;
}

void cry() {
System.out.println("I growl too loud !");
}
}

class TestAnimal {
public static void main(String[] args) {
Wolf w = new Wolf("bluish gray", 20);
Wolf wol=new Wolf();

w.drink();

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 83


w.eat();
w.movement();
w.cry();

System.out.println(w.toString());
System.out.println("");

Tiger t = new Tiger("Yellow and Marron", 20);


Tiger tig=new Tiger();

t.drink();
t.eat();
t.movement();
t.cry();

System.out.println(w.toString());
System.out.println("");

Cat c = new Cat("Yellow and Marron", 20);


Cat ca=new Cat();

c.drink();
c.eat();
c.movement();
c.cry();

System.out.println(w.toString());
System.out.println("");
}
}

6.5 Encapsulation

Encapsulation is one of the four fundamental OOP (Object Oriented Programming) concepts. The other
three are inheritance, polymorphism, and abstraction.
Encapsulation is the technique of making the fields in a class private and providing access to the fields via
public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby
hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the
code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and
extensibility to our code.

Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */


public class EncapTest{
private String name;
private String idNum;
private int age;

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 84


public int getAge(){
return age;
}

public String getName(){


return name;
}

public String getIdNum(){


return idNum;
}

public void setAge( int newAge){


age = newAge;
}

public void setName(String newName){


name = newName;
}

public void setIdNum( String newId){


idNum = newId;
}
}

The public methods are the access points to this class.s fields from the outside java world.
Normally these methods are referred as getters and setters. Therefore any class that wants to
access the variables should access them through these getters and setters.

The variables of the EncapTest class can be access as below:


/* File name : RunEncap.java */
public class RunEncap {
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James GaTARAYIHA");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName()+


", Age : "+ encap.getAge()+", Id Number:
"+encap.getIdNum());
}
}

This would produce following result:

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 85


Access Control
Access control is controlling visibility of a variable or method. When a method or variable is
visible to another class, its methods can reference the method or variable. There are four levels of
visibility that are used. Each level is more restrictive than the other and provides more protection
than the one preceding it.

Public
Any method or variable is visible to the class in which it is defined. If the method or variable
must be visible to all classes, then it must be declared as public. A variable or method with
public access has the widest possible visibility. Any class can use it.

Package
Package is indicated by the lack of any access modifier in a declaration. It has an increased
protection and narrowed visibility and is the default protection when none has been specified.

Protected
This access specifier is a relationship between a class and its present and future subclasses. The
subclasses are closer to the parent class than any other class. This level gives more protection
and narrows visibility.

Private
It is narrowly visible and the highest level of protection that can possibly be obtained. Private
methods and variables cannot be seen by any class other than the one in which they are defined.
They are extremely restrictive but are most commonly used. Any representation unique to the
implementation is declared private. An object‟s primary job is to encapsulate its data and limit
manipulation. This is achieved by declaring data as private.

Review Questions

1. Explain basic concepts of inheritance with example.


2. Explain the accessibility of the various access modifiers in Java.
3. It is possible to override overloaded methods. Why?

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 86


Chap VII: Package and interface

7.1 Packages
In the preceding lesson, the name of each example class was taken from the same name space.
This means that a unique name had to be used for each class to avoid name collisions. After a
while, without some way to manage the name space, you could run out of convenient, descriptive
names for individual classes. You also need some way to be assured that the name you choose
for a class will be reasonably unique and not collide with class names chosen by other
programmers. (Imagine a small group of programmers fighting over who gets to use the name
“Foobar” as a class name. Or, imagine the entire Internet community arguing over who first
named a class “Espresso.”) Thankfully, Java provides a mechanism for partitioning the class
name space into more manageable chunks. This mechanism is the packages. The package is both
a naming and a visibility control mechanism. You can define classes inside a package that are
not accessible by code outside that package. You can also define class members that are only
exposed to other members of the same package. This allows your classes to have intimate
knowledge of each other, but not expose that knowledge to the rest of the world.

Defining a Package
To create a package is quite easy: simply include a package command as the first statement in Java
source file. Any class declared within that file will belong to the specified package. The package
statement defines a name space in which classes are stored. If you omit the package statement, the class
names are put into the default package, which has no name. (This is why you haven‟t had to worry about
packages before now). While the default package is fine for short, sample programs, it is inadequate for
real applications. Most of the time, you will define a package for your code.
This is the general form of the package statement:

Package pkg
Here, pkg is the name of the package.

For examples, the following statement creates a package called MyPackage.

Package MyPackage

You can create a hierarchy of package. To do so, simply separate each package name from the one above
it by use of a period. The general form of a multileveled package statement is shown here:
Package pkg1[.pkg2 [.pkg3 ] ];
A package hierarchy must be reflected in the file system of your Java development system. For example,
a package declared as
package java.awt.image;

needs to be stored in java/awt/image, java\ awt \image, or java:awt:image on your UNIX, Windows, or
Macintosh file system, respectively. Be sure to choose your package names carefully. You cannot rename
a package without renaming the directory in which the classes are stored.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 87


A short package example:

// A simple package
package MyPack;

class Balance {
String name;
double bal;

Balance(String n, double b) {
name = n;
bal = b;
}

void show() {
if (bal < 0)
System.out.print("à");
System.out.println(name + " : $ " + bal);
}
}

class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K . J . Fielding ", 123.23);
current[1] = new Balance("Will Tell ", 157.02);
current[2] = new Balance(" Tom Jackson", -12.33);
for (int I = 0; I < 3; I++)
current[I].show();
}
}

Access Protection

Package adds another dimension to access control. As you will see, Java provides many level of
protection to allow fine-grained control over the visibility of variables and methods within classes,
subclasses, and package.

Packages act as containers for classes and other subordinate packages. Classes act as containers for data
and code. The class is Java‟s smallest unit of abstraction. Because of the interplay between classes and
package, Java addresses four categories of visibility for class member:
 Subclasses in the same package
 Non-subclasses in the same package
 Subclasses in different package
 Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected a variety of ways to produce the many levels
of access required by these categories.

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 88


While Java‟s access control mechanism may be seen complicated, we can simplify it as follows. Anything
declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its
class. When a member does not have an explicit access specification, it is visible to subclasses as well as
to other classes in the same package. This is the default access. If you want to allow an element to be
seen outside your current package, put only to classes that subclass your class directly, then declare that
element protected.
No
Private Protected Public
modifier
Same class Yes Yes Yes Yes
Same package
No Yes Yes Yes
subclass
Same package
No Yes Yes Yes
non-subclass
Different package
No No Yes Yes
subclass
Different package
No No No Yes
non-subclass

When a class is declared as public, it is accessible by any other code. If a class has default access, then it
can only be accessed by other code within its same package.

An Access Example
The following example shows all combination of the access control modifiers. This example has two
packages and five classes.
The source for the first package p1 defines three classes: Protection, Derived and SamePackage. The first
class (protection) defines four int variables in each of the legal protection modes. The variable n is
declared with the default protection. n_pri is private, n_pro is protected, and n_pub is public.

The second class, Derived, is a subclass of protection in the same package, p1. This grants Derived access
to every variable in protection except for n_pri, the private one. The third class, SamePackage, is not a
subclass of Protection, but is in the same package and also has access to all but n_pri.

This is file Protection.java:

package p1;

public class Protection {


int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;

public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 89


System.out.println("n_pub = " + n_pub);
}
}

This is file Derived.java:


package p1;

public class Derived extends Protection {


Derived() {
System.out.println("derived constructor ");
System.out.println("n = " + n);

//n_pri is only accessible in protection class


//System.out.println ("n_pri = " + n_pri ) ;
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
This is file SamePackage.java:
package p1;

public class SamePackage {


SamePackage() {
Protection p = new Protection();
System.out.println(" same package constructor ");
System.out.println("n = " + p.n);
// class only
// System.out.println ( “n_pri = “ +p.n_pri ) ;
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}

Following is the source code for the other package, p2. The two classes defined in p2 cover the other two
condition which are affected by access control . The first class, Protection2, is a subclass of p1.Protection.
This grants access to all of p1.Protection‟s variables except for n_pri (because it is private) and n, the
variable declared with the default protection. Remember, the default only allows access from within the
classes or the package, not extra-package subclass. Finally, the class OtherPackage has access to only one
variable, n_pub which was declared public.
This is file Protection2.java:
package p2;

import p1.Protection;

public abstract class Protection2 extends Protection {


Protection2() {
System.out.println("derived other package constructor ");
// class or package only
// System.out.println ( “n = “ + n )
// class only
// System.out.println ( “n_pri = “ + n_pri ) ;
System.out.println("n_pro = " + n_pro);

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 90


System.out.println("n_pub = " + n_pub);
}
}

This is file OtherPackage.java:


package p2;

public class OtherPackage {


OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println(" other package constructor ");
// class or package only
// System.out..println (“n = “ + p.n) ;
// class only
// System.out..println (“n_pri = “ + p. n_pri) ;
// class , subclass or package only
// System.out..println (“n_pro = “ + p.n_pro) ;
System.out.println("n_pub = " + p.n_pub);
}
}

If you wish to try these two packages, here are two test files you can use. The one for package p1 is
shown here:
// Demo package p1 .
package p1;

// Instantiate the various classes in p1


public class Demo {
public static void main(String arg[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();

}
}

The test file p2 is shown next:


// Demo package p2 .
package p2;

// Instantiate the various classes in p2


public class Demo {
public static void main(String arg[]) {
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}

Importing Packages
Given that packages exist and are a good mechanism for compartmentalizing diverse classes from each
other, it is easy to see why all of the built-in Java classes are stored in packages. There are no core Java
classes in the unnamed default package; all of the standard classes are stored in some named packages.
Since classes within packages must be fully qualified with their package name or names, it could become

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 91


tedious to type in the long dot-separated package path name for every class you want If you are going to
refer to a few dozen classes in your application, however, the import statement will save a lot of typing.
In a Java source file, import statement occurs immediately following the package statement (if it exists)
and before any class definition. This is the general form of the import statement:

import pkg1 [ .pkg2 ].(classname|*);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the
outer package hierarchy, except that imposed by the file system.

Finally, you specify either an explicit classname or a star ( * ), which indicates that the Java compiler
should import the entire package. The following code fragment shows both forms in use:
import java.util.Date; // specification of Date class in util package
import java.io.*;

All the standard Java classes included with Java are stored in a package called java. The basic language
functions are stored in a package inside of the java package called java.lang.

If a class with the same name exists in two different packages that you import using the star form, the
compile will remain silent, unless you try to use one of the classes. In that case, you will get a compiler-
time error and have to explicitly name the class specifying its package.
Any place you use a class name, you can use its fully qualified name, which includes its full package
hierarchy. For examples, this fragment uses an import statement:
import java.util.*;
class MyDate extends Date { }
The same example without the import statement looks like this:
Class MyDate extends java.util.Date { }

When a package is imported, only those items within the package declared as public will be available to
non-subclasses in the importing code. For example, if you want the Balance class of the package MyPack
shown earlier (page 16) to be available as a stand-alone class for general use outside of MyPack, then you
will need to declare it as public and put it into own file, as shown here:

Example

package MyPack;

/* Now the Balance class, its constructor, and its show ( ) method are
public. This means that they can be used by non-subclass code outside their
package .
*/// A simple package
public class Balance {
String name;
double bal;

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 92


public Balance(String n, double b) {
name = n;
bal = b;
}

public void show() {


if (bal < 0)
System.out.print("- - >");
else
System.out.println(name + " : $ " + bal);
}
}

As you can see, the Balance class is now public. Also, its constructor and its show() method are public,
too This means that they can be accessed by ant type of code outside the MyPack package. For examples,
here TestBalance import MyPack and is then able to make use the Balance class:
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/*
* Because Balance is public, you may use Balance class Copyright
* © 2011
* Kicukiro College of Technology and call its constructor .
*/
Balance test = new Balance("Habimana J.Jaspers", 99.88);
test.show(); // you may also call show()
}
}

7.2 Interfaces

In Java language an interface can be defined as a contract between objects on how to


communicate with each other. Interfaces play a vital role when it comes to the concept of
inheritance.

An interface defines the methods, a deriving class (subclass) should use. But the implementation
of the methods is totally up to the subclass.

An interface is a collection of abstract methods. A class implements an interface, thereby


inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.

An interface is similar to a class in the following ways:

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 93


 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The bytecode of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

 You cannot instantiate an interface.


 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:

Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is tightly
controlled by an interface.

Interfaces have the following properties:

An interface is implicitly abstract. You do not need to use the abstract keyword when declaring
an interface.

 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.

Example:
/* File name : Animal.java */
interface Animal {

public void eat();


public void travel();
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 94


Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements cause in a class definition, and then create the
method defined by the interface. The general form of a class that includes the implements clause
looks like this:
access class classname [ extends superclass ]
[ implements interface [, interface .. ] ] {
// class-body
}
Here, access is either public or not used. If a class implements more than one interface, the
interface are separated with a comma. If a class implements two interface that declare the same
method, then the same method will be used by client of either interface. The method that
implements an interface must be declared public. Also, the type signature of the implementing
method must match exactly the type signature specified in the interface definition.

Example:
interface Callback {
void callback ( int param ) ; }

class Client implements Callback {


// Implements Callback‟s interface public void callback ( int
p ) {
System.out.println ( “ callback called with “ + p ) ;
}
}

Notice that callback( ) is declared using the public access specifier.

It is both permissible and common for classes that implement interface to define additional
member of their own. For example, the following version of Client implements callback ( ) and
adds the method nonIface Meth( ) :
class Client implements Callback {
// Implement Callback‟s interface
public void callback ( int p ) { System.out.println (
“callback called with “ + p ) ;
}
void nonIfaceMeth ( ) {
System.out.println ( “ Classes that implement
interface “ + “ may also define other member, too .” )
;
}
}

By : BENIMANA PASCAL KICUKIRO COLLEGE OF TECHNOLOGY 95

S-ar putea să vă placă și