Comprog Fundamentals Oblcbl Module 2nd 2022 2023 Java
Comprog Fundamentals Oblcbl Module 2nd 2022 2023 Java
COMPROG
Programming Language
About Java
A Brief History
● developed in early 1990s by James Gosling et. al. as the programming language
component of the Green Project at Sun Microsystems
● originally named Oak and intended for programming networked “smart”
consumer electronics
● launched in 1995 as a “programming language for the Internet”; quickly gained
popularity with the success of the World Wide Web
● currently used by around 5 million software developers and powers more than
2.5 billion devices worldwide, from computers to mobile phones
● Design Goals
o simple: derived from C/C++, but easier to learn
o secure: built-in support for compile-time and run-time security
o distributed: built to run over networks
o object-oriented: built with OO features from the start
o robust: featured memory management, exception handling, etc.
o portable: “write once, run anywhere''
o interpreted: “bytecodes” executed by the Java Virtual Machine
o multithreaded, dynamic, high-performance, architecture-neutral
o Bytecodes are the machine language understood by the Java virtual
machine
Java Platform
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Java Programming Environment
The following are video tutorials of some of the programming editors or Integrated
Development Environment (IDE) that can assist you in writing java programs. Follow the
steps in the installation of any of the following IDEs.
● Module 4: How to Install JDK and JCREATOR LE.mp4
● Module 4: How to Install Eclipse IDE w Java JDK 13 on Windows 10.mp4
● Module 4: How to Install NetBeans 11 IDE And Java JDK SE 14 on Windows 10 8
7.mp4
You may also choose to use some online java compilers enumerated below:
● https://replit.com/languages/java10
● https://www.jdoodle.com/online-java-compiler/
● https://www.onlinegdb.com/online_java_compiler
● https://www.w3schools.com/java/java_compiler.asp
● https://compiler.javatpoint.com/opr/online-java-compiler.jsp
● https://www.jgrasp.org/
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Fundamental Concepts
Java Comments
● Comments are notes written to a code for documentation purposes. Those texts
are not part of the program and do not affect the flow of the program.
Two types of comment
o Single Line Comment
Example:
//This is an example of a single line comment
o Multi-line Comment
Example:
/* This is an example of a
multiline comment enclosed by two delimiters
that starts with a /* and ends with a */
*/
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● A block is one or more statements bounded by an opening and closing curly
braces that groups the statements as one unit. Block statements can be nested
indefinitely. Any amount of white space is allowed.
Example:
public static void main (String[] args)
{
System.out.println(“Hello”) ;
System.out.println(“World”) ;
}
● An expression is a value, a variable, a method, or one of their combinations that
can be evaluated to a value.
Examples:
int cadence = 0;
anArray[0] = 100;
8 >= x;
p || q ;
System.out.println("Element 1 at index 0: " + anArray[0]);
double squareRootTwo = Math.sqrt(2)
Java Identifiers
● Identifiers are tokens that represent names of variables, methods, classes, etc.
Examples of identifiers are: Hello, main, System, out.
● Java identifiers are case-sensitive. This means that the identifier: Hello is not the
same as hello.
Coding Standards
● There are certain rules for the naming of Java identifiers. Valid Java identifier
must be consistent with the following rules.
o An identifier cannot be a Java reserve word.
o An identifier must begin with an alphabetic letter, underscore (_), or a dollar
sign ($).
o If there are any characters subsequent to the first one, those characters must
be alphabetic letters, digits, underscores (_), or dollar signs ($).
o Whitespace cannot be used in a valid identifier.
o An identifier must not be longer than 65,535 characters.
● Also, there are certain styles that programmers widely used in naming variables,
classes and methods in Java. Here are some of them.
o Use lowercase letter for the first character of variables’ and methods’ names.
o Use pascal case for the class names (ex: LastnameResistor)
o Use camel case for the methods and variables (ex: subtractFunction,
radius1Ellipse)
o Compound words or short phrases are fine, but use uppercase letter for the
first character of the words subsequent to the first. Do not use underscore to
separate words.
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
o Use uppercase letter for all characters in a constant. Use underscore to
separate words.
o Apart from the mentioned cases, always use lowercase letter.
o Use verbs for methods’ names.
● Here are some examples for good Java identifiers.
o Variables: height, speed, filename, tempInCelcius, incomingMsg, textToShow.
o Constant: SOUND_SPEED, KM_PER_MILE, BLOCK_SIZE.
o Class names: Account, DictionaryItem, FileUtility, Article.
o Method names: locate, sortItem, findMinValue, checkForError.
Based on Oracle Coding standard, there should be four spaces before
indentation.
● Not following these styles does not mean breaking the rules, but it is always good
to be in style!
Java Keywords
● Keywords are predefined identifiers reserved by java for specific purposes. You
cannot use keywords as names of variables, classes, methods, etc.
● The difference between the various numeric primitive types is their size, and
therefore the values they can store:
Size Range of values that can be stored
Type
byte 1 byte −128 to 127
Integer short 2 bytes −32768 to 32767
int 4 bytes −2,147,483,648 to 2,147,483,647
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
long 8 bytes −9,223,372,036,854,775,808 to
9,223,372,036,854,755,807
Floating float 4 bytes −3.4e−038 to 3.4e+038
Point double 8 bytes −1.7e−308 to 1.7e+038
Characters
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Character Strings
are symbols that indicate the division and arrangement of groups of code. The
●
structure and function of code is generally defined by the separators. The
separators used in Java are as follows:
o parentheses ( )
- Used to define precedence in expressions, to enclose parameters in
method definitions, and enclosing cast types
o braces { }
- Used to define a block of code and to hold the values of arrays.
o brackets [ ]
- Used to declare array types.
o semicolon ;
- Used to separate statements.
o comma ,
- Used to separate identifiers in a variable declaration and in
the for statement.
o period .
- Used to separate package names from classes and subclasses and to
separate a variable or a method from a reference variable.
Variables
int total;
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Examples:
int count, temp, result;
double pi, average;
char cc, mm, tk;
Variable Initialization
● assigning a value to a variable for the first time
● a variable can be given an initial value in the declaration with an equal sign
Example:
int sum = 0;
int base = 32, max = 149;
● when a variable is referenced in a program, its current value is used
example:
int keys = 88;
System.out.println(“A piano has ”+ keys + “ keys”);
● prints as:
A piano has 88 keys
Assignment Statement
● an assignment statement changes the value of a variable
● the equals sign is also the assignment operator
Example:
● the expression on the right is evaluated and the result is stored as the value of the
variable on the left
● the value previously stored in total is overwritten
● you can only assign a value to a variable that is consistent with the variable's
declared type
Constants
● a constant is an identifier that is similar to a variable except that it holds the same
value during its entire existence
● as the name implies, it is constant, not variable
● in Java, we use the reserved word final in the declaration of a constant
example:
final int MIN_HEIGHT = 69;
● any subsequent assignment statement with MIN_HEIGHT on the left of the =
operator will be flagged as an error
Constants are useful for three important reasons
o first, they give meaning to otherwise unclear literal values
for example, NUM_STATES means more than the literal 50
o second, they facilitate program maintenance
if a constant is used in multiple places and you need to change its
value later, its value needs to be updated in only one place
o third, they formally show that a value should not change, avoiding
inadvertent errors by other programmers
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
The println Method
● the System.out object represents a destination (the monitor screen) to which we
can send output
System.out.println ("Whatever you are, be a good one.");
String Concatenation
● the string concatenation operator (+) is used to append one string to the end of
another
"Peanut butter " + "and jelly"
● it can also be used to append a number to a string
● a string literal cannot be broken across two lines in a program so we must use
concatenation
System.out.println(“The following facts are for your ” + “extracurricular edification”);
● the + operator is also used for arithmetic addition
● the function that it performs depends on the type of the information on which it
operates
● if both operands are strings, or if one is a string and one is a number, it performs
string concatenation
● if both operands are numeric, it adds them
● the + operator is evaluated left to right, but parentheses can be used to force
the order
System.out.println(“24 and 45 concatenated: ” + 24 + 45);
prints as: 24 and 45 concatenated: 2445
● the + operator is evaluated left to right, but parentheses can be used to force
the order
System.out.println(“24 and 45 added: ” + (24 + 45));
Then concatenation Addition is
is done done first
prints as: 24 and 45 added: 69
10
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Escape Sequences
● Example
System.out.println(“Roses are red,\n\tViolets are blue”);
Prints as:
Roses are red,
Violets are blue
● To put a specified Unicode character into a string using its code value, use the
escape sequence: \uhhhh where hhhh are the hexadecimal digits for the
Unicode value
Example: Create a string with a temperature value and the degree symbol:
double temp = 98.6;
System.out.println(“Body temperature is ” + temp + “ \u00b0F.”);
Prints as:
Body temperature is 98.6 ºF.
11
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 5: Java Operators, Flowcharting Symbols and Sample Programs
Operators
In Java, there are different types of operators. There are arithmetic operators,
relational operators, logical operators and conditional operators. These operators follow
a certain kind of precedence so that the compiler will know which of the operator to
evaluate first in case multiple operators are used in one statement.
Arithmetic Operators
Note:
When evaluating the mod operator with negative integer operands, the answer
always takes the sign of the dividend.
Illustration:
-34 % 5 = -4
34 %-5 = 4
-34 %-5 = -4
34 % 5 = 4
Increment/Decrement Operators
● Aside from basic arithmetic operators, Java also includes a unary increment
operator and unary decrement operator.
o Increment Operator (++)
- increases the value of a variable by 1
Example:
int count = 3;
count = count + 1;
12
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
// the above statement may be written as the one
//shown below.
count++;
Relational Operators
● Relational operators compare two values and determine the relationship
between those values.
● The outputs of evaluation are the boolean values true or false.
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Logical Operators
● Logical operators have Boolean operands that yield a Boolean result.
Operator Description Illustration
True && True = True
Logical AND
True && False = False
&& ● Returns True if all of its boolean
False && True = False
operands are True, False if otherwise.
False && False = False
Logical OR True||True = True
● Returns True if at least one of its True||False = True
||
Boolean operands are True, otherwise False||True = True
False False||False = False
Logical NOT !True = False
!
● Reverses the value of its operand. !False = True
13
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
++ Unary post-increment
14 Right to left
-- Unary post-decrement
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
*Larger number means higher precedence.
For more information on operator precedence, watch Module 5 Operator Precedence.
14
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Creating a Java Program
Simple Calculation
● In the above example, the statement in line 5 declares two variables that are
used to store floating point numbers. In line 6, the values from 1.0 to 10.0 are
summed together using the + operator and the resulting value is assigned to
sum. In line 7, the value of sum is divided by 10 which to obtain their average.
The statement in line 8 just prints the result on screen.
- Programmers do not sit down and start writing code right away when trying to make
a computer program. Instead, they follow an organized plan or methodology that
breaks the process into a series of tasks.
Here are the basic steps in trying to solve a problem on the computer:
In order to understand the basic steps in solving a problem on a computer, let us
define a single problem that we will solve step-by-step as we discuss the problem
solving methodologies in detail.
1. Problem Definition
● A programmer is usually given a task in the form of a problem. Before a program
can be designed to solve a particular problem, the problem must be well and
clearly defined first in terms of its input and output requirements.
● A clearly defined problem is already half the solution. Computer programming
requires us to define the problem first before we even try to create a solution.
Let us now define our example problem:
“Create a program that will determine the number of times a name
occurs in a list.”
2. Problem Analysis
● After the problem has been adequately defined, the simplest and yet the most
efficient and effective approach to solve the problem must be formulated.
15
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Usually, this step involves breaking up the problem into smaller and simpler sub-
●
problems.
3. Algorithm Design and Representation (flowchart)
● Once our problem is clearly defined, we can set to finding a solution. In
computer programming, it is normally required to express our solution in a step-
by-step manner.
● An Algorithm is a clear and unambiguous specification of the steps needed to
solve a problem. It may be expressed in either Human Language (English,
Tagalog), through a graphical representation like flowchart.
● Now given that the problem is defined, how do we express our general solution
in such a way that it is simple yet understandable?
Example Problem:
Determine the number of times a name occurs in a list.
Input Program:
list of names, name to look for
Output Program:
the number of times the name occurs in a list
16
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Flowcharting Symbols and Their Meanings
Connector Represents any entry from, or exit to, another part of the
Symbol flowchart. Also serves as an off-page connector.
● After constructing the program, it is now possible to create the source code.
Using the algorithm as basis, the source code can now be written using the
chosen programming language.
● Most of the time, after a programmer has written the program, the program isn’t
100% working right away. The programmer has to add some fixes to the program
in case of errors (also called bugs) that occurs in the program. This process is
called debugging.
● Compile-Time Error
- Occur if there is a syntax error in the code. The compiler will detect the
error and the program won’t even compile. At this point, the programmer
is unable to form an executable that a user can run until errors are fixed.
Forgetting a semi-colon at the end of a statement or misspelling a certain
command, for example, is a compile-time error.
17
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Runtime Error
- Compilers aren’t perfect and so can’t catch all errors at compile time. This
is especially true for logic errors such as infinite loops. This type of error is
called runtime error. For example, the actual syntax of the code looks
okay. But when you follow the code’s logic, the same piece of code
keeps executing over and over again infinitely so that it loops.
● To create a computer program that works, one need not only the knowledge
about the rules and syntaxes of a programming language but also a procedure
or a process that is used to accomplish the objectives of that program. Such a
procedure is called an algorithm. Usually, before creating a computer program,
an algorithm is developed based on the objective of the program before the
source code is written. An algorithm could be as simple as a single command.
More often than not, they are more complex.
● A flowchart needs a starting point of the program it represents and one or more
terminations. Steps or commands involved in the program are represented using
rectangles containing textual descriptions of the corresponding steps or
commands. These steps as well as the starting and terminating points are
connected together with line segments in which arrows are used for determining
the order of these steps. Shapes are typically placed from the top of the chart to
the bottom according to their orders. The starting and terminating points are
represented using oval shapes. Different shapes apart from the two shapes
already mentioned are defined so that they imply some specific meanings. The
following flowchart shows an algorithm of a computer program that prints out
the average of the integers from 1 to 10.
You can learn further about flowcharts by watching the Module 5 Flow Charting video.
18
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 6: Getting Program Input and Sequence Problems
Start
double ave,
Starting Point sum
ave = sum / 10
Display / Output
Termination ave
End
● Java provides different ways to get input from the user, the BufferedReader
Class, the Console Class and the Scanner Class. The Scanner Class is presumably
the most favoured technique to take input. The primary reason for the Scanner
class is to parse primitive composes and strings utilizing general expressions, in
any case, it can utilize to peruse contribution from the client in the order line. In
order to use the object of Scanner, the programmer need to
import java.util.Scanner package.
● //this line will import the Scanner Class
import java.util.Scanner;
● //create an object of the Scanner
Scanner kbd = new Scanner(System.in);
● //take input from the user
int num = kbd.nextInt();
Example: A java program that allows the user to input two numbers. The program
calculates the sum and displays it.
19
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
//import the Scanner Class
import java.util.Scanner;
public class sumOfTwoNumbers {
20
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Problems for Program Development: Solve the following Sequence Programs
1. Filename: PipeProblem_FamilyName
Create a flowchart and a java program
that will input the outside and the
inside diameter (outDia, inDia) of a
pipe. Calculate and print the thickness
(T) of the wall of the pipe.
Formula:
2. Filename: TemperatureProblem_FamilyName
Create a java program that will read a
temperature in degrees Fahrenheit (F),
output in degrees Centigrade (C).
Formula to convert degrees Centigrade to
degrees Celcius:
3. Filename: AngleToRadianProblem_FamilyName
Create a flowchart and a java program
that will read an angle expressed in
degrees (deg), minutes (min) and seconds
(sec), output in radians (rad).
Formula:
21
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
4. Filename: PowerLossProblem_FamilyName
Create a java program that will read a
current (I_AMP) flowing through a cable
and the resistance (R_OHM) of the cable,
compute and output the power loss
(P_WATT) through the cable.
Formula:
Sample Output:
5. Filename: ChangeProblem_FamilyName
Create a flowchart and a java program that
will input the amount of purchase which is
less than P100.00. The program will
calculate the change of P100.00 given by
the customer with the following breakdown:
P 50.00 - _______________;
P 20.00 - _______________;
P 10.00 - _______________;
P 5.00 - _______________;
P 1.00 - _______________;
Note: Purchases are all in pesos. No
centavos.
Formula Hint: Apply the concept of
modulus operator
6. Filename: TriangleProblem_FamilyName
If a, b and c represent the three sides of a triangle, then the area of the triangle is:
where:
Also the radius of the largest inscribed circle is given by:
and the radius of the smallest circumscribed circle is:
22
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Create a java program that will input the three sides of a triangle. Calculate and output
the area of the triangle, the area of the largest inscribed circle, and the area of the smallest
circumscribed circle given a value for a, b and c.
Sample Output:
23
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 7: Java Control Structures: Decision Control Structure
If Statement
● The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if
statement:
}
statement2;
else { if true statements if false statements
statement1;
statement2;
…
statementN;
}
24
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Nested ifs
● A nested if is an if statement that is the target of another if or else. Nested ifs are
very common in programming. When you nest ifs, the main thing to remember is
that an else statement always refers to the nearest if statement that is within the
same block as the else and that is not already associated with an else. Here is
an example:
if(i == 10) {
if(j < 20)
a = b;
if(k > 100)
c = d;
else
a = c;
}else
a = d; // this else refers to the if(i == 10)
● As the comments indicate, the final else is not associated with if(j<20) because it
is not in the same block (even though it is the nearest if without an else). Rather,
the final else is associated /* Demonstrate if-else-if statements. The program below
with if(i==10). The inner else will determine which season is the 4th month (April) */
refers to if(k>100) because it is public class SeasonProblem {
the closest if within the same public static void main(String args[]) {
block. int month = 4; // April
String season;
The if-else-if Ladder if(month == 12 || month == 1 || month == 2)
● A common programming season = "Winter";
construct that is based upon a else
sequence of nested ifs is the if(month == 3 || month == 4 || month == 5)
season = "Spring";
if-else-if ladder. It looks like this:
else
if(condition)
if(month == 6 || month == 7 || month == 8)
statement; season = "Summer";
else else
if(condition) if(month == 9 || month == 10 || month == 11)
statement; season = "Autumn";
else else
if(condition) season = "Bogus Month";
statement; System.out.println("April is in the " + season + ".");
... }
else }
statement;
● The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is true,
then the final else statement will be executed. The final else acts as a default
condition; that is, if all other conditional tests fail, then the last else statement is
performed. If there is no final else and all other conditions are false, then no
25
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
action will take place. Here is a program that uses an if-else-if ladder to
determine which season a particular month is in.
Flowchart of the if-else-if problem
For additional information about java’s selection statements: watch the following
videos
● Module 7: If Statement.mp4
● Module 7: If-else Statement.mp4
● Module 7: The If-Else-If Ladder.mp4
● Module 7: Nested IF Statements.mp4
Problems for Program Development: Solve using Decision Control Structure (if)
1. ThreeNumbersProblem_FamilyName
Create a flowchart and a java program that reads three distinct numbers (X,Y,Z). Determine
and output the following:
a) highest number (HN)
b) middle number (MN)
c) smallest number (SN)
d) the numbers in ascending order
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
2. YearProblem_FamilyName
A leap year is a year divisible by 4 unless it is a century year, in which case it must be
divisible by 100. Create a java program that reads a year and output a message whether the
year is a leap year, century year or ordinary year.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):
3. GradeProblem_FamilyName
A professor displays remarks for numeric grades in the following way:
Grade Remarks
93 – 99 Excellent
87 – 92 Very Good
80 – 86 Good
70 – 79 Fair
65 - 69 Poor
Using if, create a flowchart and a java program that reads a numeric grade and output the
equivalent remarks.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):
4. ParkingFeeProblem_FamilyName
Parking charge per hour at SMBC underground parking is as follows:
P 35.00 - minimum charge for 4 hours parking or less,
P 15.00/hr. - additional charge in excess of 4 hours parking,
P 250.00 - maximum charge.
Create a java program that reads the number of hours a vehicle was parked. Calculate and
output the parking charge.
(Note: Inputs should be integers only)
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):
27
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
5. ElectricBillProblem_FamilyName
The ABC Electric Company bases its electricity charges on two rates. Customers are charged
P30.12 per kilowatt-hour (KWH) for the first 400 KWH used in a month, and P25.23 for all
KWH used thereafter. Create a flowchart and a java program that reads an electric
consumption and output the amount to be charged to the customer.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):
Switch
● The expression must be of type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the
expression. (An enumeration value can also be used to control a switch
statement. Each case value must be a unique literal (that is, it must be a
constant, not a variable). Duplicate case values are not allowed.
● The switch statement works like this: The value of the expression is compared with
each of the literal values in the case statements. If a match is found, the code
sequence following that case statement is executed. If none of the constants
matches the value of the expression, then the default statement is executed.
However, the default statement is optional. If no case matches and no default is
present, then no further action is taken.
● The break statement is used inside the switch to terminate a statement
sequence. When a break statement is encountered, execution branches to the
28
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
first line of code that follows the entire switch statement. This has the effect of
“jumping out” of the switch.
● The break statement is optional. If you omit the break, execution will continue on
into the next case. It is sometimes desirable to have multiple cases without break
statements between them.
● The following are java programs that uses a switch statement:
1. GradeProblemUsingSwitch_FamilyName
A professor converts numeric grades to letter grades in the following way:
Grade Letter Grade
93 – 99 A
87 – 92 B
29
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
80 – 86 C
70 – 79 D
65 - 69 E
Using switch, create a java program that reads a numeric grade and output the equivalent
letter grade. There should be an error message if the grade entered is invalid.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):
2. CommodityCodeProblemUsingSwitch_FamilyName
A certain store has the following scheme:
Commodity Code:
1 - commodities are discounted by 15%
2 - commodities are taxed by 12%
3 - commodities are charged as priced
Using switch, create a program that reads a commodity code, quantity of the commodities
bought and the unit price and output the amount to be paid by the customer.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):
Enter commodity code: 1
Enter commodity code: 6 Enter quantity of commodity: 2
Invalid Code Enter unit price: 53.25
Amount to be paid is P90.53
Enter commodity code: 2
Enter quantity of commodity: 2 Enter commodity code: 3
Enter unit price: 53.25 Enter quantity of commodity: 4
Amount to be paid is P119.28 Enter unit price: 53.25
Amount to be paid is P213
● Java’s iteration statements are for, while, and do-while. These statements create
what we commonly call loops. As you probably know, a loop repeatedly
executes the same set of instructions until a termination condition is met.
For Loop
● The for loop operates as follows. When the loop first starts, the initialization portion
of the loop is executed. Generally, this is an expression that sets the value of the
loop control variable, which acts as a counter that controls the loop. It is
important to understand that the initialization expression is only executed once.
30
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Next, condition is evaluated. This must be a Boolean expression. It usually tests
the loop control variable against a target value. If this expression is true, then the
body of the loop is executed. If it is false, the loop terminates.
● Next, the iteration portion of the loop is executed. This is usually an expression
that increments or decrements the loop control variable. The loop then iterates,
first evaluating the conditional expression, then executing the body of the loop,
and then executing the iteration expression with each pass. This process repeats
until the controlling expression is false.
Sample Program
A java program using for loop that displays the numbers from 1 to 10;
For additional information about the for loop: watch Module 8: The FOR Loop.mp4
initialization
true
statement/s;
FileName: Series3Problem_FamilyName
31
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Create a java program that will output the numbers 1 4 7 ... between 1 and 150.
//no need to import the Scanner Class since there in no input in this program
public class Series3_CABS {
public static void main(String[] args) {
//initial value of x = 1
//this loop is terminated when the value of x is greater than 150
//value of the counter increases by 3
for(int x = 1; x<=150; x=x+3){
//output the value of x while x<=150
System.out.print(x+" ");
}
}
}
Start
x=1
False True
x<=150
Print x
End
x=x+3
32
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
FileName: FactorialProblem_FamilyName
Create a java program that reads a number and calculate and output its
factorial.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are
calculated and outputted by the program):
Input a number: 8 Input a number: 4
The factorial of 8 is 40320 The factorial of 4 is 24
}
}
33
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Flowchart Diagram for Factorial Using For Loop
Start
num
x=1
F=1
False
x<=num
True
F=F*x
Print num, F
x++
End
While Loop
● The while loop is Java’s most fundamental loop statement. It repeats a
statement or block while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop/statements
}
34
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition becomes
false, control passes to the next line of code immediately following the loop. The
curly braces are unnecessary if only a single statement is being repeated.
Sample Program:
initialization
while (condition)
{
//while loop body/statements;
}
condition?
False
True
Statement/s;
For additional information about the while loop: watch Module 8: The While Loop.mp4
Filename: Series2Problem_FamilyName
35
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Output the set of numbers in the series 1 2 4 7 11 16 … until 211 is reached.
Depicted below is a sample output when the program is executed:
}
}
}
Flowchart Diagram of Series2 using While Loop
36
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Filename: SphereProblem_FamilyName
Create a java program that will calculate and output the volume and area of spheres using the
formula:
V = (4PiR3)/3 A = 4PiR2
where R is the radius of the sphere is from 1 to 20.
Depicted below is a sample output when the program is executed:
37
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Flowchart Diagram for Sphere Using While Loop
Start
r=1
pi = 3.1416
False True
r<=20
a = 4*pi*r2
v = 4*pi*r3/3.0
End
Print r,v,a
r++
Do-while Loop
● If the conditional expression controlling a while loop is initially false, then the
body of the loop will not be executed at all. However, sometimes it is desirable to
execute the body of a loop at least once, even if the conditional expression is
false to begin with. In other words, there are times when you would like to test
the termination expression at the end of the loop rather than at the beginning.
Fortunately, Java supplies a loop that does just that: the do-while. The do-while
loop always executes its body at least once, because its conditional expression is
at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
38
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat.
Otherwise, the loop terminates. As with all of Java’s loops, condition must be a
Boolean expression.
initialization
do
{
statement block; statement block;
}
while (condition);
true
condition?
false
39
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Sample Program
import java.util.Scanner;
public class DoWhileMenuSelection {
public static void main(String[] args) {
// Using a do-while to process a menu selection
Scanner ram = new Scanner(System.in);
int choice;
do {
System.out.println("Help on. Please choose a number:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.print("Choose a number: ");
choice = ram.nextInt();
} while( choice < 1 || choice > 5);
switch(choice) {
case 1:
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case 2:
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence"); In the program, the do-
System.out.println(" break;"); while loop is used to
System.out.println(" // ..."); verify that the user has
System.out.println("}"); entered a valid choice.
break;
case 3: If not, then the user is
System.out.println("The while:\n"); prompted to enter
System.out.println("while(condition) another. Since the menu
statement;"); must be displayed at
break; least once, the do-while
case 4:
System.out.println("The do-while:\n"); is the perfect loop to
System.out.println("do {"); accomplish this.
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case 5:
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
} }}
40
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
More Do While Loop Examples
Filename: ObjectProblem_FamilyName
An object falling from rest in a vacuum falls 16 feet on the first second, 48 feet on
the 2nd second, 80 feet on the third second, 112 feet the 4th second and so on.
Create a java program that will output the distance traveled by the object after
15 seconds.
Depicted below is a sample output when the program is executed:
41
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Filename: BounceProblem_Familyname
A ball is dropped from an initial height of 50 feet. If the ball bounces 2/3 of the
previous height, make a program that will calculate and print the total distance
traveled by the ball after the 10th bounce.
Depicted below is a sample output when the program is executed:
//no need the import the Scanner Class since there is no input
public class Bounce_CABANILLA {
public static void main(String[] args) {
//in order to better understand this program, please try to solve is manually
double d = 50, dist = 50.0;
int b = 1;
do{
//the ball bounces 2/3 of the previous height
d = (2.0/3.0)*d;
//if the ball will bounce it goes up and down so distance travelled is doubled
dist = dist + 2*d;
//counter/number of bounce
b++;
}
//the loop is terminated after the 10th bounce
while(b<=10);
//the 1/2 of the distance on the 10th bounce is subtracted
dist = dist-d;
//output the total distance travelled
System.out.println("@ b = "+(b-1)+ "the distance travelled by the ball is "+dist);
}
}
42
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Flowchart Diagram for Bounce using DoWhile
Start
d = 50
dist = 50
b=1
d = (2.0/3.0)*d
dist = dist + 2*d
b=b+1
dist = dist - d
Print b,dist
End
43
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
If the number of iterations is If the number of If the number of
fixed, it is recommended to iterations is not fixed, iterations is not fixed
use a for loop. it is recommended to and you must have to
When to use use a while loop. execute the loop at
least once, it is
recommended to use
the do-while loop.
for(init;condition;increment) while(condition){ do{
{ //code to be executed //code to be executed
Syntax
// code to be executed } }while(condition);
}
//for loop //while loop //do-while loop
for(int i=1;i<=10;i++){ int i=1; int i=1;
System.out.println(i); while(i<=10){ do{
Example
} System.out.println(i); System.out.println(i);
i++; i++;
} }while(i<=10);
while(true){ do{
Syntax for for(;;){ //code to be executed //code to be executed
infinite loop //code to be executed } }while(true);
}
Problems for Program Development: Repetition Control Structure (while, do-while, for)
44
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
3. FileName: Series1Problem_FamilyName (Use Do While Loop)
The value of S is computed from the formula:
S = 1/1 + 1/2 + 1/3 + 1/4 + 1/5 + … + 1/N
Create a flowchart and a java program that will output the number of terms required and
the value of S before S exceeds 3.1.
Example:
1st term: S = 1;
2nd term: S = 1 + 1/2 = 1.5;
3rd term: S = 1 + 1/2 + 1/3 = 1.8333;
4th term: S = 1 + 1/2 + 1/3 + 1/4 = 2.08333;
5th term: S = 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.2833;
...
nth term: S = ?
Depicted below is a sample output when the program is executed:
45
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Definition:
▪ Composite number is a positive integer that can have more than 2 factors.
Ex : 4,6,8,9 are the example of composite numbers.
▪ A prime number is a whole number greater than 1 whose only factors are 1 and
itself. A factor is a whole number that can be divided evenly into another
number. The first few prime numbers are 2, 3, 5, 7, 11, 13, and 17. The number 1
is neither prime nor composite.
Depicted below are sample outputs when the program is executed:
46
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 9: Java Arrays
Arrays
● An array is a collection of objects (consists of a collection of data) that holds a
fixed number of values of the same data type.
● Arrays of any type can be created and may have one or more dimensions. A
specific element in an array is accessed by its numerical index.
One-Dimensional Array
● A one-dimensional array is, essentially, a list of like-typed variables. To create an
array, you first must create an array variable of the desired type. The general
form of a one-dimensional array declaration is
type var-name[ ]; or type[]var-name;
● Here, type declares the base type of the array. The base type determines the
data type of each element that comprises the array. Thus, the base type for the
array determines what type of data the array will hold. For example, the
following declares an array named month_days with the type “array of int”:
int month_days[]; or int [] month_days;
● Although this declaration establishes the fact that month_days is an array
variable, no array actually exists. In fact, the value of month_days is set to null,
which represents an array with no value. To link month_days with an actual,
physical array of integers, you must allocate one using new and assign it to
month_days. new is a special operator that allocates memory. You will look more
closely at new later, but you need to use it now to allocate memory for arrays.
The general form of new as it applies to one-dimensional arrays appears as
follows:
array-var = new type[size];
● Here, type specifies the type of data being allocated, size specifies the number
of elements in the array, and array-var is the array variable that is linked to the
array. That is, to use new to allocate an array, you must specify the type and
number of elements to allocate. The elements in the array allocated by new will
automatically be initialized to zero. The following example allocates a 12-
element array of integers and links them to month_days.
month_days = new int[12];
● After this statement executes, month_days will refer to an array of 12 integers.
Further, all elements in the array will be initialized to zero.
47
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Let’s review: Obtaining an array is a two-step process. First, you must declare a
variable of the desired array type. Second, you must allocate the memory that
will hold the array, using new, and assign it to the array variable. Thus, in Java all
arrays are dynamically allocated. Once you have allocated an array, you can
access a specific element in the array by specifying its index within square
brackets. All array indexes start at zero. For example, this statement assigns the
value 28 to the second element of month_days.
month_days[1] = 28;
● The next line displays the value stored at index 3.
System.out.println(month_days[3]);
● Putting together all the pieces, here is a program that creates an array of the
number of days in each month.
// Demonstrate a one-dimensional array.
public class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}}
● Arrays can be initialized when they are declared. The process is much the same
as that used to initialize the simple types. An array initializer is a list of comma-
separated expressions surrounded by curly braces. The commas separate the
values of the array elements. The array will automatically be created large
enough to hold the number of elements you specify in the array initializer. There is
no need to use new. For example, to store the number of days in each month,
the following code creates an initialized array of integers:
// An improved version of the previous program.
public class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
48
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
More examples of One Dimensional Array
1. A java program that determines and displays the average array of values.
public class Average {
public static void main(String args[]) {
double arrayKo[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double sum = 0, ave;
int i;
for(i=0; i<5; i++)
{
sum = sum + arrayKo[i];
}
ave = sum/5.0;
System.out.println("Average is " + ave);
}
}
2. A java program that allows the user to manually input the array size and elements in the
memory then displays its elements.
import java.util.Scanner;
public class JavaArrays {
public static void main(String[] args) {
Scanner ram = new Scanner(System.in);
System.out.print("Enter the array elements: ");
int size = ram.nextInt();
//declaring the 1-Dimensional Array
int arrayKo[]= new int[size];
int i;
//accessing the indices in the array
//then allocating the elements manually
for(i=0; i<size; i++)
{
System.out.print("The element at index "+i+" is ");
arrayKo[i] = ram.nextInt();
}
System.out.print("The array elements: ");
//access each of the indices in the array then display the array elements
for(i=0; i<5; i++)
{
System.out.print(arrayKo[i] + " ");
}
}
}
49
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 9: Declaring Arrays & Accessing Elements.mp4
For additional information about one-dimensional arrays and the for loop: watch
Module 9: Using a Loop to Access an Array.mp4
50
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Multidimensional Arrays
● In Java, multidimensional arrays are actually array of arrays. These, as you might
expect, look and act like regular multidimensional arrays. However, as you will
see, there are a couple of subtle differences. To declare a multidimensional
array variable, specify each additional index using another set of square
brackets. For example, the following declares a two-dimensional array variable
called twoD.
int twoD[][] = new int[4][5];
● The above code allocates a 4 by 5 array and
assigns it to twoD. Internally this matrix is
implemented as an array of arrays of int.
● When you allocate memory for a multidimensional
array, you need only specify the memory for the
first (leftmost) dimension. You can allocate the
remaining dimensions separately. The figure shown
is a conceptual view of a 4 by 5, two-dimensional
array.
● The following program randomly assign numbers as elements in the array from
left to right, top to bottom, and then displays these values:
// Demonstrate a two-dimensional array using the Random Class.
//import the Random Class
import java.util.Random;
public class TwoDArray {
public static void main(String[] args) {
//set up the program to be ready to accept
//a random input
Random rand = new Random();
//declaring the 2-Dimensional Array (4x5)
int twoD[][]= new int[4][5];
int i, j, k = 0;
System.out.println("The array elements: ");
//allocating the elements of a 4 by 5 array using the random class
for(i=0; i<4; i++){
for(j=0; j<5; j++){
//random number from 0 to 9 will be store at index twoD[i][j]
twoD[i][j] = rand.nextInt(10);
}
}
//access each of the indices in the array then display the array elements
for(i=0; i<4; i++) {
for(j=0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
51
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
}
Instruction:
There are two lists of numbers. Create a resultant list whose elements are the product of
the elements of the two lists.
Write a Java program using a one-dimensional array that accepts as input an integer
value asking for the number of elements for each list. This will be used to generate
random numbers (5 to 69) for the one-dimensional arrays (List A and List B). The program
52
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
will compute for the product and store it in another array (List C). Display the result
similar to the Example above.
Sample Input/Output:
Depicted below are sample outputs when the program is executed (the items in bold
characters are input from the user, while the items in bold italic are generated,
calculated and printed by the program):
Required: The .java file (FamilyName_List.java) containing the code and 2 image files
(Sample1 and Sample2) containing different sample input/output of the program.
Creating Methods
● Considering the following example to explain the syntax of a method:
public static int methodName(int a, int b) {
// body
}
● Here,
public static: modifier.
int: return type
methodName: name of the method
a, b: formal parameters
int a, int b: list of parameters
53
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Method definition consists of a method header and a method body. The same is
shown below:
modifier returnType nameOfMethod (Parameter List) {
// method body
}
● The syntax shown above includes:
modifier: It defines the access type of the method and it is optional to use.
returnType: Method may return a value.
nameOfMethod: This is the method name. The method signature consists
of the method name and the parameter list.
Parameter List: The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, methods may contain zero
parameters.
method body: The method body defines what the method does with
statements.
● Example: Here is the source code of the above defined method called max. This
method takes two parameters num1 and num2 and returns the minimum
between the two:
/*
* the snippet returns the minimum between two numbers
*/
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2){
min = n2;
}
else{
min = n1;
}
return min;
}
Method Calling:
● For using a method, it should be called. There are two ways in which a method is
called i.e. method returns a value or returning nothing noreturnvalue. The
process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then
returns control to the caller in two conditions, when:
o return statement is executed.
o reaches the method ending closing brace.
● The method returning void is considered as a call to a statement. Let is consider
an example:
System.out.println("Calling a method!");
● The method returning value can be understood by the following example:
int result = sum (6, 9);
54
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Example:
● The following is an example which demonstrate how to define a method and
how to call it:
public class ExampleMinNumber_Method{
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System .out.println("Minimum Value = " + c);
}
//returns the minimum of two numbers Sample Output:
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Example:
public class ExampleVoid_Method {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}
else
if (points >= 122.4) {
System.out.println("Rank:A2");
}
else {
System.out.println("Rank:A3");
}
}
}
55
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
This would produce the following result:
56
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Method Overloading:
● When a class has two or more methods by the same name but different
parameters, it is known as method overloading. It is different from overriding. In
overriding, a method has the same method name, type, number of parameters
etc. Let us consider the example shown before for finding minimum numbers of
integer type. If we want to find the minimum number of double type, then the
concept of Overloading will be introduced to create two or more methods with
the same name but different parameters. The below example explains the same:
public class ExampleOverloading_Method{
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
//same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
This would produce the given output on the right result:
● Overloading methods makes the program readable. Here, two methods are
given the same name but with different parameters. The minimum number from
integer and double types is the result.
57
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Module 10: Adding Parameters to a Method & Returning Values.mp4
58
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 11: Wrapper Classes and Strings
Wrapper classes are used for converting primitive data types into objects, like int
to Integer.
When working with Collection Objects, such as ArrayList and Vector, only objects
can be stored and not primitive types.
or
59
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
//Using Autoboxing
Integer autoboxObj = day; This will display the result:
The general form for converting a primitive type to a wrapper object is:
WrapperClass objectName = WrapperClass.valueOf(primitiveDataTypeVariable);
or
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
Unboxing
Automatically converting an object of a wrapper class to its corresponding
primitive type.
//using Unboxing
int unboxDay = obj; This will display the result:
System.out.println(day+ " "+ unboxDay+ " "+ obj); 21 21 21
}
The general form of converting a wrapper object to primitive data type is:
primitiveDataType variableName = objectName.primitiveDataTypeValue();
or
60
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Examples: int day = obj.intValue();
The following methods are used to get the value associated with the
corresponding wrapper object: intValue(), byteValue(), shortValue(),
longValue(), floatValue(), doubleValue(), charValue(), booleanValue().
Since Java 5, we do not need to use the intValue() method of wrapper classes
to convert the wrapper type into primitives.
public static void main(String[] args) { This will display the result:
String str=" Hello World ";
System.out.println(str); Hello World
System.out.println(str.trim()); Hello World
}
61
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
length() method
The string length() method returns length of the string.
public static void main(String[] args) { This will display the result:
String str="Hello World";
System.out.println(str); Hello World
System.out.println(str.length()); 11
}
concat() method
The java string concat() method combines specified string at the end of this
string. It returns combined string. It is like appending another string.
public static void main(String args[]){ This will display the result:
String s1="Hello";
System.out.println(s1); Hello
s1=s1.concat(" World"); Hello World
System.out.println(s1); Hello World! 2020
s1=s1.concat("!").concat(" 2020");
System.out.println(s1);
}
equals() method
The string equals() method compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters are matched, it
returns true.
equalsIgnoreCase() method
The string equalsIgnoreCase() method compares the two given strings on the
basis of content of the string irrespective of case of the string. It is like equals()
method but doesn't check case. If any character is not matched, it returns false
otherwise it returns true.
62
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
public static void main(String[] args) {
String str1="Hello World";
String str2="Hello World";
String str3="HELLO WORLD"; This will display the result:
String str4="hello";
System.out.println(str1.equalsIgnoreCase(str2)); true
System.out.println(str1.equalsIgnoreCase(str3)); true
System.out.println(str2.equalsIgnoreCase(str3)); true
System.out.println(str3.equalsIgnoreCase(str4)); false
}
compareTo() method
The string compareTo() method compares the given string with current string
lexicographically. It returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings.
If first string is lexicographically greater than second string, it returns positive
number (difference of character value). If first string is less than second string
lexicographically, it returns negative number and if first string is lexicographically
equal to second string, it returns 0.
if string1 > string2, it returns positive number
if string1 < string2, it returns negative number
if string1 == string2, it returns 0
This will display the result:
public static void main(String args[]){
String s1="hello"; 0
String s2="hello"; -5
String s3="meklo"; -1
String s4="hemlo"; 2
String s5="flag";
//start comparing from the first character of the string
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}
If you compare string with blank or empty string, it returns length of the string. If second
string is empty, result would be positive. If first string is empty, result would be negative.
63
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
indexOf() method
The java string indexOf() method returns index of given character value or
substring. If it is not found, it returns -1. The index counter starts from zero.
For additional information about java’s String methods: watch the following videos
Module 11: Changing a String to Lowercase or Uppercase
Module 11: Obtaining the Length of a String
Module 11: Combining Strings (Concatenation)
Module 11: Determining if Two Strings are Equal
Module 11: Comparing Two Strings
Module 11: Searching a String for a Substring
64
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
References:
65
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.