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

Java 200 LManual

Uploaded by

b.shehabat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Java 200 LManual

Uploaded by

b.shehabat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Kuwait University

Collage of Engineering and Petroleum


Computer Engineering Department

___________________________________________________

ENG-200: Computer Programming for Engineers

Java How to Program

Prepared by:
Eng. Aisha Alkandari
Eng. Aisha Alnoori
Eng. Basma Alfahad
Eng. Zainab Bahbahani

Supervised by:
Dr. Asmaa Alsumait
Table of contents

Lab 0: Eclipse IDE for Java Developers ................................................................................................... 3


Lab 1: Introduction to Java Programming Flowcharts ......................................................................... 10
Lab 2: Introduction to Java Applications: Input/Output and Operators .............................................. 13
Lab 3: Java control statements (if / switch) ......................................................................................... 16
Lab 4: Java control statements (while loop) ........................................................................................ 21
Lab 5: Java control statements (do…while ,for loop) ........................................................................... 25
Lab 6: Arrays / Strings .......................................................................................................................... 29
Lab 7: Methods .................................................................................................................................... 33
Lab 8: Using Arrays with Methods ....................................................................................................... 37
Lab 9: Introduction to Classes and Objects.......................................................................................... 40

ENG-200 2 Computer Engineering Department


Lab 0: Eclipse IDE for Java Developers

Install Eclipse IDE

Step 1: Download
Download Eclipse from https://www.eclipse.org/downloads/packages/installer. The Eclipse
Installer 2022-03 R now includes a JRE for macOS, Windows and Linux.

Choose "Windows x86_64" (e.g., "eclipse-java-202x-xx-R-win32-x86_64.zip"- about


313MB) ⇒ Download.

ENG-200 3 Computer Engineering Department


Step 2: Install
To install Eclipse, simply Double-click the downloaded application (eclipse-inst-jre-
win64.exe).

Choose “Eclipse IDE for Java Developers” ⇒ INSTALL ⇒ LAUNCH.

ENG-200 4 Computer Engineering Department


Choose an appropriate directory for your workspace, i.e., the directory (or folder) that you
would like to save your files (e.g., c:\myProject\eclipse_workspace) ⇒ Launch.

If the "Welcome" screen shows up, close it by clicking the "close" button next to the "Welcome"
title.

Writing your First Java Program in Eclipse

Step 1: Create a new “Java Project”


For each Java application, you need to create a project to keep all the source files, classes
and relevant resources.
To create a new "Java project":
1. Choose "File" menu ⇒ "New" ⇒ "Java project".

ENG-200 5 Computer Engineering Department


2. The "New Java Project" dialog pops up.
a. In "Project name", enter "FirstProject".
b. Check "Use default location".
c. In "JRE", select "Use an execution environment JRE (JavaSE-xx).
Make sure that your JDK is 17 and above.
d. In "Project Layout", check "Use project folder as root for sources and
class files".
e. In "Module", UNCHECK "Create module-info.java" file. If "Create
module-info.java" dialog appears, click "Don't Create" (This will not appear
if you do step 2(e)).
Push "Finish" button.

Step 2: Write a Hello-world Java Program (or Java Class)


1. In the "Package Explorer" (left pane) ⇒ Right-click on "FirstProject" (or use the
"File" menu) ⇒ New ⇒ Class

ENG-200 6 Computer Engineering Department


2. The "New Java Class" dialog pops up.
a. In "Source folder", keep the "FirstProject".
b. In "Package", leave it EMPTY. Delete the content if it is not empty.
c. In "Name", enter "Hello".
d. Check "public static void main(String[] args)".
e. Don't change the rest.
Push "Finish" button.

3. The source file "Hello.java" opens on the editor panel (the center pane). Enter
the code below

ENG-200 7 Computer Engineering Department


Step 3: Compile & Execute the Java Program
1. There is no need to compile the Java source file in Eclipse explicitly. It is
because Eclipse performs the so-called incremental compilation, i.e., the Java
statement is compiled as and when it is entered.
2. To run the program, right-click anywhere on the source file "Hello.java" (or
choose "Run" menu) ⇒ Run As ⇒ Java Application.

3. The output "Hello, world!" appears on the Console pane (the bottom pane).

NOTES:
• You should create a NEW Java "project" for EACH of your Java application.
• Nonetheless, Eclipse allows you to keep more than one programs (classes) in a
project, which is handy for writing toy programs. To run a particular program, open
and right-click on the source file ⇒ Run As ⇒ Java Application.
• Clicking the "Run" button (with a "Play" icon) runs the recently-run program (based
on the previous configuration). Try clicking on the "down-arrow" besides the "Run"
button.

ENG-200 8 Computer Engineering Department


Correcting Syntax Errors

Eclipse performs incremented compilation, as and when a source "line" is entered. It marked
a source line having syntax error with a RED CROSS. Place your cursor at the RED CROSS
to view the error message.
You CANNOT RUN the program if there is any syntax error (marked by a RED CROSS
before the filename).
Correct all the syntax errors and RUN the program.

HINTS:
In some cases, Eclipse shows an ORANGE LIGHT-BULB (for HINTS) next to the ERROR
RED-CROSS (Line 5 in the above diagram). You can click on the LIGHT-BULB to get a list of
HINTS to resolve this particular error, which may or may not work!

SYNTAX WARNING:
marked by an orange triangular exclamation sign. Unlike errors, warnings may or may not
cause problems. Try to fix these warnings as well. But you can RUN your program with
warnings.

ENG-200 9 Computer Engineering Department


Lab 1: Introduction to Java Programming Flowcharts

Objective:

1. Understand the steps required to solve a problem.


2. Use flowchart to solve a problem.
3. Draw flowcharts using a diagramming application such as Microsoft Visio.

Introduction:

An algorithm is a step-by-step set of instructions that provides a solution for a problem. The
flow chart is a diagram that can be used to represent an algorithm. The most commonly used
symbols in the flow charts are shown in the following table.

Symbol Name Function

Indicates any processing


Process
function

Indicates that the computer


Input/Output is to obtain data or output
results

Indicates a decision point


Decision that leads to two paths
(Yes/No, True/False)

Indicates flowchart
Connector connection to another
symbol

Predefined Process Used to invoke a function

Indicates the start or end of


Terminal
a program

Flow Lines Show direction of flow

ENG-200 10 Computer Engineering Department


Using Microsoft Visio:

Microsoft Visio is a diagramming application and is part of Microsoft Office 365 applications.
To access Visio on you Microsoft 365 account, you can use the following link:
www.office.com/launch/visio. You may also log into your account on office.com and locate
Visio link using the App launcher on the top left corner of your window. To start working on
Visio:

1. From the main window, click on Flowchart Template as shown in the following figure:

2. From Design menu, you can change the theme and colors as shown in the following
figure:

ENG-200 11 Computer Engineering Department


3. From Basic Flowchart Shapes, you can drag and drop the shapes into the design area.
You can double-click on the shape to add text inside the shape. You can also point the
cursor to a shape to see a connection point and you may point to another shape to create
a connector between two shapes.

Lab Exercises:

1. Draw a flowchart for finding the greatest number among two numbers and print the
result.
2. Draw a flowchart for finding whether a number is odd or even and print the result.
3. Draw a flowchart for printing the first 10 even numbers.
4. Draw a flowchart for calculating the average from 20 exam scores and print the result

Challenging Problems:

1. Draw a flowchart for checking whether a number n is prime or not and print the result.
2. Draw a flowchart for finding and printing the first 10 number in the Fibonacci sequence.

ENG-200 12 Computer Engineering Department


Lab 2: Introduction to Java Applications: Input/Output and
Operators

Objective:

1. Use input and output statements.


2. Write simple Java applications.
3. Use arithmetic, relational, and equality operators.
4. Write simple decision-making statements.

Introduction:

In this lab, we will introduce the first Java program that displays output messages on the
screen. Figure 1 shows a program that displays a line of text on the screen using three
different Java print methods. Note that line numbers at the beginning of each line of code is
not part of the Java program. Line 1 and 2 show single-line comments while lines 17-19 show
a multiple-line comment.

Figure 1 Printing text

The second Java program reads, or inputs an integer typed by the user through the keyboard.
Many useful methods used to read different types of inputs are members of the Scanner
class from the package named java.util that is part of Java API (Java Application
Programming Interface).
Figure 2 shows a program that reads an integer from the user and then displays the integer
using printf method. Line 1 shows the import declaration that is required to use class
Scanner. Line 7 creates a Scanner object to use methods of the class to read characters
typed by the user at the keyboard.

ENG-200 13 Computer Engineering Department


Figure 2 Reading inputs

Common programming errors:

A syntax error occurs when the compiler finds code that violates Java’s language rules or
syntax. Syntax errors are also called compilation errors because the compiler detects these
errors when compiling the program. When a syntax error is detected, the compiler issues an
error message.

A logical error is an error in the way a program works. The program can execute but produces
incorrect results.

• A compilation error occurs if a public class’s filename is not exactly the same name as
the class followed by the .java extension.
• It is a syntax error if braces do not occur in matching pairs.
• Placing an import declarations inside of after a class declaration is a syntax error.
• Forgetting to include an import declarations for a class that must be imported results in
a compilation error.

Good programming practice:

• It is a good practice to begin your program with a comment that states the purpose of the
program and the author.
• Use blank lines and indentation in your program to enhance readability.
• By convention, begin the class name with a capital letter and capitalize the first letter of
each word they include (e.g., SampleClassName). This naming convention is known as
camel case.
• Indent the entire body of each class declaration one level between the braces that delimit
the class. IDEs typically indent code for you. The Tab key may also be used to indent
code.
• Indent the entire body of each method declaration one level between the braces that
define the method’s body.
• Place a space after each comma (,) in an argument list to make programs more readable.
• Declare each variable in its own declaration to allow a descriptive comment to be inserted
next to each variable.
• Choosing meaningful variable names helps a program to be self-documenting.
• By convention, variable-name identifier use the camel-case naming convention with a
lowercase first letter (i.e. firstNumber).

ENG-200 14 Computer Engineering Department


Lab Exercise:

Write a Java application that reads two integers and determines whether if the first integer is
divisible by the second integer and prints the quotient. If the first number is not divisible by
the second number, the program prints the remainder.

Sample Output 1:
Enter first integer: 10
Enter second integer: 5
10 is divisible by 5
10 / 5 = 2

Sample Output 2:
Enter first integer: 10
Enter second integer: 3
When 10 is divided by 3, the remainder is 1

Challenging Problems:

3. Write a Java application that inputs a 5-digit number from the user, separates the number
into individual digits, then prints the sum of the digits. For example, if the user types the
number 12345, the program should print sum = 15. Assume the user enters the correct
number of digits.
4. Write a Java application that add two 2-bit binary numbers.
5. Write a Java application that converts a 3-bit binary number to decimal.
6. Write a Java application that reverse a 3-digit decimal number.
7. Write a Java application that reads an integer n and computes the value n + nn + nnn. For
example, if the user inputs 5, you should print the value of 5 + 55 + 555.

ENG-200 15 Computer Engineering Department


Lab 3: Java control statements (if / switch)
- Logical Operators
- If statement
- If…else statement
- Nested if…else statement
- switch Multiple-Selection Statement

Objective:

1. Learn basic problem-solving techniques.


2. Use the logical operators to form complex conditional expressions in control statements.
3. Use if and if…else selection statements to choose between alternative actions.
4. Use the conditional operator in place of if…else statements.
5. Learn multiple selection using the switch selection statement.

Introduction:

Simple conditions are expressed in terms of the relational operators where each expression
tests only one condition. In this lab we will discover the logical operators that enable you to
form more complex conditions by combining simple conditions.

Java has three types of section statements. In this lab, we will learn how to use two types of
selection statements.
1- Single selection statement: if statement either selects an action, if the condition is
true, or skips it, if the condition is false.
(selects or ignores a single action/group of actions)
2- Double selection statement: if…else statement selects an action if the condition is
true and performs a different action if the condition is false.
(selects between two different actions/group of actions)
The last topic to be explained in this lab is switch statement that performs different actions
based on the possible values of a constant integral expression.

Logical Operators :

Logical operators are used to check whether an expression is true or false. They are used in
decision making.
Operator
Operator Example Meaning
name
true only if both
expression1 && expression2 expression1 and
&& Logical AND
expression2 are
true.
true if either
expression1 || expression2 expression1 or
|| Logical OR
expression2 is
true
true if expression
! Logical NOT !expression is false and vice
versa.

ENG-200 16 Computer Engineering Department


Syntax of single-selection if statement:

if (condition)
statement;
or

if (condition) {
block of statements;
}
Flowchart of single-selection if statement:

Syntax of double-selection if…else statement:

if (condition)
{statement/s;}
else
{statement/s;}

Flowchart of double-selection if…else statement:

ENG-200 17 Computer Engineering Department


Syntax of Nested if…else statement:

if (condition)
{statement/s;}
else
{if (condition)
{statement/s;}
else
{if (condition)
{statement/s;}
else
{statement/s;}
}
}

Flowchart of Nested if…else statement:

Syntax of switch multiple-selection statement :

switch (expression)
{
case value1:
Statement/s;
break; //optional
case value2 :
Statement/s;
break; //optional
case value3 :
Statement/s;
break; //optional

default :
Statement/s
break; //optional
}

ENG-200 18 Computer Engineering Department


Syntax of switch multiple-selection statement :

Common programming errors:

• In a nested if...else statement, ensure that you test for all possible cases.
• Placing a semicolon after the condition in an if or if...else statement leads to a logic error
in single-selection if statements and a syntax error in double-selection if...else statements
(when the if-part contains an actual body statement).
• Forgetting the left and/or right parenthesis for the condition in an if statement is a syntax
error.
• Confusing the equality operator, ==, with the assignment operator, =, can cause a logic
error or a syntax error.
• Use expressions of the same type for the second and third operands of the ?: operator to
avoid subtle errors.

Good programming practice:

• In expressions using &&, a condition—we’ll call this the dependent condition—may require
another condition to be true for the dependent condition’s evaluation to be meaningful. In
this case, the dependent condition should be placed after the && operator to prevent
errors. Consider the expression (i != 0) && (10 / i == 2). The dependent condition (10/i==2)
must appear after the && to prevent the possibility of division by zero.
• Indent both body statements of an if...else statement. Most IDEs do this for you.
• If there are several levels of indentation, each level should be indented the same additional
amount of space.
• Conditional expressions are more difficult to read than if…else statements and should be
used to replace only simple if…else statements that choose between two values.
• Although each case and the default case in a switch can occur in any order, place the default
case last. When the default case is last, the break for that case is not required.
• Forgetting a break statement when one is needed in a switch is a logic error.
• In a switch statement, ensure that you test all possible values of the controlling expression.

ENG-200 19 Computer Engineering Department


Lab Exercise:

1- Write a Java application that reads three numbers from the user, then prints the
greatest number.

Sample Output :
Enter first number: 52
Enter second number: 87
Enter third number: 78

The greatest number is 87

2- Write a Java application that takes a year from the user, then prints whether that
year is a leap year or not.

Sample Output 1:
Enter a year: 2020
2020 is a leap year

Sample Output 2:
Enter a year: 2022
2020 is not a leap year

3- Write a Java program to find a month in words.(use switch)

Sample Output :

Enter a month number: 2


February

Challenging Problems:

8. Write a Java application that will take a four digit number from the user, then prints a new
number with digits reversed as of original one

ENG-200 20 Computer Engineering Department


Lab 4: Java control statements (while loop)
- While iteration statement
- Formulating Algorithms
- Compound assignment operators
- Increment and decrement operators

Objective:

1. Use the while iteration statement to execute statements in a program repeatedly.


2. Use counter-controlled iteration and sentinel-controlled iteration.
3. Use the compound assignment operator and the increment and decrement operators.

Introduction:

An iteration statement (looping) allows you to specify that a program should repeat an action
while some condition remains true. In this lab we will learn how to use two formulating
algorithms . The first one is Counter-controlled iteration, the second one is Sentinel-controlled
iteration. In addition, we will learn how to compound the assignment operators as well as how
to use the increment (++) and decrement(- -) operators.

Syntax of while iteration statement:

while (condition)
{

block of statements;
}

Flowchart of while iteration statement:

ENG-200 21 Computer Engineering Department


Formulating Algorithms:

1- Counter-controlled iteration:
Uses a variable called a counter (or control variable) to control the number of
times a set of statements execute. It is often called definite iteration, because the
number of iterations is known before the loop begins executing.
counter =0
while (counter < number of iterations)
{

block of statements;
counter = counter +1;
}

2- Sentinel-controlled iteration:
A special value called a sentinel value (also called a signal value, a dummy
value or a flag value) is used to indicate “end of data entry.”. The sentinel value must
be chosen that cannot be confused with an acceptable input value.

input value
while (value != stopping value)
{

block of statements;
input value;
}

Compound Assignment Operators:

The compound assignment operators abbreviate assignment expressions.

variable = variable operator expression;

where operator is one of the binary operators +, -, *, / or % and the same variable name is
used can be written in the form

variable operator = expression;

Increment and Decrement Operators:

Java provides two unary operators for adding 1 to or subtracting 1 from the value of a
numeric variable. These are the unary increment operator, ++, and the unary decrement
operator, --.
Sample
Operator Operator name Explanation
expression

++a Increment a by 1, then use the new value of


++ Prefix increment
a in the expression in which a resides.
a++ Use the current value of a in the expression
++ Postfix increment
in which a resides, then increment a by 1.
--b Decrement b by 1, then use the new value of
-- Prefix decrement
b in the expression in which b resides.
b-- Use the current value of b in the expression
-- Postfix decrement
in which b resides, then decrement b by 1.

ENG-200 22 Computer Engineering Department


Common programming errors:

• Not providing in the body of a while statement an action that eventually causes the
condition in the while to become false normally results in a logic error called an infinite
loop (the loop never terminates).
• Using the value of a local variable before it’s initialized results in a compilation error. All
local variables must be initialized before their values are used in expressions.
• To avoid error, initialize each total and counter, either in its declaration or in an assignment
statement. Totals are normally initialized to 0. Counters are normally initialized to 0 or 1,
depending on how they’re used.
• Assuming that integer division rounds (rather than truncates) can lead to incorrect results.
For example, 7÷ 4, which yields 1.75 in conventional arithmetic, truncates to 1 in integer
arithmetic, rather than rounding to 2.
• Omitting the braces that delimit a block can lead to logic errors, such as infinite loops. To
prevent this problem, some programmers enclose the body of every control statement in
braces, even if the body contains only a single statement.
• A cast operator can be used to convert between primitive numeric types, such as int and
double. Casting to the wrong type may cause compilation errors or runtime errors.
• Using floating-point numbers in a manner that assumes they’re represented precisely can
lead to incorrect results.
• Attempting to use the increment or decrement operator on an expression other than one
to which a value can be assigned is a syntax error. For example, writing ++(x + 1) is a
syntax error, because (x + 1) is not a variable.

Good programming practice:

• In a sentinel-controlled loop, prompts should remind the user of the sentinel.


• Unlike binary operators, the unary increment and decrement operators should be placed next
to their operands, with no intervening spaces.

Lab Exercise:

4- Write a Java application that find the summation of numbers from 1 to a given number.

Sample Output :

Enter a number: 10
The summation of numbers from 1 to 10 = 55

5- Write a Java application to display the pattern like right angle triangle of a given
number.

Sample Output :

Enter a number: 5
1
12
123
1234
12345

ENG-200 23 Computer Engineering Department


Challenging Problems:

9. Write a Java application to display the number rhombus structure


1
212
32123
4321234
543212345
65432123456
7654321234567
65432123456
543212345
4321234
32123
212
1

ENG-200 24 Computer Engineering Department


Lab 5: Java control statements (do…while ,for loop)
- do…while Iteration Statement
- for Iteration Statement

Objective:

1. Use the do...while iteration statements to execute statements in a program


repeatedly.
2. Use the for iteration statement to execute statements in a program repeatedly.

Introduction:

In this lab we will study how to use the do...while statement which is similar to the while
iteration statement. In the while, the program tests the loop-continuation condition at the
beginning of the loop, before executing its body; if the condition is false, the body never
executes. The do...while statement tests the loop-continuation condition after executing the
loop’s body; therefore, the body always executes at least once.

Java provides the for iteration statement, which specifies the counter-controlled-
iteration details in a single line of code. The for statement specifies all the details of counter-
controlled iteration in its header. When the for statement begins executing, its control variable
is declared and initialized. If the loop-continuation condition is initially true, the body executes.
After executing the loop’s body, the increment expression executes. Then the loop-
continuation test is performed again to deter-mine whether the program should continue with
the next iteration of the loop.

Syntax of do…while iteration statement :

do
{
block of statements;
}
while (condition)

Flowchart of do…while iteration statement :

ENG-200 25 Computer Engineering Department


Syntax of for iteration statement :

loop’s control determines modifies the


variable and whether the loop control variable’s
its initial value should continue value executing
executing

for (initialization; loopContinuationCondition; increment)

statement/s Required

Flowchart of for iteration statement :

Common programming errors:

• Using an incorrect relational operator or an incorrect final value of a loop counter in the
loop-continuation condition of an iteration statement can cause an off-by-one error.
• Using the final value and operator <= in a loop’s condition helps avoid off-by-one errors.
For a loop that outputs 1 to 10, the loop-continuation condition should be counter <= 10
rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is
correct). Many programmers prefer so-called zero-based counting, in which to count 10
times, counter would be initialized to zero and the loop-continuation test would be counter
< 10.
• When a for statement’s control variable is declared in the initialization section of the for’s
header, using the control variable after the for’s body is a compilation error.
• Placing a semicolon immediately to the right of the right parenthesis of a for header makes
that for’s body an empty statement. This is normally a logic error.
• Infinite loops occur when the loop-continuation condition in an iteration statement never
becomes false. To prevent this situation in a counter-controlled loop, ensure that the
control variable is modified during each iteration of the loop so that the loop-continuation
condition will eventually become false. In a sentinel-controlled loop, ensure that the
sentinel value is able to be input.

ENG-200 26 Computer Engineering Department


• Although the value of the control variable can be changed in the body of a for loop, avoid
doing so, because this practice can lead to subtle errors.

• Using an incorrect relational operator in the loop-continuation condition ofa loop that
counts downward (e.g., using i <= 1 instead of i >= 1 in a loop counting down to 1) is
usually a logic error.
• Do not use equality operators (!= or ==) in a loop-continuation condition if the loop’s control
variable increments or decrements by more than 1. For example, consider the for
statement header for (int counter = 1; counter != 10; counter += 2). The loop-continuation
test counter != 10 never becomes false (resulting in an infinite loop) because counter
increments by 2 after each iteration.

Good programming practice:

• For readability limit the size of control-statement headers to a single line if possible.

Lab Exercise:

6- Write a Java program that asks the user for an integer number, then prints its multiplication
table.

Sample Output :
Enter an integer number: 5
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25

7- Write a Java program that asks the user for an integer number, then prints its factorial.

Sample Output 1 :
Enter an integer number: 5
5! = 120

Sample Output 2 :
Enter an integer number: 7
7! = 5040

Challenging Problems:

1. In Java, we can create an ATM program for representing ATM transection. In the ATM
program, the user has to select an option from the options displayed on the screen.
The options are related to withdraw the money, deposit the money, check the balance,
and exit.
To withdraw the money, we simply get the withdrawal amount from the user and
remove that amount from the total balance and print the successful message.
To deposit the money, we simply get the deposit amount from the user, add it to the
total balance and print the successful message.
To check balance, we simply print the total balance of the user.
2. Write a Java program to display the following character rhombus structure.

ENG-200 27 Computer Engineering Department


A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDEFEDCBA
ABCDEFGFEDCBA
ABCDEFEDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A

3. In Java, we can create an ATM program for representing ATM transection. In the ATM
program, the user has to select an option from the options displayed on the screen.
The options are related to withdraw the money, deposit the money, check the balance,
and exit.
To withdraw the money, we simply get the withdrawal amount from the user and
remove that amount from the total balance and print the successful message.
To deposit the money, we simply get the deposit amount from the user, add it to the
total balance and print the successful message.
To check balance, we simply print the total balance of the user.

ENG-200 28 Computer Engineering Department


Lab 6: Arrays / Strings

Objective:

1. Declare, initialize, and manipulate arrays.


2. Pass arrays to methods and return arrays.
3. Learn the difference between primitive types and reference types.
4. Understand what are strings in java.
5. Be able to define string in java.
6. Be able to use string predefined methods to manipulate strings.

Introduction:

An array is a group of elements that can hold values of the same type. An array is an object,
so it is considered as reference type. The elements of the array can be either primitive types
or reference types.

Strings are an object variable type. They are immutable, which means they can-not be
changed. That doesn’t mean you can never modify a string when writing a program, it just
means that when you’re modifying it, it’s actually creating a new string each time a change
is made. Strings are stored as arrays of chars where each character has an index that can
be recall with. Their indexing is 0-based, so the first character of the string is at index 0. If a
string is used without being stored in a variable, such as in a print statement, it is referred to
as a literal. Strings are objects made from the String class which associated with some
useful and easy to use methods.

Syntax of Arrays:

The array can be created using the keyword new as follows:

array_type [] arrayName = new array_type[array_size];

The array_type can be primitive or reference type and the array_size can be replaced
by a literal value or a constant variable. When the array is created using new keyword, array
elements are initialized to the default values depending on the array type (i.e. 0 for int array,
False for boolean array, null for an array of references, etc). The array can be also created
and initialize using array initializer as follows:

array_type [] arrayName = {value1, value2, value3, …};

Every array object has its own length stored in a length instance variable.

ENG-200 29 Computer Engineering Department


Syntax of strings:

Define string in Java:

String <string variable name> = new String();

Example of strings methods:

1. s1.length(); This method will return the number of characters in string s1.
2. s1.equals(s2); This method is Boolean method and will return true if string s1 is
equal to string s2.
3. S1.replace(‘char1’,’char2’); This method will replace every existence of char1 in
the string with char2.
4. s1.reverse(); This method will reverse the string s1.
5. s1.charAt(index);This method will return the character located in the string s1 at
the given index.

Common programming errors:

• An index must be an int value or a value of a type that can be promoted to int (i.e. byte,
short, or char but not long). Otherwise, a compilation error occurs.
• In an array declaration, specifying the number of elements in the square brackets of the
declaration (e.g. int[12] c;) is a syntax error.
• Declaring multiple array variables in a single declaration can lead to subtle errors.
Consider the declaration int[] a, b, c;. If a, b and c should be declared as array
variables, then this declaration is correct. However, if only a is intended to be an array
variable, and b and c are intended to be individual int variables, then this declaration is
incorrect. The declaration int a[], b, c; would achieve the desired result.
• Assigning a value to a final variable after it has been initialized is a compilation error.
Similarly, attempting to access the value of a final variable before it is initialized results
in a compilation error.
• Any attempt to access an element outside that range of indices results in a runtime error
that’s known as an ArrayIndexOutOfBoundsException.
• Using java strings methods has different types and argument, make sure to follow the
exact format to prevent syntax and runtime errors.
• When two separate objects that contains the same value are compared with == the
result will be false, instead method equals must be used to determine whether the two
objects have the same content.

Good programming practice:

• For readability, keep each declaration on a separate line, and include a comment
describing the variable being declared.
• Constant variables also are called named constants. They often make programs more
readable than programs that use literal values (e.g. 10). A named constant such as
ARRAY_LENGTH clearly indicates its purpose, whereas a literal value could have different
meanings based on its context.
• Multiword named constants should have each word separated from the next with
underscore (_) as in ARRAY_LENGTH.
• Java provides many strings methods, using them will save time and effort. The following
link give more details about java strings methods:
• https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

ENG-200 30 Computer Engineering Department


Lab Exercise:

1- Write a Java application called GradeStatistics, that keeps the grades of 20


students and displays the average, minimum, maximum, standard deviation, and a
histogram of the grades. The program should store the grades in an array of type int.
Hint: Create an integer array and initialize it with random numbers in the range 0 to
99.

The standard deviation is given as

Sample Output:

The grades are:


79 87 41 5 4 96 78 72 97 21 13 57 73 90 41 21 94 72 75 81

The maximum grade is 97


The minimum grade is 4
The average is 59.85
The standard deviation is 31.95

2- Write a java program that reads two text value from the user and do some string
manipulation. The strings should be stored in object of type String s1 and s2. You
need to show the following menu for the use:
1. Reverse
2. Remove a character
3. Number of Uppercase
4. Number of digits
5. Compare two strings
6. Exit
:
• Reverse: Takes a string and reverse it.
• Remove a character: Takes a character and a string, and removes all occurrences of
that character in the string.
• Number of uppercase letters: Takes a string and prints the number of Uppercase letters
in the string.
• Number of digits: Takes a string and prints the number of digits in the string.
• Compare two strings: Checks whether two strings are equal or not. Use string
comparison methods ( s1.equals(s2) or s1.compareTo(s2)).

ENG-200 31 Computer Engineering Department


Challenging Problems:

10. Write a Java application that simulate the Tic Tac Toe game. Here are the requirements:
a. The first player is the user who inputs the move using the keyboard and the second
user is the computer who chooses the move randomly.
b. The board should be printed out every time a player makes a move.
c. You should be able to accept input of the player position and then place a symbol on
the board.
You can use a 3-by-3 array to represent the board. You can assume that 1 represents X,
0 represents O, and -1 represents an empty position. Use methods and control statements
in your program.

ENG-200 32 Computer Engineering Department


Lab 7: Methods

Objective:

1. Understand methods and method calls.


2. Use static methods that are associated with classes.
3. Build large program from small, simple pieces (divide and conquer).
4. Use Math methods from the Java API.
5. Use secure random-number generation.

Introduction:

Methods help you build a large program from small, simple units. Methods make program
development more manageable using divide and conquer approach, it also promotes software
reusability by using existing methods to build new programs and help the programmer to avoid
repeating code.

Random number generation is a very useful to implement programs that simulate real-life
application. The class SecureRandom that is available in the package java.security of
the Java API has several methods that can generate random values of different types. To
generate integers at random from sets of values other than ranges of consecutive integers,
you can use the following general statement:

number = shiftValue + differenceBetweenValues * randomNumbers.nextInt(scalingFactor);

Where shiftValue specifies the first number in the range of values, differenceBetweenValues
specifies the difference between consecutive values in the sequence, and scalingFactor
specifies how many numbers are in the range.

Method declaration and method call:

Method declaration:

public static return_type methodName(parameter_list){

// method body

The syntax shown above includes:


• The modifier public means that the method can be called from methods of other
classes.
• The keyword static means that the method is static method. Static methods in the
same class can call each other directly. If the static method is called in other class, the
class name should precede the method name (i.e. ClassName.methodName()).
• return_type specifies the type of data a method returns to the calling method after

ENG-200 33 Computer Engineering Department


performing the task. If the method does not return any information, you should use the
return type void.
• The method name convention is the camel case naming scheme that begins with
lowercase letter.
• The parameter list is a comma-separated list that includes a type and a variable name
for each parameter. If the method does not have any parameter, the list should be
empty. The method’s parameters are considered as local variables of the method and
can be used inside the method’s body.

There are three ways to call a method:


• Using a method name by itself to call another method of the same class.
• Using the class name followed by a dot (.) and the method name to call a static
method in another class.
• Using an object’s variable name followed by a dot (.) and the method name to call a
non-static method of the object. This will be discussed in lab 9.

Common programming errors:

• Declaring method parameters of the same type as float x, y instead of float x,


float y is a syntax error. A type is required for each parameter in the parameter list.
• A compilation error occurs if the number of arguments in a method call does not match
the number of parameters in the method declaration.
• It is a syntax error to break a String literal across lines. You can split a String into
several smaller Strings and use concatenation to form the desired String.
• Confusing the + operator used for concatenation with the + operator used for addition can
lead to strange results. For example, if y has the value 5, then the expression “y + 2 =
“ + y + 2 results in the string “y + 2 = 52”, because the concatenation operator +
is evaluated from left to right.
• Declaring a method outside the body of a class declaration or inside the body of another
method is a syntax error.
• Redeclaring a parameter as a local variable in the method’s’ body is a compilation error.
• Forgetting to return a value from a method that should return a value is a compilation error.
If a return type other than void is specified, the method must contain a return statement
that returns a value consistent with the method’s return type.
• Casting a primitive-type value to another primitive type may change the value if the new
type is not a valid promotion. For example, if casting a floating-point value to an integer
value may introduce truncation errors into the results.
• Declaring overloaded methods with identical parameter lists is a compilation error
regardless of whether the return types are different.

Good programming practice:

• By convention, method-name identifier use the camel-case naming convention with a


lowercase first letter (i.e. findArea()).
• Declare local variables as close to where they are first used as possible.

Lab Exercise:

Write a Java application that performs the following operations based on a user choice:
1. Reverse the digits of a number.
2. Check if a number is palindrome.
3. Check if a number is a perfect number.

ENG-200 34 Computer Engineering Department


4. Check whether a number is prime of not.
5. Count the number of prime numbers that exist up to a given number.

You should implement the following methods:


• reverseDigits: The method takes a number and returns the number after reversing
the order of its digits.
• isPalindrome: The method determines whether a number is palindrome or not. A
positive integer is palindrome if its value is the same after reversing the order of the
digits in the number.
• isPerfectNumber: The method determines whether a number is perfect number or
not. An integer number is a perfect number if its factors, including 1 but not including
the number itself, sum to the number. For example, 6 is perfect number because 6 =
1 + 2 + 3.
• isPrime: The method determines whether a number is prime or not. A positive
integer is prime if it is divisible by only 1 and itself.
• countPrimes: The method returns the number of prime numbers that exist up to and
including a given number.

HINT: you can call a method inside another method to avoid using repeated code and take
advantage of software usability.

Sample Output:

Please enter a number: 12345

1- Reverse the digits of a number.


2- Check if a number is palindrome.
3- Check if a number is a perfect number.
4- Check whether a number is prime of not.
5- Count the number of prime numbers that exist up to a given
number.
6- Exit

Enter your choice: 1

The reversed number is 54321

Please enter a number: 12321

1- Reverse the digits of a number.


2- Check if a number is palindrome.
3- Check if a number is a perfect number.
4- Check whether a number is prime of not.
5- Count the number of prime numbers that exist up to a given
number.
6- Exit

Enter your choice: 2

The number 12321 is a palindrome

Please enter a number: 28

ENG-200 35 Computer Engineering Department


1- Reverse the digits of a number.
2- Check if a number is palindrome.
3- Check if a number is a perfect number.
4- Check whether a number is prime of not.
5- Count the number of prime numbers that exist up to a given
number.
6- Exit

Enter your choice: 3

The number 28 is a perfect number

Please enter a number: 7

1- Reverse the digits of a number.


2- Check if a number is palindrome.
3- Check if a number is a perfect number.
4- Check whether a number is prime of not.
5- Count the number of prime numbers that exist up to a given
number.
6- Exit

Enter your choice: 8

Invalid choice!

Please enter a number: 6

1- Reverse the digits of a number.


2- Check if a number is palindrome.
3- Check if a number is a perfect number.
4- Check whether a number is prime of not.
5- Count the number of prime numbers that exist up to a given
number.
6- Exit

Enter your choice: 6

Thank you!

Challenging Problems:

1. Write a Java method isArmstrong that determines whether a number is an Armstrong


number or not. An Armstrong number is a whole number that is equal to the sum of its
digits raised to the power of the total number of digits. For example, 153 is Armstrong
number because there are three digits, and 153 = 13 + 53 + 33. You can test the method
by printing all Armstrong numbers between 0 to an input number.
2. Write a Java method the returns a string of the prime factors of a given number.
3. Write a Java application that simulate a rock, paper, scissors game. The two players are
the user and the computer. The user inputs the choice through the keyboard and the
computer chooses the move through random number generation (i.e. 0 = rock, 1 = paper,
2 = scissors). Use random number generation and methods in your program.

ENG-200 36 Computer Engineering Department


Lab 8: Using Arrays with Methods

Objective:

1. Pass arrays to methods and return arrays.


2. Learn the difference between primitive types and reference types.

Introduction:

This lab demonstrates how to pass arrays and individual array elements as arguments to
methods.

Pass-By-Value vs. Pass-By-Reference:


There are two ways to pass arguments in method calls in many programming languages:

1- Pass-by-value:
When an argument is passed by value, a copy of the argument’s value is passed to the
called method. The called method works exclusively with the copy. Changes to the called
method’s copy do not affect the original variable’s value in the caller.
2- Pass-by-reference:
When an argument is passed by reference, the called method can access the argument’s
value in the caller directly and modify that data, if necessary.

All arguments in Java are passed by value

A method call can pass two types of values to a method:


- Copies of primitive values, which can store exactly one value of its declared type at a
time. (e.g., values of type int or double)
- Copies of references to objects, which store the location of an object in the memory.

Syntax of passing arrays to methods:

To pass an array argument to a method, specify the name of the array without any brackets.

double[ ] array_name = new double[array_size] ;

then the method call

method_name(array_name);

Common programming errors:

• An index must be an int value or a value of a type that can be promoted to int (i.e. byte,
short, or char but not long). Otherwise, a compilation error occurs.

ENG-200 37 Computer Engineering Department


Good programming practice:

• Passing references to arrays, instead of the array objects themselves, makes sense for
performance reasons

Lab Exercise:

Write a Java application called GradeStatistics, that keeps the grades of 20 students and
displays the average, minimum, maximum, standard deviation, and a histogram of the grades.
The program should store the grades in an array of type int. Your program should include
the following methods:
• initArray: the method takes an integer array and initialize it with random numbers
in the range 0 to 99.
• maximum: the method takes an integer array and returns the maximum grade.
• minimum: the method takes an integer array and returns the minimum grade.
• average: the method takes an integer array and returns the average grade as double.
• standardDev: the method takes an integer array and returns the standard deviation
of the grades as double. The standard deviation is given as

.
• printArray: the method takes an integer array and prints the array elements.
• computeHistogram: the method takes an integer array and returns a new integer
array. The method counts the frequency of each grade and stores the count value in
the new array. Assume the first element of the new array stores the frequency of
grades in the range 0 to 9, the second element stores the frequency of grades in the
range 10 to 19, etc.
• printHistogram: the method takes an integer array and prints the histogram
horizontally. Hint: you can call method computeHistogram.

Sample Output:
The grades are:
79 87 41 5 4 96 78 72 97 21 13 57 73 90 41 21 94 72 75 81

The maximum grade is 97


The minimum grade is 4
The average is 59.85
The standard deviation is 31.95

The grades histogram:


0- 9: **
10-19: *
20-29: **
30-39:
40-49: **
50-59: *
60-69:
70-79: ******
80-89: **
90-99: ****

ENG-200 38 Computer Engineering Department


Challenging Problems:

Write a Java application that simulate the Tic Tac Toe game. Here are the requirements:
a) The first player is the user who inputs the move using the keyboard and the second
user is the computer who chooses the move randomly.
b) The board should be printed out every time a player makes a move.
c) You should be able to accept input of the player position and then place a symbol
on the board.
You can use a 3-by-3 array to represent the board. You can assume that 1 represents X,
0 represents O, and -1 represents an empty position. Use methods and control statements
in your program.

ENG-200 39 Computer Engineering Department


Lab 9: Introduction to Classes and Objects

Objective:

1. Declare a class and use it to create an object.


2. Declare instance variables in a class to implement the class’s attributes.
3. Declare methods in a class to implement the class’s behaviors.
4. Call an object’s method to make that method perform its task.

Introduction:

Classes: A class is a user defined prototype from which objects are created. It represents
the set of methods that are common to all objects of one type. In general, class declarations
can include these components, in order:
1. Modifiers: A class can be public or has default access.
2. class keyword: class keyword is used to create a class.
3. Class name: Class names begin with an uppercase letter, and method and
variable names begin with a lowercase letter.
4. Body: The class body surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provides the state
of the class and its objects, and methods are used to implement the behavior of the class
and its objects. Its declaration uses the same name as the class and it has no return type.
Objects: A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of:
1. State: It is represented by attributes of an object. It also reflects the properties of
an object.
2. Behavior: It is represented by methods of an object. It also reflects the response
of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.

Common programming errors:

• An attempt by a method that is not a member of a class to access a private member of


that class is a compilation error.
• A compilation error occurs if a program attempts to initialize an object of a class by
passing the wrong number or types of arguments to the class’s constructor.

ENG-200 40 Computer Engineering Department


Good programming practice:

• We prefer to list a class’s fields first, so that, as you read the code, you see the names
and types of the variables before they’re used in the class’s methods.
• Place a blank line between method declarations to separate the methods and enhance
program readability.

Lab Exercise:

Create a class called Student that has three instance variables: studentName (type String),
studentId (type int) and studentGpa (type double). Your class should have the following:

Student

-studentName : String
-studentId : int
-studentGpa : double

+Student(String, int, double)


+setStudentName (String) : void
+setStudentId(int) : void
+setStudentGpa(double) : void
+getStudentName() : String
+getStudentId() : int
+getStudentGpa() : double
Figure. 3
+displayStudentInfo(): void

• A constructor that initializes the three instance variables.


• set and get methods for each instance variable.
• A method displayStudentInfo to display all student’s data.

Write a test application named StudentTest that demonstrates class Student capabilities. In
the main method, do the following:
• Input two students’ data (name, id and gpa) from the user.
• Create two Student objects. Initialize the objects using the data entered by the user.
• Display both students’ data information.
• Compare both students gpa and display which one has higher gpa than the other

Sample Output
Enter student#1 info:
Name: Khalid Ali
ID: 2221011234
GPA: 2.54
Student’s name is Khalid Ali, ID number is 2221011234 with a GPA of 2.54

ENG-200 41 Computer Engineering Department


Enter student#2 info:
Name: Mariam Fahad
ID: 2230112233
GPA: 3.33
Student’s name is Mariam Fahad, ID number is 2230112233 with a GPA of 3.33

Mariam Fahad has a higher GPA than Khalid Ali

Challenging Problems:

Create a class called FindRoots that find the roots of a quadratic function ax2 + bx + c. where
a, b and c are double numbers and a can’t be 0. The class includes:
• Three instance variables: a (type double), b (type double) and c (type double).
• A constructor that initializes the three instance variables.
• set and get methods for each instance variable.
• A method getDiscriminant that will calculate and return the discriminant.
• A method calRoots that will calculate and display the roots of a quadratic function.
• A method DisplayQuadFunction that will return a string representation of a quadratic
function.

Write a test application named Test that do the following:


• Input the coefficients a, b and c from the user.
• Create one FindRoots object. Initialize the object using the data input by the user.
• Display the quadratic function.
• Display the roots of quadratic function.

Sample output 1:
Enter the coefficients a, b and c of quadratic function
a: 1
b: 5
c: 6
Quadratic function: 1.0*x^2 + 5.0*x + 6.0
There are 2 roots: -2.00 and -3.00

Sample output 2:
Enter the coefficients a, b and c of quadratic function
a: 1
b: 2
c: 1
Quadratic function: 1.0*x^2 + 2.0*x + 1.0
There is one root: -1.00
Sample output 3:
Enter the coefficients a, b and c of quadratic function
a: 2
b: 1
c: 5
Quadratic function: 2.0*x^2 + 1.0*x + 5.0
No roots, discriminant < 0.

ENG-200 42 Computer Engineering Department

You might also like