0% found this document useful (0 votes)
4 views55 pages

Java Programming - Basics

This document provides an introduction to object-oriented programming, emphasizing the concepts of objects, classes, methods, and data types in Java. It explains the structure of Java applications, the process of compiling and interpreting code, and the use of comments and data input/output methods. Additionally, it covers variable declaration, initialization, and the Scanner class for user input.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views55 pages

Java Programming - Basics

This document provides an introduction to object-oriented programming, emphasizing the concepts of objects, classes, methods, and data types in Java. It explains the structure of Java applications, the process of compiling and interpreting code, and the use of comments and data input/output methods. Additionally, it covers variable declaration, initialization, and the Scanner class for user input.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING

This is a programming style in which, we try to replicate what is obtainable in reality (physical plane) in a computing
environment. Main points to note include:
1. Objects exist in the physical plane e.g. person, table etc.
2. These objects have attributes/traits e.g. name, height, age etc.
3. These traits can be given values e.g. John, 6.3m, 46years etc.
4. Objects interact with each other, using their abilities.

When creating the digital versions of these objects the most essential attributes and abilities are used to create them. This
focus on only the essentials is termed ABSTRACTION.

WHERE TO FIND PREDEFINED PROGRAMMING TOOLS (DATA & METHOD)


The terms below are very essential when discussing the subject matter above.
1. CLASS: template describing what should be contained in an object when it is created. It is similar to the plan of a
building.
2. OBJECT: an INSTANCE of a class. It is similar to the building erected, following the details in the plan.
3. METHOD: a set of instructions that perform a task or tasks, when executed, especially those that can be done
repeatedly. A method is the same as a function in C programming.

When putting together a class for a given family of objects, data represents attributes of the objects, while methods represent
abilities of these objects.

Predefined programming tools can only be found in predefined classes, and in terms of structure or organization,
 data and methods form a class
 classes form a package
 packages form a module.

This is as shown below:


Data/Methods  Class  Package  Module

Data/Method are either gotten from the class or an object created from the class. Those gotten from the class are CLASS or
STATIC data/methods, while those gotten from the object are called OBJECT or INSTANCE data/methods.

Creating an object of a class is called INSTANTIATION, and it is done with special methods called a CONSTRUCTORS.

IDENTIFIERS
An identifier is the programming term for a name. Objects in the physical plane or reality have names. Their digitals versions
are not different.
An identifier (a valid one) is any combination of 1 or more characters taken from the alphabets (a – z, A-Z), digits (0 – 9),
underscore (_), or the dollar ($) that doesn’t begin with a digit. Examples are: x, y, radius, mass1, first_name etc.
BASIC PROGRAM (APPLICATION) TEMPLATE
Important points to note include:
1. A statement in Java is terminated by a semi-colon.
2. Using predefined data or method requires providing the class that contains it.
3. import [Link]; is the statement that provides the content (data & method) of the class (parent)
specified.
4. import packageName.*; is used to provide the content of all classes in the package specified.
5. The contents of the classes from the package [Link] are available by default, hence their usage doesn’t require
using an import statement. This implies that import statements aren’t compulsory.

Application template is given below:

import [Link];
import packageName.*;

public class ClassName{


public static void main(String[] args){

}
}

NOTE
1. The name of a class must start with an uppercase alphabet
2. Applications are classes that can be executed (are runnable).
3. A class is only an application, if contains the main-method.
4. Saving the file after typing the program requires: Application name, and .java as extension i.e. [Link].
5. In a program, predefined data and method are written as:
 [Link] & [Link](…)  Static or class tools
 [Link] & [Link](…)  Instance or object tools

FROM PROGRAM SOURCE FILE TO PROGRAM OUTPUT


 [Link] gets compiled by the Java compiler to [Link] (BYTECODE).
 [Link] gets interpreted by JVM (Java Virtual Machine) to give the program output.

POINTS TO NOTE:
1. Java like English, has rules followed when writing.
2. When a program is written in such a way that one or more of these rules are broken, it is said to have SYNTAX
ERROR(S).
3. [Link] (Source file) compiled successfully produces [Link] (ByteCode). This is most obvious on a
PC.
4. [Link] interpreted by JVM gives the program output.
5. [Link] will only be compiled if it has no syntax error.
6. From (3) and (4), it is clear that, Java as a language, is both compiled and interpreted.
7. There is a version of JVM for any type of system (platform) available. This ensures that a Java program output
remains the same from system to system, irrespective of the system on which it was written and compiled on
8. Java is said to be PLATFORM INDEPENDENT because of (7) and this is one of its major selling points, when
compared to other programming languages.
COMMENTS
These are explanatory notes added to a program when writing. Comments are skipped by the compiler during compilation
because they are meant for man (programmers), not machine. There are 3 types in Java, which are:
1. Single-line comment
// Comment

2. Multi-line comment
/*Comment
Comment
:
Comment*/

3. JavaDoc Comments: Multi-line comments used for producing Java documentation about a program.
/**Comment
Comment
:
Comment*/

TYPES OF DATA
Integral Type (Whole Numbers)

SN Type Size (Bytes) Range Examples


1 byte 1 (8 bits) -128  127 34, -24
2 short 2 (16 bits) -32768  32767 34, 129, -130
3 int 4 (32 bits) -2147483648  2147483647 32768, -32769
4 long 8 (64 bits) -9223372036854775808  9223372036854775807 23l, 45L, -32l, -87L
5 char 2 (16 bits) Decimal: 0  65635 Symbolic
3-digit Octal: 0  377 ‘#’, ‘5’
4-digit Hexadecimal: 0000  FFFF Numeric
Base 10: 64, 62
Base 8: ‘\377’
Base 16: ‘\u00A5’, ‘\U00A5’

NOTES
1. Codes are used to present characters with symbols that can’t be found on a keyboard.
2. Lower bound of the range = -(2bits-1), and 20 for char
3. Upper bound of the range = (2bits-1 – 1) and (2bits – 1) for char

Real Numbers
SN Type Size (Bytes) Range Examples
-45 38
1 float 4 (32 bits) Negative: -1.4 x 10  -3.4028235 x 10 2.45f, -0.324F, 1.2e-14f,
Positive: 1.4 x 10-45  3.4028235 x 1038 -2.4E-19F
-324 308
2 double 8 (64 bits) Negative: -4.9 x 10  -1.7976931348623157 x 10 2.45, -0.324, 2.3e-23, 1.234E12
Positive: 4.9 x 10-324  1.7976931348623157

boolean
Values: true, false

String (Class): 0 or more characters


Values: “453”, “4orm”, “#Grace”, “\u00b5, “”, “\u00A5349” (equivalent to ¥349)
DATA OUTPUT TO SCREEN
USING METHODS FROM [Link]
1. [Link](data); displays the cursor immediately after the data (same line)
Example Folder before compiling Folder after compiling Output
1 public class Experiments{
2 public static void main(String[] args){
3 [Link]("Hello ");
4 [Link]("world!!!");
5 }
6 }

2. [Link](data);  displays the cursor on a new line below the data


Example
1 public class Test {
2 public static void main(String[] args) {
3 [Link]("Hello");
4 [Link]("world");
5 }
6 }

Output

3. [Link](“Format_String”[, data, data, …, data]);  in terms of usage, it is identical to


printf(…) you were taught in C programming, and the portion in square brackets is optional, because it is only present,
if the format string contains one or more placeholders representing mostly data that is unknown at the time of writing. A
quick rundown of placeholders is given below:
a. %d (Base 10 integer)
[Link]("%d", 10);  10

b. %o (Base 8 integer)
[Link]("%o", 10);  12

c. %x (Base 16 integer with alphabets in lowercase)


[Link]("%x", 10);  a

d. %X (Base 16 integer with alphabets in uppercase)


[Link]("%X", 10);  A

e. %c (Single character)
[Link]("%c", '#');  #
[Link]("%c", 64);  @
[Link]("%c", '\172');  z
[Link]("%c", '\u00A5');  ¥

f. %s (String of characters)
[Link]("%s", "\u00A5100");  ¥100

g. %f (Fractional number)
[Link]("%f", 2.65);  2.650000

h. %e (Fractional number in scientific form with e used)


[Link]("%e", 0.00265);  2.650000e-03

i. %E (Fractional number in scientific form with E used)


[Link]("%E", 0.00265);  2.650000E-03

j. %g (%f or %e [standard form power is < -4 or > +5])


[Link]("%g", 0.000265);  0.000265000
[Link]("%g", 0.0000265);  2.65000e-05
[Link]("%g", 250000.0);  250000
[Link]("%g", 2500000.0);  2.50000e+06

k. %G (%f or %E [standard form power is < -4 or > +5])


[Link]("%G", 0.000265);  0.000265000
[Link]("%G", 0.0000265);  2.65000E-05
[Link]("%G", 250000.0);  250000
[Link]("%G", 2500000.0);  2.50000E+06

USING METHODS FROM [Link]


The method is only suitable for a computer, not mobile devices. The output is displayed on a dialog box (pop-up window).

1. [Link](null, data);  Doesn’t require import statement


Example
1 public class Test {
2 public static void main(String[] args) {
3 [Link](null, "Hello world!!!");
4 }
5 }

Output

2. [Link](null, data);  Requires import statement


Example
1 import [Link];
2 public class Test {
3 public static void main(String[] args) {
4 [Link](null, false);
5 }
6 }

Output

Note
import [Link]; can be replaced by the shorter import [Link].*;
BASIC DATA STORAGE
Data is stored in what is called a variable. The amount of computer memory set aside for a variable (capacity of a variable) is
equal to the size of the data type to be stored in it.
DEFINING/DECLARING A VARIABLE
Syntax of a single variable
dataType name;
e.g. double length;

Syntax for multiple variables of the same type


dataType name, name, …, name;
e.g. double length, breadth, height;

INITIALIZING A VARIABLE
This refers to storing the first data in a variable immediately after its declaration.
Syntax of a single variable
dataType name = value;
e.g. double length = 2.5;

Syntax for multiple variables of the same type


dataType name = value, name = value, …, name = value;
e.g. double length = 3.6, breadth = 4.8, height = 2.5;

Note:
1. The name of a variable must reflect the data it is storing i.e. name has to be self-referencing. For example, r is better
name for a variable that will store radius, than n.
2. The name of a variable returns the data stored in it.
Example
1 public class App {
2 public static void main(String[] args) {
3 String fullname = "Simon Peter";
4 [Link](fullname);
5 }
6 }

Output
Simon Peter

DATA INPUT FROM KEYBOARD


USING METHODS FROM [Link]
All methods involved are object methods, hence the need to first, create an object of the Scanner class.

Instantiation
Scanner objectName = new Scanner([Link]);

Methods Available
Most of the methods have names that indicate the type of data they read and return.
1. nextByte() 8. next(): returns a string terminated by any space
2. nextShort() 9. next().charAt(0): returns a character (i.e. first character of a string)
3. nextInt() 10. nextLine(): returns a string ending with a new line (ENTER character).
4. nextLong() It will return an empty string if the first character it encounters in the input stream is the
5. nextFloat() ENTER character (remnant or trailing character from a previous data entry operation)
6. nextDouble()
7. nextBoolean()
Example
1 import [Link].*;
2
3 public class App {
4 public static void main(String[] args){
5 // INSTANTIATION
6 Scanner input = new Scanner([Link]);
7
8 // PROMPT, RECEIVE AND SAVE DATA
9 [Link]("Enter a string with space: ");
10 String s1 = [Link]();
11 [Link]("Enter an integer: ");
12 int i = [Link]();
13 [Link]("Enter a double: ");
14 double d = [Link]();
15 [Link]("Enter a boolean: ");
16 boolean b = [Link]();
17 [Link]("Enter a string without space: ");
18 String s2 = [Link]();
19 [Link]("Enter a character: ");
20 char ch = [Link]().charAt(0);
21
22 // DISPLAY RECEIVED DATA
23 [Link](
24 "\nDATA ENTERED" +
25 "\nString with space: " + s1 +
26 "\nInteger: " + i +
27 "\nDouble: " + d +
28 "\nBoolean: " + b +
29 "\nString with space: " + s2 +
30 "\nCharacter entered: " + ch
31 );
32 }
33 }

Output
Enter a string with space: Tommy Smith
Enter an integer: 56
Enter a double: 2.56e-4
Enter a boolean: false
Enter a string without space: Elijah
Enter a character: $

DATA ENTERED
String with space: Tommy Smith
Integer: 56
Double: 2.56E-4
Boolean: false
String with space: Elijah
Character entered: $

Notes
 The above methods all scan the input stream for the type of data they return
 The cursor blinks when a method can’t find the type of data it seeks, thus waiting for fresh data to be entered.
 nextLine() has to be invoked twice, if it is used after a data entry operation. The first empties the stream, by getting rid
of the trailing ENTER character, while the second provides a fresh opportunity to enter data.
 [Link]  System keyboard (data source)
 [Link]  System screen
Example 1
1 public class App{
2 public static void main(String[] args){
3 [Link] input = new [Link]([Link]);
4 [Link]("Enter integer: ");
5 int i = [Link]();
6 [Link]("Enter string with space: ");
7 String s = [Link]();
8
9 [Link]("\n\nData Entered\nInteger: " + i + "\nString: " + s);
10 }
11 }

Output
Enter integer: 65
Enter string with space:

Data Entered
Integer: 65
String:

Example 2
1 public class App{
2 public static void main(String[] args){
3 [Link] input = new [Link]([Link]);
4 [Link]("Enter integer: ");
5 int i = [Link]();
6 [Link]("Enter string with space: ");
7 String s = [Link]();
8 s = [Link]();
9
10 [Link]("\n\nData Entered\nInteger: " + i + "\nString: " + s);
11 }
12 }

Output
Enter integer: 65
Enter string with space: Ray Allen

Data Entered
Integer: 65
String: Ray Allen

USING METHODS FROM [Link]


The method is a static method. It returns a string, irrespective of the type of data entered. The method is not suitable for
phones. The method displays a dialog box with a text field for data entry.
 [Link](“Prompt to user”);
Example
1 import [Link].*;
2
3 public class App {
4 public static void main(String[] args){
5 String str = [Link]("What is your name?");
6 // Display name entered
7 [Link](null, str);
8 }
9 }
Output

It is also possible to return an appropriate string to any of the primitive data types, for further processing in the program.
This can be done using static methods in special classes defined in [Link] called WRAPPER CLASSES or WRAPPERS.
Each primitive data type has a corresponding wrapper.

SN DATA WRAPPER METHOD EXAMPLE


1 byte Byte parseByte(“str”); [Link](“45”);
2 short Short parseShort(“str”); [Link](“45”);
3 int Integer parseInt(“str”) [Link](“67”);
4 long Long parseLong(“str”) [Link](“67l”);
5 float Float parseFloat(“str”) [Link](“2.54e-05f”);
6 double Double parseDouble(“str”) [Link](“2.5E-05”);
7 boolean Boolean parseBoolean(“str”) [Link](“true”);

NOTE:
1. The string argument in the example can also be replaced by the variable housing the returned string
2. The wrapper for char is Character and it is not listed in the table because using charAt(0) can convert a single character
string to char i.e. by using [Link](0).
Example
String str = [Link](“Enter sex (m/f)”);
char gender = [Link](0)

ARITHMETIC OPERATORS
1. + (addition and concatenation if there is a string operand)
Examples
5 + 5 = 10
5 + “5” = “55”
“Ans: ” + 3.4 = “Ans: 3.4”

2. – (subtraction)
3. * (multiplication)

4. / (division): result is fractional if at least one operand is fractional, and it is an integer (no fractional part) if both
operands are integer values.
Examples
7 / 2 = 3 (fractional part is truncated)
7 / 2.0 = 3.5
7.0 / 2 = 3.5
7.0 / 2.0 = 3.5

5. % (modulus): remainder operator which also returns a fractional value if at least an operand is fractional.
Example
5%2=1
4 % 2.1 = 1.9
25 % 5 = 0
25.0 % 5 = 0.0

MATH METHODS (FUNCTIONS)


Package: [Link] (no import needed)
Class: Math
Method/Variable Type: static

Some important methods, as well as the value they return, and variables:

1. Math.E  e (2.718281828459045)

2. [Link]  π (3.141592653589793)

3. [Link](x)  sine of x radians

4. [Link](x)  cosine of x radians

5. [Link](x)  tangent of x radians

6. [Link](y)  y degrees in radians

7. [Link](x)  x radians in degrees

8. [Link](z)  sin-1 z (arc sine) in radians

9. [Link](z)  cos-1 z (arc cosine) in radians

10. [Link](z)  tan-1 z (arc tangent) in radians

11. [Link](x)  ex

12. [Link](x)  ln(x) (natural logarithm of x)

13. Math.log10(x)  log(x) (logarithm of x to base 10)

14. [Link](x, y)  xy

15. [Link](x)  √x

16. [Link](x)  ∛x
17. [Link](x)  ⌈x⌉ (x pushed up to the nearest whole number higher than or equal to x)

18. [Link](x)  ⌊x⌋ (x pushed down to the nearest whole number lower than or equal to x)

19. [Link](x)  x to the nearest whole number

20. [Link](a, b)  lesser of a and b

21. [Link](a, b)  larger of a and b

22. [Link](x)  |x| (absolute value of x)

23. [Link]()  random number that is greater than 0 but less than 1
NOTE
Random number between 0 to (n – 1)  (int)([Link]() * n)
Example
1 import [Link].*;

2 public class App {


3 public static void main(String[] args){
4 [Link]("RANDOM FRACTIONAL NUMBERS");
5 [Link]([Link]());
6 [Link]([Link]());
7
8 [Link]("\nRANDOM INTEGERS BW 0 - 5");
9 [Link]((int)([Link]()*6));
10 [Link]((int)([Link]()*6));
11 }
12 }

Output 1
RANDOM FRACTIONAL NUMBERS
0.7563692287542084
0.7107141893878408

RANDOM INTEGERS BW 0 - 5
3
5

Output 2
RANDOM FRACTIONAL NUMBERS
0.8404349066260486
0.6462394167626859

RANDOM INTEGERS BW 0 - 5
5
5

EXERCISES
1. Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and
displays the result. The formula for the conversion is as follows:
fahrenheit = (9 / 5) * celsius + 32
Hint: In Java, 9 / 5 is 1, but 9.0 / 5 is 1.8.

Here is a sample run:


Output
Enter a degree in Celsius: 43
43 Celsius is 109.4 Fahrenheit

2. Write a program that reads in the radius and length of a cylinder and computes the area and volume using the
following formulas:
area = radius * radius * �
volume = area * length

Here is a sample run:

Output
Enter the radius and length of a cylinder: 5.5 12
The area is 95.0331
The volume is 1140.4

3. Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an
integer is 932, the sum of all its digits is 14.
Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 =
2 and 932 / 10 = 93.

Here is a sample run:

Output
Enter a number between 0 and 1000: 999
The sum of the digits is 27

4. Write a program that prompts the user to enter two points (x1, y1) and (x2, y2) and displays their distance between
them. The formula for computing the distance is (�2 + �1 )2 + (�2 + �1 )2 . Note that you can use [Link](a, 0.5) to
compute �. Here is a sample run:

Output
Enter x1 and y1: 1.5 -3.4
Enter x2 and y2: 4 5
The distance between the two points is 8.764131445842194

5. How cold is it outside? The temperature alone is not enough to provide the answer. Other factors including wind speed,
relative humidity, and sunshine play important roles in determining coldness outside. In 2001, the National Weather
Service (NWS) implemented the new wind-chill temperature to measure the coldness using temperature and wind
speed. The formula is
twc = 35.74 + 0.6215ta - 35.75v0.16 + 0.4275tav0.16
where ta is the outside temperature measured in degrees Fahrenheit and v is the speed measured in miles per hour. twc
is the wind-chill temperature. The formula cannot be used for wind speeds below 2 mph or temperatures below -58 ºF
or above 41ºF.
Write a program that prompts the user to enter a temperature between -58 ºF and 41ºF and a wind speed greater than
or equal to 2 and displays the wind-chill temperature. Use [Link](a, b) to compute v0.16. Here is a sample run:
Output
Enter the temperature in Fahrenheit between -58°F and 41°F: 5.3
Enter the wind speed (>=2) in miles per hour: 6
The wind chill index is -5.56707

6. Write a program that prompts the user to enter three points (x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area.
The formula for computing the area of a triangle is
s = (side1 + side2 + side3)/2;
area = �(� − ����1)(� − ����2)(� − ����3)
Here is a sample run:

Output
Enter three points for a triangle: 1.5 -3.4 4.6 5 9.5 -3.4
The area of the triangle is 33.6

7. Consider the following circuit.

Write a program that reads the resistances of the three resistors and computes the total resistance, using Ohm’s law.
The formula for this computation is
� �
�1 + � 2+�3
2 3
Output
Enter R1, R2, and R3: 1500 3000 2.4e3
Total resistance is 2833.333333333333

8. The dew point temperature Td can be calculated (approximately) from the relative humidity RH and the actual
temperature T by
�. �(�, �)
�� =
� − �(�, ��)
�. �
� �, �� = + ln (��)
�+�
Where a = 17.27 and b = 237.7oC.
Write a program that reads the relative humidity (between 0 and 1) and the temperature (in degrees C) and prints the
dew point value. Here is a sample run:

Output
Enter relative humidity (0 -1): 0.5
Enter temperature in degrees Celsius: 60
Due point is 45.75173774365529

BOOLEAN OPERATORS
RELATIONAL OPERATORS
Result is always Boolean (true or false).
1. < (is less than)
2. <= (is less than equal to)
3. > (is greater than)
4. >= (is greater than or equal 0)
5. == (is equal to)
6. != (is not equal to)

LOGICAL OPERATOR
Each operand takes only Boolean values as operands.
1. ! (NOT): converts true to false and false to true
!true = false
!false = true

2. || (OR): its expression is true if one or more operands are true, otherwise it is false.
false || false = false
true || false = true
true || true = true

3. | (OR): same as ||

4. && (AND): its expression is false if one or more operands are false, otherwise it is true.
true && true = true
true && false = false
false && false = false

5. & (AND): same as &&

6. ^ (XOR/Exclusive OR): its expression is true if its operands are different. Generally having an odd number of true
operands gives a true.
true ^ true = false
true ^ false = true
false ^ false = false
true ^ true ^ true ^ true = false
true ^ true ^ false ^ true = true

For |, ||, &, and && values are evaluated one after the other from left to right. In the case of || and &&, further evaluation
is stopped and final result returned when the first true operand (for ||) or the first false operand (for &&) is encountered.
This form of evaluation is called short-circuit evaluation. | and & don’t support short-circuit evaluation (i.e. all values are
evaluated even with the final result determined)
Example
In the examples below, the Boolean value that is bold and underlined is the last evaluated.
1. false || true || false || true || true || false = true
2. false | true | false | true | true | false = true
3. true && true && false && false && true = true
4. true & true & false & false & true = false

BRANCHING
TENARY OPERATOR (?)
Single expression with two possible results. Final result is determined by the value of a Boolean expression.
Syntax:
Boolean_expression ? true_expression : false_expression
 true_expression: evaluated for the final result if boolean_expression = true
 false_expression: evaluated for the final result if boolean_expression = false
Example 1
[Link](9<25?[Link](9):[Link](25));
Result = 3.0

Example 2
[Link](9>25?[Link](9):[Link](25));
Result = 5.0
IF-STATEMENT
if(boolean_expression){
// statement(s) executed if boolean_expression is true otherwise skip
}
Example
1 [Link]("Enter score: ");
2 [Link] input = new [Link]([Link]);
3 int score = [Link]();
4 if(score < 45){
5 [Link]("Remark: Fail");
6 }
7 if(score >= 45){
8 [Link]("Remark: Pass");
9 }

Outputs
Enter score: 44
Remark: Fail

Enter score: 56
Remark: Pass

IF-ELSE STATEMENT
if(boolean_expression){
// statement(s) executed if boolean_expression is true
}
else{
// statement(s) executed if boolean_expression is false
}
Example
1 [Link]("Enter score: ");
2 [Link] input = new [Link]([Link]);
3 int score = [Link]();
4 if(score < 45){
5 [Link]("Remark: Fail");
6 }
7 else{
8 [Link]("Remark: Pass");
9 }

Outputs
Enter score: 44 Enter score: 56
Remark: Fail Remark: Pass

NESTED IF-ELSE STATEMENT


Unlike the if-else statement which has provision for only two outcomes, the nested version makes provision for far more.
The statement(s) in a block only get executed if the Boolean expression directly above it/them is true. Once this happens,
the statement is exited i.e. no further evaluation (downward).
if(boolean_expression){
// statement(s)
}
else if(boolean_expression){
// statement(s)
}
:
else if(boolean_expression){
// statement(s)
}
else{
// statement(s) get executed if all conditions above are false
}

NOTE
The braces are not necessary is a boolean_expression is followed by only one statement.

Example
1 [Link]("Enter score: ");
2 [Link] input = new [Link]([Link]);
3 int score = [Link]();
4 char grade;
5
6 if(score < 45)
7 grade = 'F';
8 else if(score < 50)
9 grade = 'D';
10 else if(score < 60)
11 grade = 'C';
12 else if(score < 70)
13 grade = 'B';
14 else
15 grade = 'A';
16
17 [Link]("Grade: " + grade);

Outputs
Enter score: 56 Enter score: 70 Enter score: 34
Grade: C Grade: A Grade: F

SWITCH-STATEMENT
This statement gets statement(s) if a variable contains a specific/single value.
switch(variable){
case value:
statement(s)
break;
case value:
statement(s)
break;
case value: case value: // statements to be executed for two values are the same
statement(s)
break;
:
default:
statement(s) get executed if the variable couldn’t match any of the given values
}

Note: The break ensures that the switch-statement is exited immediately after the statement(s) following a matched value
gets/get executed.
Example
1 [Link] input = new [Link]([Link]);
2 [Link]("Enter score: ");
3 int score = [Link]();
4 [Link]("Enter course unit: ");
5 int units = [Link]();
6
7 char grade = score<45 ? 'F':(score<50 ? 'D':(score<60 ? 'C':(score<70 ? 'B':'A')));
8 int multiplier;
9
10 switch(grade){
11 case 'F':
12 multiplier = 0;
13 break;
14 case 'D':
15 multiplier = 2;
16 break;
17 case 'C':
18 multiplier = 3;
19 break;
20 case 'B':
21 multiplier = 4;
22 break;
23 default:
24 multiplier = 5;
25 }
26
27 [Link]("\nGrade: " + grade);
28 [Link]("Multiplier: " + multiplier);
29 [Link]("Grade Points: " + (units * multiplier));

Outputs
Enter score: 67 Enter score: 44 Enter score: 78
Enter course unit: 3 Enter course unit: 4 Enter course unit: 2

Grade: B Grade: F Grade: A


Multiplier: 4 Multiplier: 0 Multiplier: 5
Grade Points: 12 Grade Points: 0 Grade Points: 10

EXERCISES
1. Write a program that reads an integer and prints how many digits the number has, by checking whether the number is
≥ 10, ≥ 100, and so on. (Assume that all integers are less than ten billion.) If the number is negative, first multiply it
with –1, if it is greater than or equal to ten billion, state that it is out of range.

Outputs
Enter an integer less than 10 billion: 56664675
Digits: 8

Enter an integer less than 10 billion: -586646


Digits: 6

Enter an integer less than 10 billion: 1000000000


Number is out of range

2. Suppose a right triangle is placed in a plane as shown below. The right-angle point is at (0, 0), and the other two points
are at (200, 0), and (0, 100). Write a program that prompts the user to enter a point with x- and y-coordinates and
determines whether the point is inside the triangle.
Outputs
Enter a point’s x- and y-coordinates: 100.5 22.5
(100.5, 22.5) is in the triangle

Enter a point’s x- and y-coordinates: 100.5 50.5


(100.5, 50.5) is outside the triangle

3. Zeller’s congruence is an algorithm developed by Christian Zeller to calculate the day of the week. The formula is

 h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday, 4: Wednesday, 5: Thursday, 6: Friday).
 q is the day of the month.
 m is the month (3: March, 4: April, ..., 12: December). January and February are counted as months 13 and 14
of the previous year.
����
 j is the century (i.e., 100
).
 k is the year of the century (i.e., year % 100).

Write a program that prompts the user to enter a year, month, and day of the month, and then it displays the name of
the day of the week.

Outputs
Enter year: (e.g., 2008): 2013
Enter month: 1-12: 1
Enter the day of the month: 1-31: 25
Day of the week is Friday

Enter year: (e.g., 2008): 2012


Enter month: 1-12: 5
Enter the day of the month: 1-31: 12
Day of the week is Saturday

4. Write a program that prompts the user to input the x-y coordinate of a point in a Cartesian plane. The program should
then output a message indicating whether the point is the origin, is located on the x- (or y-) axis, or appears in a
particular quadrant.

Outputs
Enter x and y coordinates: 0 0
(0, 0) is the origin

Enter x and y coordinates: 4 0


(4, 0) is on the x-axis

Enter x and y coordinates: 0 -3


(0, -3) is on the y-axis

Enter x and y coordinates: -2 3


(-2, 3) is in the second quadrant

Enter x and y coordinates: 1 -4


(-2, 3) is in the fourth quadrant
5. Write a program that converts a positive integer into the Roman number system. The Roman number system has digits
I -> 1, V -> 5, X -> 10, L -> 50, C -> 100, D -> 500, and M -> 100
Numbers are formed according to the following rules:
a. Only numbers up to 3,999 are represented.
b. As in the decimal system, the thousands, hundreds, tens, and ones are expressed separately.
c. The numbers 1 to 9 are expressed as I -> 1, II -> 2, III -> 3, IV -> 4, V -> 5, VI -> 6, VII -> 7, VIII -> 8, IX -> 9, X
-> 10
As you can see, an I preceding a V or X is subtracted from the value, and you can never have more than three
I’s in a row.
d. Tens and hundreds are done the same way, except that the letters X, L, C and C, D, M are used instead of I, V,
X, respectively.
Your program should take an input, such as 1978, and convert it to Roman numerals,
MCMLXXVIII.

Outputs
Enter any integer from 1 - 3999: 1978
Roman equivalent: MCMLXXVIII

Enter any integer from 1 - 3999: -154


Number is out of range.

Enter any integer from 1 - 3999: 4000


Number is out of range.

6. The roots of the quadratic equation ax2 + bx + c = 0, a ≠ 0 are given by the following formula:

−� ± �2 − 4��
�=
2�

In this formula, the term b2−4ac is called the discriminant. If b2−4ac = 0, then the equation has a single (repeated) root.
If b2−4ac > 0, the equation has two real roots. If b2−4ac < 0, the equation has two complex roots. Write a program that
prompts the user to input the value of a (the coefficient of x2), b (the coefficient of x), and c (the constant term) and
outputs the of roots of the equation.

Outputs
Enter values for a, b, and c: 1 2 1
Root = -1.0

Enter values for a, b, and c: 1 3 2


1st root: -1.0
2nd root: -2.0

Enter value for a, b, and c: 1 3 2


1st root: -0.5 + 1.6583123951777
2nd root: -0.5 - 1.6583123951777

INCREMENT AND DECREMENT OPERATORS


These operators are applied to variables, not literals. Increment (++) increases the value in a variable by 1, while the
decrement (--) decreases the value in a variable by 1.
PRE AND POST INCREMENT/DECREMENT OPERATIONS
When a variable with -- or ++ is used with another operator or a method, which value of the variable gets used? Is it the
original or altered (by -- or ++)?
In pre increment/decrement
1. The operator is written before the variable i.e. --variable, or ++variable.
2. -- or ++ edits the variable, before it is used with the operator or method.
Example 1
1 public class Experiments{
2 public static void main(String[] args){
3 double var = 2;
4 [Link](++var); // increment, then print var
5 [Link](var);
6 }
7 }

Output
3.0
3.0

Example 2
1 public class Experiments{
2 public static void main(String[] args){
3 double a = 3, b;
4
5 b = --a + 10;
6 // decrement a, then add it to 10, and assign the result to b
7
8 [Link]("a = " + a);
9 [Link]("b = " + b);
10 }
11 }

Output
a = 2.0
b = 12.0

In post increment/decrement
1. The operator is written after the variable i.e. variable-- or variable++
2. The variable is first used with the operator or method, after which it gets edited by -- or ++.

Example 1
1 public class Experiments{
2 public static void main(String[] args){
3 double var = 2;
4 [Link](var++); // display var, then increment
5 [Link](var);
6 }
7 }

Output
2.0
3.0

Example 2
1 public class Experiments{
2 public static void main(String[] args){
3 double a = 3, b;
4
5 b = a-- + 10;
6 // add a to 10, decrement a, then assign result of addition to b
7
8 [Link]("a = " + a);
9 [Link]("b = " + b);
10 }
11 }

Output
a = 2.0
b = 13.0

AUGMENTED ASSIGNMENT OPERATORS


var = var operator value;  var operator= value;
This implies that:
1. var = var + value;  var += value;
2. var = var – value;  var -= value;
3. var = var * value;  var *= value;
4. var = var / value;  var /= value;
5. var = var % value;  var %= value;

LOOPING/ITERATION
Looping refers to executing a programming statement or group of statements repeatedly. Facts to note include:
 task or group of statements are only executed when a predefined Boolean expression (condition) is true
 depending on the technique used, a loop runs either for a specified number of times, or for as long as a
programming condition persists.
 After executing statements in the body, the condition is re-evaluated to confirm if the statement(s) would be
executed again. The loop terminates the moment the condition turns false.

Looping techniques are presented below:


1. while-loop
while(Boolean_expression){
// statement(s) to execute
}

2. do-while loop
do{
// statement(s) to execute
}while(Boolean_expression);

3. for-loop
for(initializations; Boolean_expression; alteration){
// statement(s) to execute
}

PROGRAMMING EXAMPLES
1. Write a program that prompts a student to enter a Java score. If the score is greater or equal to 60, display “you pass the
exam”; otherwise, display “you don’t pass the exam”. Your program ends with input -1. Here is a sample run:

Enter your score: 80


You pass the exam.

Enter your score: 59


You don't pass the exam.

Enter your score: −1


No numbers are entered except 0

Solution with a while loop


1 import [Link].*;
2 public class Experiments{
3 public static void main(String[] args){
4 // Initialize score to any value but -1
5 int score = 0;
6
7 Scanner scan = new Scanner([Link]);
8
9 String format = "";
10
11 while(score != -1){
12 [Link](format + "Enter your score: ");
13 score = [Link]();
14
15 // Test score
16 if(score >= 60)
17 [Link]("Your pass the exam.");
18 else if (score == -1){
19 [Link]("No numbers are entered except 0");
20 }
21 else{
22 [Link]("You don\'t pass the exam.");
23 }
24
25 // space next prompt a bit downward
26 format = "\n";
27 }
28 }
29 }

Solution with do-while loop


1 import [Link].*;
2 public class Experiments{
3 public static void main(String[] args){
4
5 int score;
6
7 Scanner scan = new Scanner([Link]);
8
9 String format = "";
10
11 do{
12 [Link](format + "Enter your score: ");
13 score = [Link]();
14
15 // Test score
16 if(score >= 60)
17 [Link]("Your pass the exam.");
18 else if (score == -1)
19 [Link]("No numbers are entered except 0");
20 else
21 [Link]("You don\'t pass the exam.");
22
23 // space next prompt a bit downward
24 format = "\n";
25 }while(score != -1);
26 }
27 }
2. Write a program that displays the following table (note that farenheit = celsius * 9/5 + 32):
Celsius Fahrenheit
0 32.0
2 35.6
...
98 208.4
100 212.0

Solution
Facts to note before writing the program
1. Independent values (Celsius values) are from 0 to 100 with an increment of 2
2. The Celsius values are aligned to the left
3. The Fahrenheit values are aligned to the right
4. The Fahrenheit values are provided to one decimal place
5. The is space between both columns of values

1 import [Link].*;
2
3 public class Experiments{
4 public static void main(String[] args){
5
6 // DISPLAY HEADING
7 [Link]("Celsius\tFahrenheit\n");
8
9 // CALL IN THE CELCIUS VALUES
10 for(int c = 0; c <= 100; c = c + 2){
11
12 // Calculate the Fahrenheit value
13 double f = c * 9.0/5 + 32;
14
15 // Display properly formatted table body
16 [Link]("%-7d\t%10.1f\n", c, f);
17 }
18 }
19 }

EXERCISES
1. Write a program that displays the following table (note that 1 inch is 2.54 centimeters):
Inches Centimetres
1 2.54
2 5.08
...
9 22.86
10 25.40

2. Write a program that displays the following two tables side by side:
Celsius Fahrenheit | Fahrenheit Celsius
0 32.000 | 20 −6.667
2 35.600 | 25 −3.889
...
98 208.400 | 265 129.444
100 212.000 | 270 132.222

3. Write a program that displays the following two tables side by side (note that 1 ping = 3.305 square meters):
Ping Square meter | Square meter Ping
10 33.050 | 30 9.077
15 49.575 | 35 10.590
...
75 247.875 | 95 28.744
80 264.400 | 100 30.257

4. Suppose that the tuition for a university is $10,000 this year and increases 6% every year. In one year, the tuition will
be $10,600. Write a program that computes the tuition in ten years and the total cost of four years’ worth of tuition
after the tenth year.

5. Write a program that prompts the user to enter the number of students and each student’s name and score, and finally
displays the name of the student with the highest score. Use the next() method in the Scanner class to read a name,
rather than using the nextLine() method.

6. Write a program that displays all the numbers from 100 to 1,000, ten per line, that are divisible by 3 and 4. Numbers
are separated by exactly one space.

7. Use a while loop to find the smallest integer n such that n3 is greater than 12,000.

8. Use a while loop to find the largest integer n such that n2 is less than 12,000.

BREAKING CONTROL FLOW


It is possible to disrupt the way a loop runs. There are two keywords used to do this, these are:
1. break: it ends the loop containing it, when executed
2. continue: it ends the current iteration when executed, thus paving the way for the commencement of the next
iteration.

Example 1
1 public class Experiments{ 1 public class Experiments{
2 public static void main(String[] args){ 2 public static void main(String[] args){
3 for(int i = 1; i <= 3; i++){ 3 for(int i = 1; i <= 3; i++){
4 for(int j = 1; j <= 5; j++){ 4 for(int j = 1; j <= 5; j++){
5 [Link]( 5 if(j == 4)
6 "%d x %d = %d\n", i, j, i*j 6 break;
7 ); 7 [Link](
8 } 8 "%d x %d = %d\n", i, j, i*j
9 [Link](); 9 );
10 } 10 }
11 } 11 [Link]();
12 } 12 }
13 }
14 }
Example 2
1 public class Experiments{ 1 public class Experiments{
2 public static void main(String[] args){ 2 public static void main(String[] args){
3 for(int i = 1; i <= 3; i++){ 3 for(int i = 1; i <= 3; i++){
4 for(int j = 1; j <= 5; j++){ 4 for(int j = 1; j <= 5; j++){
5 [Link]( 5 if(j == 4)
6 "%d x %d = %d\n", i, j, i*j 6 continue;
7 ); 7 [Link](
8 } 8 "%d x %d = %d\n", i, j, i*j
9 [Link](); 9 );
10 } 10 }
11 } 11 [Link]();
12 } 12 }
13 }
14 }

NESTED LOOPS
This is a scenario in which we have one or more loops running within another loop. In most cases, it is a one or more for-
loops running within another for-loop.
Example 1
Use nested loops that display the following patterns in four separate programs:
Pattern A Pattern B Pattern C Pattern D
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
Pattern A
1 public class Experiments{
2 public static void main(String[] args){
3 for(int i = 1; i <= 6; i++){
4 for(int j = 1; j <= i; j++){
5 [Link]("%2c", '*');
6 }
7 [Link]();
8 }
9 }
10 }

Pattern B
1 public class Experiments{
2 public static void main(String[] args){
3 for(int i = 6; i >= 1; i--){
4 for(int j = 1; j <= i; j++){
5 [Link]("%2c", '*');
6 }
7 [Link]();
8 }
9 }
10 }

Pattern C
1 public class Experiments{
2 public static void main(String[] args){
3 int spaces = 5; // Spaces on the first line
4 for(int i = 1; i <= 6; i++){
5 // Display spaces
6 for(int s = 1; s <= spaces; s++){
7 [Link]("%2s", "");
8 }
9 // Display stars
10 for(int j = 1; j <= i; j++){
11 [Link]("%2s", "*");
12 }
13 // Prepare for next line
14 spaces--;
15 [Link]();
16 }
17 }
18 }

Pattern D
1 public class Experiments{
2 public static void main(String[] args){
3 int spaces = 0; // Spaces on the first line
4 for(int i = 6; i >= 1; i--){
5 // Display spaces
6 for(int s = 1; s <= spaces; s++){
7 [Link]("%2s", "");
8 }
9 // Display stars
10 for(int j = 1; j <= i; j++){
11 [Link]("%2s", "*");
12 }
13 // Prepare for next line
14 spaces++;
15 [Link]();
16 }
17 }
18 }

Example 2
Write a program that displays all the prime numbers from 1 to 30.
1 public class Experiments{
2 public static void main(String[] args){
3 int count = 0;
4 // Roll in the numbers
5 for(int n = 1; n <= 30; n++){
6 // Roll in the factors
7 for(int f = 1; f <= n; f++){
8 if(n%f == 0)
9 count++;
10 }
11 // A prime number has only two factors
12 if(count == 2)
13 [Link](n);
14
15 // Reset count
16 count = 0;
17 }
18 }
19 }

Output

EXERCISES
1. Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid, as shown in the
following sample run:

Enter the number of lines: 7


7 6 5 4 3 2 1 2 3 4 5 6 7
6 5 4 3 2 1 2 3 4 5 6
5 4 3 2 1 2 3 4 5
4 3 2 1 2 3 4
3 2 1 2 3
2 1 2
1

2. Write a nested for loop that prints the following output:

3. Write a program that will display all the prime numbers between 2 and 1,200, inclusive. Display eight prime numbers
per line. Numbers are separated by exactly one space.

4. A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For
example, 6 is the first perfect number because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. There are four perfect
numbers 6 10,000. Write a program to find all these four numbers.

5. Write a program that prompts the user to enter 10 numbers and displays the mean and standard deviations of these
numbers using the following formula:
Here is a sample run:

Enter 10 numbers: 1 2 3 4.5 5.6 6 7 8 9 10


The mean is 5.61
The standard deviation is 2.99794

6. ISBN-13 is a new standard for identifying books. It uses 13 digits d1d2d3d4d5d6d7d8d9d10d11d12d13. The last digit
d13 is a checksum, which is calculated from the other digits using the following formula:
10 - (d1 + 3d2 + d3 + 3d4 + d5 + 3d6 + d7 + 3d8 + d9 + 3d10 + d11 + 3d12) % 10
If the checksum is 10, replace it with 0. Your program should read the input as a string. Here are sample runs:

Enter the first 12 digits of an ISBN-13 as a string: 978013213080


The ISBN-13 number is 9780132130806

Enter the first 12 digits of an ISBN-13 as a string: 978013213079


The ISBN-13 number is 9780132130790

Enter the first 12 digits of an ISBN-13 as a string: 97801320


97801320 is an invalid input

EXERCISES
1. Write a class that contains the following two methods:

/* Convert from Mile to Kilometer */


public static double mileToKilometer(double mile)

/* Convert from Kilometer to Mile */


public static double kilometerToMile(double kilometer)

The formula for the conversion is:


1 mile = 1.6 kilometers
Write a test program that invokes these methods to display the following tables:

2. Implement the following two methods:

/* Return true if the sum of every two sides is


* greater than the third side. */
public static boolean isValid(double side1, double side2, double side3)
/* Return the area of the triangle. */
public static double area(double side1, double side2, double side3)
Write a test program that reads three sides for a triangle and uses the isValid method to test if the input is valid and
uses the area method to obtain the area. The program displays the area if the input is valid. Otherwise, it displays that
the input is invalid. Required formulas are given below:
�+�+�
���� = �(� − �)(� − �)(� − �) , � = 2

3. Write a method that finds the number of occurrences of a specified character in a string using the following header:

public static int count(String str, char a)

For example, count("Welcome", 'e') returns 2. Write a test program that prompts the user to enter a string followed
by a character then displays the number of occurrences of the character in the string.

ARRAYS
A finite cluster of variables of the same type. Important facts to note about arrays include:
1. Each variable is an element
2. They all share the same identifier/name
3. The number of variables in the array is called size, length, or dimension.
4. Each element is differentiated by an integer called the index
5. The index starts from 0, for first element to (size – 1) for the last element in the array

DECLARING ARRAYS (1 DIMESIONAL)


 type[] name = new type[size];
int[] scores = new int[60];
 All variables in the array are initialized to 0 or the 0-equivalent of its data type

 type[] name = {value, value, …, value};


int[] ages = {45, 34, 76, 54};
 Size of the array is equal to the number of values

Some important facts to note about arrays include:


1. name[index]  reference to the element of the array at the specified index
2. [Link]  size of the array

ACCESSING ELEMENTS IN THE ARRAY


In many cases, the use of an array involves all elements of the array, and on account of the fact that the index values of an
array form an arithmetic series where
1. first value = 0 or (size – 1)
2. last value = (size – 1) or 0
3. common difference = 1 or -1
it is easier to access the elements of an array one at a time with the aid a for-loop that returns all the index values of the
array.
This is shown below:
From index 0 to (size – 1)
for(int index = 0; index < [Link]; index++){
process name[index]
}

Example
1 public class Experiments{
2 public static void main(String[] args){
3 int[] ages = {45, 67, 98, 23, 56};
4 for(int index = 0; index < [Link]; index++)
5 [Link](ages[index]);
6 }
7 }

From index (size – 1) to 0


for(int index = [Link] – 1, index >= 0; index--)
process name[index]
}

Example
1 public class Experiments{
2 public static void main(String[] args){
3 int[] ages = {45, 67, 98, 23, 56};
4 for(int index = [Link] - 1; index >= 0; index--)
5 [Link](ages[index]);
6 }
7 }

Enhanced for-loop
This for-loop provides a means of getting the entire data (starting from index 0) stored in an array. It cannot be used for
entering data into an array.

for(type variable : array){


// process variable
}

Example
1 public class Experiments{
2 public static void main(String[] args){
3 int[] scores = new int[4];
4
5 // Display initial scores
6 [Link]("Initial Scores");
7 for(int var : scores)
8 [Link](var + " ");
9
10 // Prompt for new scores
11 [Link]("\n\nEnter 4 scores: ");
12
13 // Receive and save 4 scores
14 [Link] scan = new [Link]([Link]);
15 for(int i = 0; i < [Link]; i++)
16 scores[i] = [Link]();
17
18 // Display new scores
19 [Link]("\nNew Scores");
20 for(int i = 0; i < [Link]; i++)
21 [Link](scores[i] + " ");
22 }
23 }

SOME METHODS FOR ARRAYS


1. [Link](array): sorts array in ascending order
1. public class Experiments{
2. public static void main(String[] args){
3. int[] scores = {4, 8, 12, 2, 1};
4.
5. // Array before sorting
6. [Link]("Array before sorting");
7. for(int s : scores)
8. [Link](s + " ");
9.
10. // Sort array
11. [Link](scores);
12.
13. // Arrau after sorting
14. [Link]("\n\nArray after sorting");
15. for(int s : scores)
16. [Link](s + " ");
17. }
18.}

1 [Link](sourceArray, sourceStart, targetArray, targetStart, count): copies


data from sourceArray to targetArray.
i. sourceArray: array from which data is to be copied.
ii. sourceStart: index from which the copying will start in the source array.
iii. targetArray: array to which data is to be copied.
iv. targetStart: index in the target array where pasting of copied data will start
v. count: number of consecutive data in the source that will be copied to the target array.
Note: target array must have enough spaces to receive the expected data
1 public class Experiments{
2 public static void main(String[] args){
3 int[] arrA = {2, 8, 0, 0, 0, 0, 0};
4 int[] arrB = {7, 9, 10, 11, 12};
5
6 // arrA before copying
7 [Link]("arrA before copying");
8 for(int o : arrA)
9 [Link](o + " ");
10
11 // Copy 9, 10, and 11 from arrB to arrA
12 [Link](arrB, 1, arrA, 2, 3);
13
14 // arrA after copying
15 [Link]("\n\narrA after copying");
16 for(int o : arrA)
17 [Link](o + " ");
18
19 }
20 }

2 [Link](array, value): returns the index of the value in the array. It returns a
negative number if value can’t be found in array. This method is only effective if the array is sorted.
1 import [Link].*;
2 public class Experiments{
3 public static void main(String[] args){
4 int[] arr = {7, 9, 10, 11, 12};
5
6 [Link]("Index of 10: " + [Link](arr, 10));
7 [Link]("Index of 2: " + [Link](arr, 2));
8 }
9 }

3 [Link](array, value): puts value in all elements of array


1 import [Link].*;
2 public class Experiments{
3 public static void main(String[] args){
4 int[] arr = {7, 9, 10, 11, 12};
5
6 [Link]("Array before filling");
7 for(int o : arr)
8 [Link](o + " ");
9
10 [Link](arr, 0);
11
12 [Link]("\n\nArray after filling");
13 for(int o : arr)
14 [Link](o + " ");
15 }
16 }

4 [Link](array1, array2): returns true if array1 is equal to array2, and false otherwise.
1 import [Link].*;
2 public class Experiments{
3 public static void main(String[] args){
4 int[] arr1 = {1, 2, 3};
5 int[] arr2 = {1, 2, 3};
6 int[] arr3 = {1, 2, 4};
7
8 [Link]("[Link](arr1, arr2) = " + [Link](arr1, arr2));
9 [Link]("[Link](arr1, arr3) = " + [Link](arr1, arr3));
10 }
11 }

MUTLIDIMENSIONAL ARRAYS (2-DIMENSIONAL)


It is described as an array of arrays, not single data like we have seen thus far. This type of array is best described, using
tables with rows and columns.
DECLARATION
 type[][] name = new type[rows][cols];
 all values are 0
Example
int[] scores = new int[6][24];

 type[][] name = {{val, val, …, val},{val, val, …, val}, …,{val, val, …, val}};
Example
int[][] ca = {{4, 6, 8, 2}, {4, 9, 7, 7}, {3, 8, 4, 7}};

ELEMENT REFERENCING
name[rowIndex][colIndex]  array element
Example
1. scores[4][1] = 0
2. ca[2][2] = 4

Note
 [Link]  number of rows (parent array)
 name[row_index].length  number of columns in the specified row (child array)

There are two indexes – row, and column – hence easier access to the elements of these arrays, requires two nested for-
loops.
for(int r = 0; r < [Link]; r++){
for(int c = 0; c < name[r].length; c++){
// process name[r][c]
}
// any other thing to do before getting the next row
}

Example
1 public class Experiments{
2 public static void main(String[] args){
3 int[][] arr = {
4 {7, 7, 9, 3},
5 {2, 5, 0, 5},
6 {1, 11, 12, 4}
7 };
8
9 for(int r = 0; r < [Link]; r++){
10 for(int c = 0; c < arr[r].length; c++){
11 [Link]("%4d", arr[r][c]);
12 }
13 [Link]("\n");
14 }
15 }
16 }

Note
 The inner for-loop can be replaced by an enhance for-loop
 All array methods mentioned for one-dimensional or SINGLY-SUBSCRIPTED arrays apply to the contained arrays

Example
1 public class Experiments{
2 public static void main(String[] args){
3 int[][] arr = {
4 {7, 7, 9, 3},
5 {2, 5, 0, 5},
6 {1, 11, 12, 4}
7 };
8 [Link]("BEFORE ALTERATION");
9 for(int r = 0; r < [Link]; r++){
10 // Enhanced for-loop to process each row (1-dimensional array)
11 for(int ele : arr[r]){
12 [Link]("%4d", ele);
13 }
14 [Link]();
15 }
16
17 // ALTERATION
18 for(int r = 0; r < [Link]; r++){
19 // Fill each row with its index value
20 [Link](arr[r], r);
21 }
22
23 [Link]("\nAFTER ALTERATION");
24 for(int r = 0; r < [Link]; r++){
25 for(int ele : arr[r]){
26 [Link]("%4d", ele);
27 }
28 [Link]();
29 }
30 }
31 }
RAGGED ARRAY
These are arrays with unequal number of columns in the rows. In creating these arrays
 The row is first created during a declaration devoid of column count
 Each row is then assigned a 1-dimensional array with a size matching the column count for that row

Example
0 0 0 0 0 0
0 0 0 0
0 0 0 0 0

The program below creates array matching that described above


1 public class Experiments{
2 public static void main(String[] args){
3 // CREATE ROWS WITHOUT COLUMNS
4 int[][] arr = new int[3][];
5
6 // CREATE EACH COLUMN
7 arr[0] = new int[6];
8 arr[1] = new int[4];
9 arr[2] = new int[5];
10
11 // DISPLAY RAGGED ARRAY
12 for(int r = 0; r < [Link]; r++){
13 for(int ele : arr[r]){
14 [Link](ele + " ");
15 }
16 [Link]();
17 }
18 }
19 }

It is also possible to use loops in the creation. Two instances where this could happen include:
 The number of columns in the rows establish a numeric pattern
 The number of columns can be saved in an array, from which they can then be pulled up when necessary.

Example 1
0 0 0 0 0 0
0 0 0 0 0
0 0 0 0
0 0 0
0 0
0

1 public class Experiments{


2 public static void main(String[] args){
3 // CREATE ROWS WITHOUT COLUMNS
4 int[][] arr = new int[6][];
5
6 // TRAVERSE ROWS AND CREATE COLUMNS
7 int c = 6;
8 for(int r = 0; r < [Link]; r++){
9 arr[r] = new int[c];
10 c--;
11 }
12
13 // DISPLAY RAGGED ARRAY
14 for(int r = 0; r < [Link]; r++){
15 for(int ele : arr[r]){
16 [Link](ele + " ");
17 }
18 [Link]();
19 }
20 }
21 }

Example 2
1 public class Experiments{
2 public static void main(String[] args){
3 // COLUMN COUNT FOR THE ROWS
4 int[] cols = {10, 5, 8, 9, 4, 7, 11};
5
6 // CREATE ROWS WITHOUT COLUMNS
7 int[][] arr = new int[[Link]][];
8
9 // TRAVERSE ROWS AND CREATE COLUMNS
10 for(int r = 0; r < [Link]; r++){
11 arr[r] = new int[cols[r]];
12 }
13
14 // DISPLAY RAGGED ARRAY
15 for(int r = 0; r < [Link]; r++){
16 for(int ele : arr[r]){
17 [Link](ele + " ");
18 }
19 [Link]();
20 }
21 }
22 }
EXERCISES
1. Write a program that reads ten integers, and then display the number of even numbers and odd numbers. Assume that
the input ends with 0. Here is the sample run of the program.

Enter numbers: 1 2 3 2 1 6 3 4 5 2 3 6 8 9 9 0
The number of odd numbers: 8
The number of even numbers: 7

2. Write a method that finds the largest element in an array of double values using the following header:
public static double max(double[] array)
Write a test program that prompts the user to enter ten numbers, invokes this method to return the maximum value,
and displays the maximum value. Here is a sample run of the program:

Enter ten numbers: 1.9 2.5 3.7 2 1.5 6 3 4 5 2


The minimum number is: 6

3. This exercise uses a different but equivalent formula to compute the standard deviation of n numbers.

To compute the standard deviation with this formula, you have to store the individual numbers using an array, so they
can be used after the mean is obtained. Your program should contain the following methods:

/** Compute the deviation of double values */


public static double deviation(double[] x)
/** Compute the mean of an array of double values */
public static double mean(double[] x)

Write a test program that prompts the user to enter 10 numbers and displays the mean and standard deviation, as
presented in the following sample run:
Enter 10 numbers: 1.9 2.5 3.7 2 1 6 3 4 5 2
The mean is 3.11
The standard deviation is 1.55738

4. Write a method that returns the sum of all the elements in a specified row in a matrix using the following header:

public static double sumRow(double[][] m, int rowIndex)

Write a test program that reads a 3-by-4 matrix and displays the sum of each row. Here is a sample run:

Enter a 3−by−4 matrix row by row:


1.5 2 3 4
5.5 6 7 8
9.5 1 3 1
Sum of the elements at row 0 is 10.5
Sum of the elements at row 1 is 26.5
Sum of the elements at row 2 is 14.5

5. Write a method that averages all the numbers in the major diagonal in an n * n matrix of double values using the
following header:

public static double averageMajorDiagonal(double[][] m)

Write a test program that reads a 4-by-4 matrix and displays the average of all its elements on the major diagonal. Here
is a sample run:
Enter a 4−by−4 matrix row by row:
1 2 3 4.0
5 6.5 7 8
9 10 11 12
13 14 15 16
Average of the elements in the major diagonal is 8.625

6. Compute the alternating sum of all elements in an array. For example, if your program reads the input
1 4 9 16 9 7 4 9 11
then it computes
1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = –2

ARRAY LISTS
An array list is similar to an array in that, it represents a cluster of variables. However, unlike an array, it doesn’t have a
fixed size because its size can be increased (adding additional elements) or decreased (removing elements). Important
details are outlined below:
1. Package requires  [Link]
2. Declaration  ArrayList<Class> listName = new ArrayList<Class>();
Example
ArrayList<String> courseList = new ArrayList<String>();

Outlined below are some of the methods used in processing an array list:
1. [Link](listName) or [Link](listName)  prints the content of list in square brackets

2. add(object)  adds object to the end of the list


1 import [Link].*;
2 public class Experiments{
3 public static void main(String[] args){
4 ArrayList<String> codes = new ArrayList<String>();
5 [Link](codes);
6
7 [Link]("EEE234");
8 [Link]("\n" + codes);
9
10 [Link]("FCE246");
11 [Link]("\n" + codes);
12 }
13 }

3 add(index, object)  adds object to the list at the specified index, displacing the original element there.
1 public class Experiments{
2 public static void main(String[] args){
3 [Link]<String> codes = new [Link]<String>();
4
5 [Link]("EEE234");
6 [Link]("FCE246");
7 [Link](codes);
8
9 [Link](1, "EEE231");
10
11 [Link]("\n" + codes);
12 }
13 }

4 remove(index)  removes the element at the specified index


1 public class Experiments{
2 public static void main(String[] args){
3 [Link]<String> codes = new [Link]<String>();
4
5 [Link]("EEE234");
6 [Link]("FCE246");
7 [Link]("EEE231");
8 [Link](codes);
9
10 [Link](2);
11 [Link]("\n" + codes);
12 }
13 }

5 set(index, object)  replaces the element at the specified index with the object provided.
1 public class Experiments{
2 public static void main(String[] args){
3 [Link]<String> codes = new [Link]<String>();
4
5 [Link]("EEE234");
6 [Link]("FCE246");
7 [Link]("EEE231");
8 [Link](codes);
9
10 [Link](0, "FCE202");
11 [Link]("\n" + codes);
12 }
13 }

6 get(index)  retrieves the element at the specified index.


1 public class Experiments{
2 public static void main(String[] args){
3 [Link]<String> codes = new [Link]<String>();
4
5 [Link]("EEE234");
6 [Link]("FCE246");
7 [Link]("EEE231");
8
9 [Link]([Link](1));
10 }
11 }
7 size()  returns the number of elements in the list.
1 public class Experiments{
2 public static void main(String[] args){
3 [Link]<String> codes = new [Link]<String>();
4
5 [Link]("EEE234");
6 [Link]("FCE246");
7 [Link]("EEE231");
8
9 for(int i = 0; i < [Link](); i++)
10 [Link]([Link](i));
11 }
12 }

NOTE:
 Primitive data can only be used with array lists via their wrapper classes (wrappers)
 It is possible to store values directly in an array list using data from the keyboard
1 import [Link].*;
2 public class Experiments{
3 public static void main(String[] args){
4 ArrayList<Double> numbs = new ArrayList<Double>();
5 Scanner scan = new Scanner([Link]);
6
7 [Link]("Enter numbers, Q to quit:");
8 double n = 0;
9 while([Link]()){
10 [Link]([Link]());
11 }
12
13 [Link]("\n" + numbs);
14 }
15 }

Notice that from the above program it is possible to find out if the input stream has a particular type of data before
proceeding to the read the data. In line 9, the program used hasNextDouble(), which returns a boolean value.
Outlined below are the methods for some of the other data types

1. hasNextInt()
2. hasNext()
3. hasNextByte()
4. hasNextShort()
5. hasNextLong()
6. hasNextBoolean()
STRINGS
This data type is represented by the class String defined in the package [Link]. Within the class are important methods
that help with the processing of strings. Presented below is rundown of some of these methods:

1. String substring(int a): returns a substring of the main string starting from index a to the end
Example
“madam”.substring(1) = “adam”

2. String substring(int a, int b): returns a substring of the main string, starting from index a to (b-1)
Example
“madam”.substring(1, 4) = “ada”

3. int length(): returns the number of characters in a string


Example
“madam”.length() = 5

4. char charAt(int index): returns the character at the specified index of the string.
Example
“madam”.charAt(2) = ‘d’

5. boolean equals(String str): compares the parent string to str, and returns true if it is equal to str, and false otherwise.
Examples
“madam”.equals(“madam”) = true
“madam”.equals(“Madam”) = false

6. boolean equalsIgnoreCase(String str): similar to equals(…) but ignores the case of the characters.
Examples
“madam”.equalsIgnoreCase(“MADAM”) = true
“adam”.equalsIgnoreCase(“dam”) = false

7. int compareTo (String str): compares the parent string with str on a character by character basis, using their numeric
code. The result is negative if the parent string is lesser, 0 when it is equal to str, and positive when parent string is
greater.
Examples
“ben”.compareTo(“bed”) = 10 (same as ‘n’ – ‘d’)
“ben ”.compareTo(“ben”) = 1
“ben”.compareTo(“ben ”) = -2
“ben”.compareTo(“ben”) will return 0

8. boolean endsWith (String suffix): returns true if the string ends with the suffix and false otherwise.
Examples
“bed”.endsWith("n") = false
“bed”.endsWith(“ed”) = true

9. boolean startsWith (String prefix): returns true if the string begins with prefix and false otherwise
Examples
“bed”.startsWith(“n”) = false
“bed”.startsWith(“be”) = true
10. int indexOf(String str): searches the string from index 0, for the first occurrence of str. It returns the index (start
position) of the argument if it is in the string, otherwise it returns -1 to indicate the argument was not found in the
string.
Examples
“coconut”.indexOf("co") = 0
“coconut”.indexOf("tu") = -1

11. int indexOf (String str, int fromIndex): similar to the above method, but starts the search from the index represented
by the second argument.
Example
“coconut”.indexOf(“co”, 1) = 2
“coconut”.indexOf(“co”, 2) = 2
“coconut”.indexOf(“co”, 3) = -1

12. int lastIndexOf(String str): returns the start of the last occurrence of str in the parent string. Searching starts from
index 0. If the argument is not found, a -1 is returned to indicate this.
Example
“coconut”.lastIndexOf(“co”) = 2

13. boolean contains(String str): returns true if the parent string contains str, and false if it doesn’t.
Examples
“miebi.@[Link]”.contains(“@”) = true
“miebi.@[Link]”.contains(“$.”) = false

14. String replaceAll(String oldString, String newString): returns a new string formed by replacing all occurrences of
oldString with newString.
Example
“switch”.replaceAll(“w”, “t”) = “stitch”
15. String replaceFirst(String oldString, String newString): returns a new string by replacing the first occurrence of
oldString with newString.
Example
“inking”.replaceFirst("in", "as") = “asking”

16. String toLowerCase(): returns a new string by converting all characters in the original string to the lower case.
Example
"TIN".toLowerCase() = “tin”

17. String toUpperCase(): returns a new string formed by converting all characters in the original string to upper case.
Example
“tin”.toUpperCase() = “TIN”

18. String trim(): returns a new string by eliminating all leading and trailing spaces (white characters) in parent string.
Example
“ Hello ”.trim() = “Hello”

19. String[] split(String delimiter): it breaks up a string into substrings in an array by using the provided delimiter. An
empty string cannot be the last element in the array.
Example
“boo:and:foo”.split(“:”) will return the array { “boo”, “and”, “foo” }
“boo:and:foo”.split(“o”) will return the array { “b”, “”, “:and:f” }
USER-DEFINED METHODS
A method is block of reusable code. A method has a head and a body which carries its implementation. The basic syntax for
defining a method is given below:

modifier(s) returnType methodName(0 or more paraments){


// implementation
}

 The modifiers that are of interest at the moment are:


1. public  to improve access to the method
2. static  to make the method, a class method (no need to instantiate before invoking). If it is missing, the method is
an instance method.
 parameter  type name
 multiple parameters are presented in comma-separated form

CALLING/INVOKING A METHOD
Syntax: [Link](0 or more arguments)

Important points to note include:


1. parentName  class name (static), or object name (instance)
2. argument  value/literal or variable
3. multiple arguments are presented in a comma-separated form
4. invoking or calling a method causes the code in the body to be executed
5. if arguments are provided in the method call, they are copied into the parameters, for usage in the body during
execution

EXAMPLES
1. A pentagonal number is defined as n(3n-1)/2 for n = 1, 2, …, and so on. Therefore, the first few numbers are 1, 5, 12,
22, …. Write a method with the following header that returns a pentagonal number:

public static int getPentagonalNumber(int n)

For example, getPentagonalNumber(1) returns 1 and getPentagonalNumber(2) returns 5. Write a test program that uses
this method to display the first 100 pentagonal numbers with 10 numbers on each line. Use the %7d format to display
each number.
1 public class Experiments{
2 public static int getPentagonalNumber(int n){
3 return n*(3*n - 1)/2;
4 }
5
6 public static void main(String[] args){
7 for(int i = 1; i <= 100; i++){
8 [Link]("%7d", getPentagonalNumber(i));
9 if(i%10 == 0)
10 [Link]();
11 }
12 }
13 }
2. Write a method that computes the sum of the digits in an integer. Use the following method header:

public static int sumDigits(long n)

For example, sumDigits(234) returns 9 (= 2 + 3 + 4). (Hint: Use the % operator to extract digits and the / operator to
remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4). To remove 4 from 234, use 234 / 10
(= 23). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program that
prompts the user to enter an integer then displays the sum of all its digits.
1 public class Experiments{
2 public static int sumDigits(long n){
3 int sum = 0;
4 while(n > 0){
5 int digit = (int)(n%10);
6 sum += digit;
7 n = n/10;
8 }
9 return sum;
10 }
11
12 public static void main(String[] args){
13 [Link]("Enger an integer: ");
14
15 [Link] scan = new [Link]([Link]);
16 long numb = [Link]();
17 [Link]("Sum of digits = " + sumDigits(numb));
18
19 }
20 }

3. Write the methods with the following headers:

// Return the reversal of an integer, e.g., reverse(456) returns 654


public static int reverse(int number)

// Return true if number is a palindrome


public static boolean isPalindrome(int number)

Use the reverse method to implement isPalindrome. A number is a palindrome if its reversal is the same as itself. Write
a test program that prompts the user to enter an integer and reports whether the integer is a palindrome.
1 public class Experiments{
2 // Return the reversal of an integer, e.g., reverse(456) returns 654
3 public static int reverse(int number){
4 String reversedNum = "";
5 while(number > 0){
6 int digit = number%10;
7 reversedNum += digit;
8 number /= 10;
9 }
10 return [Link](reversedNum);
11 }
12
13 // Return true if number is a palindrome
14 public static boolean isPalindrome(int number){
15 return number == reverse(number) ? true : false;
16 }
17
18 public static void main(String[] args){
19 [Link]("Enger an integer: ");
20
21 [Link] scan = new [Link]([Link]);
22 int numb = [Link]();
23 if(isPalindrome(numb))
24 [Link](numb + " is a palindrome.");
25 else
26 [Link](numb + " is not a palindrome.");
27
28 }
29 }

ARRAYS AND METHODS


Important points to note when using arrays with methods include:
As return type
1. type[]  return type as a 1-dimensional array e.g. int[]
2. type[][]  return type as a 2-dimensional array e.g. int[][]
As parameter
1. type[] name  1-demensional array as a parameter. E.g. int[] scores
2. type[][] name  2-dimensional array as a parameter. E.g. int[][] scores

Example
1 public class Experiments{
2 public static int[][] duplicateArray(int[][] arr){
3 for(int r = 0; r < [Link]; r++){
4 for(int c = 0; c < arr[r].length; c++)
5 arr[r][c] *= 2;
6 }
7 return arr;
8 }
9 public static void showArray(int[][] arr){
10 for(int r = 0; r < [Link]; r++){
11 for(int c = 0; c < arr[r].length; c++)
12 [Link]("%3d", arr[r][c]);
13 [Link]();
14 }
15 }
16
17 public static void main(String[] args){
18 int[][] array = {
19 {5, 8, 2, 1},
20 {3, 4, 1, 7}
21 };
22
23 [Link]("ARRAY BEFORE DUPLICATION");
24 showArray(array);
25
26 [Link]("\nARRAY AFTER DUPLICATION");
27 showArray(duplicateArray(array));
28 }
29 }

VARIABLE-LENGTH ARGUMENT LIST


It is possible to make a single method take a varying number of arguments when invoked. The argument list is made up of
values of the same type. The argument is treated as an array in the method implementation. The syntax for this parameter
is given below:
type… name e.g. int… scores
Facts to note include:
3. a method can contain only one variable-length parameter
4. if it is present with other parameters, it must be the last in the list
5. it can be replaced with an array (of the same data type)

Example
1 public class Experiments{
2 public static double getMean(double... nos){
3 double sum = 0;
4 for(int i = 0; i < [Link]; i++){
5 sum += nos[i];
6 }
7 return sum/[Link];
8 }
9
10 public static void showVals(double... nos){
11 for(int i = 0; i < [Link]; i++){
12 String sp = (i < [Link] - 1) ? ", " : "";
13 [Link](nos[i] + sp);
14 }
15 }
16
17 public static void main(String[] args){
18 [Link]("Mean of ");
19 showVals(2.5, 5, 8, 9.3, 7, 1);
20 [Link](" = %.4f", getMean(2.5, 5, 8, 9.3, 7, 1));
21
22 double[] vals = {2.4, 3.5, 7.8};
23 [Link]("\n\nMean of ");
24 showVals(vals);
25 [Link](" = %.4f\n", getMean(vals));
26 }
27 }

OBJECTS AND CLASSES (USER-DEFINED)


An object is a reusable software component. Similar objects have common features (attributes and behavior/capability) and
as such can be described in a general way. The document describing a group of objects is called a class. For example, all
students have forename, surname, and sex etc. and all students register courses. This means, all students can be given a
general description. If students are objects, then this general description of students is called the CLASS

MEMBERS OF A CLASS
A class has a name that is a valid identifier that begins with a capital letter. This has been the case from the very beginning,
with all the applications written, thus far. It is not about to change.

VARIABLES
Represent the attributes of an object. Each comes with a name and normally takes value, which is used when creating an
object.

METHODS
There are regular methods and CONSTRUCTORS. The regular methods represent the capabilities of an object. The
constructor is the method invoked/called to create an object. Special features to note, in the definition of constructors are:
1. They have no return data type.
2. They bear the same name as the class.

ACCESS MODIFIERS
These are keywords used to either grant or restrict access to members. The common main ones are:
1. private: used to restrict access to a member. This is the default modifier given to members that are variables.
2. public: used to grant access to a member. This is the default modifier given to members that are methods.
NOTE
The modifier static, must be added to any member that can be accessed through a class. It is normally immediately after the
access modifier.

CLASS TEMPLATE
The template below is general view of what a class definition is like.

public class ClassName{


// ATTRIBUTE(S)
private dataType variableName;
:

// CONSTRUCTOR(S)
public ClassName(0 or more parameters){
// statements initializing attributes
}
:

// METHOD(S)
public returnDataType methodName(0 or more parameters){
// statements
}
:
}

NOTES
1. It is possible to have more than one method with the same name.
2. For (1) to happen, the methods must be different in terms of their parameter list.
3. This concept is called METHOD OVERLOADING.
4. Because attributes have restricted access, methods are normally provided to either change or get their values.
5. Methods mainly provided to change the values of attributes are called SETTERS.
6. Methods mainly provided to get or return the values of attributes are called GETTERS.
7. Once a class has been defined, it is normally used in an application. The rule for now is to make sure class and
application are in the same directory or folder.
8. Parameters provided in constructor and setters are normally given the same name as the attributes they are to initialize.
This is done simply the process of matching a parameter to its attribute. In order to differentiate parameter from
attribute during implementation, the keyword this, is normally used to provide the attribute i.e.
[Link] instead of just attributName which is the same as parameterName.

Example
Design a class named Triangle, representing a triangle with sides a, b, and c. Important formulas for this class include:

Perimeter = a + b + c
s = Perimeter / 2
Area = �(� − �)(� − �)(� − �)

The class contains:


 Private data fields a, b, and c.
 A constructor with the arguments a, b, and c.
 Three getters for a, b, and c.
 Three setters for a, b, and c.
 A method named formsTriangle() that returns true if s is greater than a, b, and c i.e. a, b, and c can form a
triangle.
 Methods getPerimeter() and getArea() that return the perimeter and area of the triangle respectively.
Write a test program that prompts the user to enter a, b, and c and displays the perimeter and area of the triangle. If the
sides can’t form a triangle, report that the provided sides can’t form a triangle.

[Link]
1 public class Triangle{
2 // ATTRIBUTES
3 private double a, b, c;

4 // CONSTRUCTOR
5 public Triangle(double a, double b, double c){
6 this.a = a;
7 this.b = b;
8 this.c = c;
9 }

10 // GETTERS
11 public double getA(){
12 return a;
13 }
14 public double getB(){
15 return b;
16 }
17 public double getC(){
18 return c;
19 }

20 // SETTERS
21 public void setA(double a){
22 this.a = a;
23 }
24 public void setB(double b){
25 this.b = b;
26 }
27 public void setC(double c){
28 this.c = c;
29 }
30
31 // OTHER METHODS
32 public boolean formsTriangle(){
33 double s = (a + b + c) / 2;
34 if(s <= a || s <= b || s <= c)
35 return false;
36 else
37 return true;
38 }
39
40 public double getPerimeter(){
41 return a + b + c;
42 }
43
44 public double getArea(){
45 double s = (a + b + c) / 2;
46 double area = [Link](s * (s - a) * (s - b) * (s - c));
47 return area;
48 }
49 }

[Link]
1 import [Link].*;
2
3 public class App{
4 public static void main(String[] args){
5 [Link]("Ener sides a, b, and c of a triangle: ");
6
7 double a, b, c;
8 Scanner kb = new Scanner([Link]);
9 a = [Link]();
10 b = [Link]();
11 c = [Link]();
12
13 Triangle t = new Triangle(a, b, c);
14
15 if([Link]()){
16 [Link]("\nPerimeter = " + [Link]());
17 [Link]("Area = " + [Link]());
18 }
19 else
20 [Link](
21 "\n" + [Link]() + ", " + [Link]() + ", and " + [Link]() + " can\'t form a triangle."
22 );
23 }
24 }

Sample run 1
Ener sides a, b, and c of a triangle: 5 7 9

Perimeter = 21.0
Area = 17.41228014936585

Sample run 2
Ener sides a, b, and c of a triangle: 5 2 7

5.0, 2.0, and 7.0 can't form a triangle.

EXCEPTION HANDLING
The term for a runtime error in Java is EXCEPTION. Returning of program output is discontinued the moment an
exception is encountered. Dealing with it requires using a try-catch block. Syntax for it
try{
// statements
}
catch(Exception var){
// statements
}
Note
1. The try-block contains the statement(s) that can raise exception.
2. The statements in the catch block are only executed if an exception occurs.
Example
1 public class Test { 1 public class Test {
2 public static void main(String[] args){ 2 public static void main(String[] args){
3 try{ 3 try{
4 [Link]("START"); 4 [Link]("START");
5 [Link](4/2); 5 [Link](4/2);
6 [Link]("END"); 6 [Link]("END");
7 } 7 }
8 catch(Exception err){ 8 catch(Exception err){
9 [Link]("No / by 0"); 9 [Link]("No / by 0");
10 } 10 }
11 } 11 }
12 } 12 }

Output Output
START START
2 No / by 0
END

3. You can have multiple catch-blocks, with each dedicated to handling a specific type of exception.
try{
//statements
}
catch(Exception1 var1){
// statements
}
catch(Exception2 var2){
// statements
}
:
catch(ExceptionN varN){
// statements
}

4. Sometimes the catch-block(s) is followed by a finally-block which represents statements that must be executed,
whether an exception was raised or not.
try{
// statements
}
catch(Exception var){
// statements
}
finally{
// statements
}
Example
1 public class Test { 1 public class Test {
2 public static void main(String[] args){ 2 public static void main(String[] args){
3 try{ 3 try{
4 [Link]("START"); 4 [Link]("START");
5 [Link](4/2); 5 [Link](4/0);
6 [Link]("END"); 6 [Link]("END");
7 } 7 }
8 catch(Exception err){ 8 catch(Exception err){
9 [Link]("No / by 0"); 9 [Link]("No / by 0");
10 } 10 }
11 finally{ 11 finally{
12 [Link]("Hi from finally"); 12 [Link]("Hi from finally");
13 } 13 }
14 } 14 }
15 } 15 }

Output Output
START START
2 No / by 0
END Hi from finally
Hi from finally

BASIC FILE PROCESSING


Programs written thus far, get user data from the keyboard, while program output have always been sent to the screen. We
will now explore the use (text) files in the system for program input and output operations.
OUTPUT TO FILE
Steps to follow:
In a try-block
1. Create an object from [Link] using the path/URL to the file as argument i.e.
[Link] pw = new [Link](“File path”);
2. Use print(…), println(…), and printf(…) through the object from (1) to send program output to the file.

3. Invoke close() through the object from (1) to close the file and release system resources, once the task is
completed.
Note
1. Creating the PrintWriter object will create a new file that overwrites an existing version.
2. Use import [Link].*; to make [Link] just PrintWriter.
3. For paths with one or more slashes, use \\ or /.
4. File path is either absolute or relative.
5. Absolute file path begins with the drive letter.
6. Relative file path begins from where the source file is located.
7. Relative path can be obtained from the absolute path by removing all directories before the source file from the
absolute path of the file.
Examples
a. C:/Users/Tony/Desktop/[Link]  C:/Users/Tony/Desktop/[Link]  “[Link]” = Relative path
b. C:/Users/Tony/Desktop/[Link]  C:/Users/Tony/Desktop/output/[Link]  “output/[Link]” = Relative path
8. All directories listed in the file path, must exist before program execution to prevent an exception
(NullPointerException). If they don’t exist, then they must be created before program execution.

Example
1 import [Link].*;
2
3 public class App {
4 public static void main(String[] args){
5 PrintWriter pw = null;
6 try{
7 pw = new PrintWriter("[Link]");
8 [Link]("%-5s%-8s\n", "x", "cos(x)");
9 [Link]("%-5s%-8s\n", "***", "*******");
10 for(int i = 0; i <= 360; i+=20){
11 [Link]("%-5d%+-8.4f\n", i, [Link]([Link](i)));
12 }
13 }
14 catch(Exception err){
15 [Link]("An error occurred.\n" + [Link]());
16 }
17 finally{
18 [Link]();
19 }
20 }
21 }

Output (Content of [Link])


x cos(x)
*** *******
0 +1.0000
20 +0.9397
40 +0.7660
60 +0.5000
80 +0.1736
100 -0.1736
120 -0.5000
140 -0.7660
160 -0.9397
180 -1.0000
200 -0.9397
220 -0.7660
240 -0.5000
260 -0.1736
280 +0.1736
300 +0.5000
320 +0.7660
340 +0.9397
360 +1.0000

INPUT FROM FILE


In a try-block
1. Create an object of the class [Link], supplying the file path/URL as string argument to the constructor.
File name = new File(“File path/URL”);

2. Construct an object of the class [Link], with the File object from (1) supplied as argument (data source)
to the constructor.
Scanner name = new Scanner(file_object);

After creating the Scanner object has been created, you will be able to use all Scanner methods you are already familiar
with, through the object to get data from the file. It is very important to
Example 1
1 import [Link].*;
2 import [Link].*;
3
4 public class ReadFromFile {
5 public static void main(String[] args){
6 Scanner dataSource = null;
7 try{
8 dataSource = new Scanner(new File("[Link]"));
9 while([Link]())
10 [Link]([Link]());
11 }
12 catch(Exception err){
13 [Link]("An error occurred.\n" + [Link]());
14 }
15 finally{
16 [Link]();
17 }
18 }
19 }

Output
x cos(x)
*** *******
0 +1.0000
20 +0.9397
40 +0.7660
60 +0.5000
80 +0.1736
100 -0.1736
120 -0.5000
140 -0.7660
160 -0.9397
180 -1.0000
200 -0.9397
220 -0.7660
240 -0.5000
260 -0.1736
280 +0.1736
300 +0.5000
320 +0.7660
340 +0.9397
360 +1.0000

It is important to know in advance, the nature of the data in the file. This helps when trying to do more in terms of how
the data read from the file can be processed in the program.

Example 2
1 import [Link].*;
2 import [Link].*;
3
4 public class ReadFromFile2 {
5 public static void main(String[] args){
6 Scanner dataSource = null;
7 try{
8 dataSource = new Scanner(new File("[Link]"));
9
10 // Read the column heads
11 [Link]("%-3s | %7s\n",[Link](),[Link]());
12 [Link](); // break to the next line
13
14 // Read the line (replacing asterisks with dash)
15 [Link](
16 "%-3s-|-%7s\n",
17 ([Link]()).replace('*','-'),
18 ([Link]()).replace('*','-')
19 );
20 [Link]();
21
22 // Read the (integers and real/fractional) numbers
23 while([Link]()){
24 [Link]("%-3d | %+7.4f\n",[Link](),[Link]());
25 }
26 }
27 catch(Exception err){
28 [Link]("An error occurred.\n" + [Link]());
29 }
30 finally{
31 [Link]();
32 }
33 }
34 }

Output
x | cos(x)
----|--------
0 | +1.0000
20 | +0.9397
40 | +0.7660
60 | +0.5000
80 | +0.1736
100 | -0.1736
120 | -0.5000
140 | -0.7660
160 | -0.9397
180 | -1.0000
200 | -0.9397
220 | -0.7660
240 | -0.5000
260 | -0.1736
280 | +0.1736
300 | +0.5000
320 | +0.7660
340 | +0.9397
360 | +1.0000

You might also like