Java Programming - Basics
Java Programming - Basics
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.
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.
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.
import [Link];
import packageName.*;
}
}
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
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)
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
Output
b. %o (Base 8 integer)
[Link]("%o", 10); 12
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
Output
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;
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;
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
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
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.
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
Some important methods, as well as the value they return, and variables:
1. Math.E e (2.718281828459045)
2. [Link] π (3.141592653589793)
11. [Link](x) ex
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)
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].*;
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.
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
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.
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
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
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
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
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
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
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
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
Outputs
Enter any integer from 1 - 3999: 1978
Roman equivalent: MCMLXXVIII
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
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
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.
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:
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.
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:
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:
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:
EXERCISES
1. Write a class that contains the following two methods:
3. Write a method that finds the number of occurrences of a specified character in a string using the following header:
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
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 }
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.
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 }
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 }
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 }
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
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
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:
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:
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:
Write a test program that reads a 3-by-4 matrix and displays the sum of each row. Here is a sample run:
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:
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
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 }
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 }
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”
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:
CALLING/INVOKING A METHOD
Syntax: [Link](0 or more arguments)
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:
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:
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 }
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 }
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 }
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 }
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.
// 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 = �(� − �)(� − �)(� − �)
[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
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
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 }
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