Java Week 1-10
Java Week 1-10
Java Week 1-10
Reminders:
/* Use netbeans for kapag outputs hinahanap para sure yung sagot
(take note: minsan kahit tama output sa netbeans, mali output sa oed.
Ayun yung nakakairita don)
Strictly check the word kung may ‘s’ sa dulo or wala. Kasi kapag
walang ‘s’ minsan mali na
Not 100% tama pero pwede na
Nilagay ko din dito yung module na nasa oed para kung may mga
tanong na walang sagot, pwede nyong hanapin (wag tamad magbasa)
*/
-Ren Jastine
Java Module
Analyze the Problem
Before anything else, the program requirements should be clearly defined. What is the
program for? What does it do? Who are the end users? What are the functions? What are the
scope and limitations?
Just like what you do every time you cook (or your mom or dad or auntie). Decide first what you
are going to cook before gathering the necessary ingredients and cooking tools.
Now that the requirements have been identified, the next phase is designing the program. How
do you actually design a program?
Tools such as flowchart and pseudocode, which will be discussed in detail in the later part of
this module, are used in conceptualizing and designing a program.
Why is this phase important? Cant we just go ahead and write code?
Imagine constructing and building a house without a blueprint. The workers do not have an idea
on how the house should look like. It’s the same with flowcharts. Flowcharts give the
programmers an idea on the flow of the program and its scope.
Once the program design has been accomplished, programmers will now proceed with the
actual coding – using a programming language like Java to write the lines of code.
Testing and debugging comes after coding the program. This is done to ensure that the
program works, procedure the correct and intended result, and displays it appropriately.
“Debugging” actually means finding and removing bugs or errors for the program to function
properly and meet its requirements. Programmers are responsible for debugging their program.
In the phase, the program is run to check for syntax and grammatical errors which could have
been overlooked during the coding phase.
Documentation
Documentation comes last. In this phase, the programmers write down instruction for the end
users (the ones who are going to use the system), the purpose of the program, how it performs
its function, the input needed and the output expected.
Internal documentations are done by programmers through comments (this will be discussed in
a later module). These comments explain what a function does and why it was created.
Algorithm
Algorithm is used to described how you do simple daily tasks or action. In computer science,
algorithm is defined as a procedure or formula which consists of a set of steps to accomplish a
specific task. In the next section, we will discuss the different tools to present an algorithm.
Pseudocode
Pseudocode, or program design language, describes the steps of an algorithm using everyday
language. These statements describe an action and focuses on the logic of the program’s
algorithm. Steps should be numbered and should be clear enough so that the desired
programming code can be generated using these statements.
Pseudocode, as another way to interpret an algorithm, has its own set of benefits:
1. Pseudocode provides a simple means of presenting program logic through the use of
everyday language.
2. it is language independent
3. it is easier to right codes from a Pseudocode than a flowchart ( refer to the next section).
Flowchart
Connector – this symbol connect sections of the flowchart for smooth and linear
flow.
Terminal – this shape indicates the start and end of the program.
Flow lines – these arrows indicates the direction of the program flow.
Documentation standards
An effective programmer does not only write codes and programs that work without
errors and bugs. You also have to follow coding techniques, programming practices and
documentation protocol in case new features will be added to the program: change it
features, fix bugs and improve your performance. Your codes should be readable
enough so that other programmers can comprehend them very well.
Names
Naming the different elements of a program aids programmer to understand the program
flow. A name should tell “what” is does rather than “how” it does a function.
Use simple words that can be understood by others. For example, use GetNextStuden()
instead of GetNextString().
There are different program elements:
Naming routines:
1 in object-oriented programming, avoid repeating the name of the class in naming class
properties. Instead of BookBookTitle, BookTitle.
2. use both a verb or a noun to describe operations and functions, for example
CalculateAverageScore().
3 in programming language that allow function overloading, all overloads should perform
the same function.
Naming variables:
1 attach computation qualifiers such as Sum, Avg (average), Min (Minimum), Max
(Maximum) to the ending of a variable name, if applicable.
2 use traditional opposite pairs such as begin/end, open/close and min/max in variable
names.
4. capitalize each word, except the first word, in naming variables like totalScore.
5 boolean variables names should contain Is which imply Yes/No, true/false values like
recordIsFound.
6 use meaningful variable names even for variables which will only be used a few times
in the program.
2 in naming columns, do not repeat the name of the table, use LastName instead of
StudentLastName in the Student table.
3 do not include data type in the name of the column, use Age instead of IntAge (which
means that age is set of integer).
Comments
Comments have two types – internal and external documentation. Internal comments
can be found in the program itself while external is the opposite.
External documentation includes help files, specifications and design documents.
Format
A proper programming format makes the program’s logical flow stand out. Take time to
make sure that the program is formatted in a consistent way.
Syntax
You’ve probably seen this word when you typed something on your calculator “Syntax
Error”.
We also have “syntax” when it comes to programming. Basically, syntax is one of the
building blocks of programming language – it is the spelling and grammar of
programming. You should follow it or else you’ll get an error.
Naming convention
Programmers have to follow standard naming conventions so that their code will be easy
to read and understand. We have discussed this topic briefly in properly documenting a
program.
Classes
2 it should be written in mixed case with the first letter of each word capitalized.
Methods
2 it should be written in mixed case as well but the first letter is in lower case.
Variables
1 variables should be written in mixed case with the first letter in lower case.
Constants
Standard convention for indention uses four spaces as the unit of indention. If your code
is too long, make sure its no longer 80 lines. If in case a code statement will not fit in a
single line
3rd Module
Clauses = Expressions
Sentences = statements
Paragraph = blocks
Expression
Expression consist of methods, variables and operators which follow certain syntax
depending on the language used, which in this case in Java. An expression concludes to
a single value after evaluation; an int a, Boolean and so on.
“string1” + “string2”
100 + 1
1||2
Statements
Statements are mostly the same as expression but they are terminated by a semicolon
(;). The following expression can be turned into statements by ending it with a semicolon
(;)
1 assignment expression
a. sStr = “string”;
b.nValue = 5;
c. bool = true;
a. number++;
b. number--;
a. System.out.pritnln(“Hi!”);
b.System.in.read();
Blocks are single or multiple statements within braces. They can be one liners or huge
class containing methods and functions.
Conditional statements that utilize the clauses if, then and else.
Switches
4th module
For loops are loops with explicitly defined conditions. This kind of loop is what you
would commonly encounter as you can see the conditions directly through the code.
This is just like for loop but rather than check with an explicit and abbreviated text
expression, it check a Boolean. The Boolean decides variable whether the loop
continues or ends.
The Boolean value must be change inside the loop while it is running or else you will get
an infinite loop. Infinite ice cream or infinite money may sound good but when you got an
infinite loop and your computer isn’t hefty enough to handle it or the environment is not
set to reserve memory then… you might just need to press the restart button.
Do while loop
A do-while loop is a while that checks the Boolean after an execution of the body.
The “continue” statement makes a loop or conditional statement to re-run its pass, thus
skipping a cycle.
The “break” statement makes the loop or conditional statement to stop everything its
doing and end it, causing it to break out of the cycle.
5th module
Arrays are objects that contain a specific number of elements of a certain data type. It may
seem simple, but it gets complicated as we go on.
Declaring arrays
Arrays declaration in java are almost the same as in the C-based programs.
Example:
int[] myArray;
char[] newArray;
the braces can also be at the end of the array’s name, but this practice is strongly
discouraged as it produces weird complications.
Initializing arrays
Example:
int[] myArray;
myArray[1] = 1;
myArray[2] = 2;
myArray[3] = 3;
myArray[4] = 4;
myArray[5] = 5;
myArray[6] = 6;
the array initialized one by one with each initialization using one assignment declaration.
Multi-Dimentional array
You may see array as linear set of values but as mentioned, it gets complicated really
fast.
Arrays can have more than one dimension. That’s right, array can have one, two, three
and any number of dimensions you can handle, if you are extremely good at tracking
things, or your computer, if it can handle that amount of data and calculations.
Example:
int[][] myArray;
Copying arrays
Array manipulation
Manipulating array in java with built-in methods can ease the hard job of doing them
manually.
Other methods, that can be called from “java.util.Arrays”, to manipulate arrays are:
6th module
Object-oriented programming is a programming pattern that uses abstraction (in the form
of classes and objects) to create models based on the real world environment. Objects
are capable in passing messages, receiving messages, and processing data.
The aim of object-oriented programming is to try to increase the flexibility and
maintainability of programs. Because programs created through OOP
Language are modular, they can be easier to develop, and simpler to understand after
development.
However, the procedural-oriented languages use a design method called top down design
where the focus in on procedures, with function as the basic unit. First, you need to figure out all
the functions and then think about how to represent the data.
1 Ease in software design: being able to think in the problem space with high-level concepts
and abstractions. Ease in design leads to more productive software development.
2 ease software maintenance: object oriented software are easier to understand, therefore
easier to test, debug and maintain.
3 reusable software: there will be no need for you to keep re-inventing the wheels and the
same function for different application. The quickest and safest way in developing a new
application software is to reuse old or existing codes – fully tested and proven codes.
Characteristics = variables
Behavior = method
Creating objects
1. declaration – this refers to the variable declaration associated with a variable name and
object type
3. initialization – this is the part where the object is initialized by calling a constructor.
Objects fields are accessed by their name. You must use a name that is unambiguous.
The code that is outside the object’s class must use an object reference or expression,
followed by the dot operator and a simpler field name, as in:
Example:
objectReference.fieldName
Encapsulation
Encapsulation is a mechanism of packing up the data (variables) and the code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class
will be hidden from other class. The hidden variables can be accessed only through the
methods of their current class. The process is also known as data hiding.
For example, you discovered that you have one piece of chocolate wafer left. What do
you do? You hide it in the crisper to prevent your younger brother from eating it. Its your
private property.
Inheritance
Inheritance can be defined as the process where one class acquires the methods and
fields of another class. Using inheritance, the information is made manageable in a
hierarchical order.
The class which inherits the properties of another is known as subclass (derived class,
child class). On the other hand, the class whose properties are inherited is known as
super class (base class, parent class).
In other words,
2 you can also declare new fields in the child class which are not in the parent class.
4 you can override methods by writing a new instance of the method inherited from the super
class
5 you can declare new methods in the child class which are not in the parent class
6 you can use a subclass constructor that invokes the super class constructor
The keyword used to inherit the properties of a class is the “extends” keyword.
Polymorphism
Polymorphism occurs when there are different forms of an individual in the same species.
Polymorphism – it is the ability of a Java object to take different forms. Subclasses or child
classes could have different behaviors and still share the same functions from their parent class
or super class.
It is important to know that you can only access an object using a reference variable. A
reference variable can be of only one type. Once declared, the reference variable type cannot
be changed.
If a reference variable is not declared as final, it can be reassigned to other objects. The
reference variable type would determine the method that it can invoke on the object.
A reference variable can refer to any object of its type or any subtype of its type. A reference
variable can be declared as a class or interface type.
Abstraction
This refers to the process of hiding the details of implementation and showing only the
necessary functions.
Abstraction is a process of hiding the implementation details from the user, providing only the
functionality. With this, the user will have the information on what the object does instead of how
the object does it.
A class which contains the abstract keyword in its declaration is known as abstract class.
Using this model, any of the procedures created might be called at any location during the
execution of a program, including other procedures or itself. It also focuses on the step-by-step
sequence of instructions to perform task.
Procedural programming is used by almost all programming languages. This kind of approach is
needed because computers and applications cannot decide on their own which sequence to
use. Who says computers are more intelligent than us?
On the other hand, non-procedural programming is done by identifying what needs to be done
rather than how it should be done. Non-procedural programming involves instructing the system
as to how to complete a task.
While non-procedural languages exist, these languages are normally limited to small
applications and are limited in the scope of tasks that they can perform.
The most commonly used programming languages which use the procedural approach include
C, C++, Java, Fortran, pascal and BASIC. These languages have evolved over time but they all
have procedural aspects to them.
Procedural programming is tricky for large applications. Large procedural programs can become
hard to manage.
There is often little opportunity for abstraction, which largely helps in simplifying a problem.
The interfaces between parts of an application can also become difficult to manage.
Programmers tend to spent a lot of time learning how to program these interfaces.
This refers to a case where a program method is continuously broken down into smaller sub-
problems (to decrease the complexity of the programming task) until each sub-problems can be
solved in a few steps.
Program Specification
Classes
A class is a blueprint from which individual objects are created. The class can have any number
of methods to access the value of various kinds of methods.
The public class has to have the same name as the Java file.
A single Java file can contain more than one nonpublic class but can have only one public class.
Modifiers
Modifiers are keywords that you add to those definitions to change their meanings.
2. Access Non-Modifiers.
Access modifiers – Java provides a number of access modifiers to set access levels for
classes, variables, methods and constructors. The four access levels are:
Non-access modifiers – Java provides a number of non-access modifiers to achieve many other
functionalities:
2. the final modifier for finalizing the implementations of classes, methods, and variables;
4 the synchronized and volatile modifiers, which are used for threads.
Java variables
Programs work by manipulating data placed in the computer memory. The data can be
numbers, text, objects, etc. the data is given a name, so that it can be re-used whenever it is
needed. The name and its corresponding value, is known as a Variable.
A variable is a named storage that programs can manipulate. It can also be defined as the
name of the reserved area allocated in the memory. It can also be defined as the name of the
reserved area allocated in the memory. With the combination of the words “vary” and “able”, it
simply means the value of a variable can be changed.
Variables Types
1. Local variables – these variables are declared within the body of a method and can be only
used inside the method. Unlike instance and class variables, local variables are fussy about
where you position the declaration for it.
You must place the declaration before the first statement that actually uses the variable.
The variable message is our local variable because it was declared inside the main method.
Methods cannot use variables that are locally declared from other methods.
2. instance variables – these are variables that are declared in a class, but outside a method.
They hold values that might be referenced by more than one method or block.
Instance variables can be accessed directly by calling the variable. They should be called using
the fully qualified name as ObjectReference.VariableName
3. Class/Static Variables - these variables are declared with the static keyword in a class, but
outside a method or a block. Defining its visibility or access level is similar to instance variables.
Usually, static variables are declared publicly in order for them to be available for users of the
class.
Static variables can also include the final keyword. This means that those variables are storing
constant values.
When a variable is declared with the keyword “static”, it is called a class variables or static
variable.
A Java method is a collection of commands that are grouped together to perform an operation
that can be used over again.
Sometimes, the terms “function” and “method” are used interchangeably. The correct
terminology for Java is “method”.
1. Modifier – it defines the access type of the visibility of the method. It is optional to use.
2. Return Type – this refers to the data type of the value to be returned by the method.
Examples: void, int, double, Boolean
3. Method Name – this is whatever you want to call your method depending on its purpose.
Just remember about the naming convention for Java methods.
4. Parameter List – it is the type, order, and number of parameters of a method. Using
parameters lists is optional, since a method may contain zero parameters.
5. Method Body – this is where the actions of the method takes place. It contains all valid java
instructions that the method should do.
Where:
Public – modifier
x, y – formal parameters
Answer: True
The operator “new” allocates a memory block the size of what is declared.
Answer: True
Answer: false
Answer: false
Ans: false
number++; is a block
ans: false
Ans: true
When polymorphism is used, the Java object can only take one form.
Subclasses should have the same function with the parent class.
Ans: false
Ans: fills
Ans: true
Ans: true
Ans: true
A: true
A: Boolean
A: false
A: false
A: true
A: directly
Using a break; statement causes the loop to jump to the next iteration.
A: false
A: discouraged
A: false
A: 2-d or 2-dimensional
A: any
An array is always an _______.
A: object
Please refer to figure 1 to answer the question below: If the test expression
“num <= 10” is changed to “num <= 2”, the final value of num would be
_______.
A: 4
A:true
number++; is an expression
A: true
A: false
A: 5
A: True
A: False
A: false
A: false
A: false
A: true
A: true
A: false
A: true
A: false
A: false
A: false
Please refer to figure 1 to answer the question below: The final value of
num in the output is ________
A: 12
True or False: Instance variables are declared inside a method but outside a
class.
A: False
System.out.println(val_3);
Output: 12
TRUE OR FALSE: The output of this code is “The quick brown fox”
A: False
True or False: You’ll know that a variable is a class variable when you see
that variable inside a class with the word static.
A: True
TRUE OR FALSE: The value of “val_4” is “fox”
A: False
val_2 = val_1;
val_1 = val_3;
System.out.println(val_1);
Output: bar
";
System.out.println(val_1);
Output: f6
TRUE OR FALSE: “val_2” contains “The”.
A: true
True or False: Public, private and protected are some of the return types
used in Java programming.
A: False
String val_1 = "foobar";
char ch = val_1.charAt(3);
val_2 = String.valueOf(ch);
ch = val_1.charAt(1);
System.out.println(val_2);
Output: boar
True or False: Variable names in Java are not necessarily case sensitive.
A: False
A: True
The string method “length( )” returns the number of characters within a string.
A: True
Val_1 = val_1.substring(4,6);
System.out.println(val_1);
Output: 5698
System.out.println(val_1);
Output: 200
variable
Fill in the blank: A Java is simply a storage with a name.
String val_1 = "35";
int num = 1;
val_1 = val_1.substring(0,1);
System.out.println(num);
Output: 4
Select one:
True
False
String val_1 = "foobar";
System.out.println(val_1);
Output: Error
Select one:
True
False
Substrings can contain 1 or 2 arguments.
Select one:
True
False
TRUE OR FALSE: The value “val_3” is a white space “ “.
Select one:
True
False
String val_1 = "foo";
val_2 = val_1;
val_1 = val_3;
System.out.println(val_2);
Output: foo
True
Select one:
h. Super class
i. More than one
j. Abstract class
A class statement has three (3) major parts – declaration, initialization and
instantiation.
Select one:
a. False
b. True
Select one:
a. True
b. False
While statements check the test expression at the end.
Select one:
a. True
b. False
A child class inherits all the methods of every other class.
Select one:
a. True
b. False
Conditional test expressions can contain declarations
Select one:
b. True
Blocks can contain more blocks of code.
Select one:
a. True
b. False
Arrays are_______.
Select one:
a. Objects
b. Integers
c. Operators
d. Data types
Select one:
a. else-if statement
b. If-else-if statement
c. none of the choices
d. If statement
e. all of the choices
If the value of “pStr” in line 7 is changed to _______ then the value of “pStr”
in line 24 will be changed as well.
Select one:
a. True
b. default
c. tralse
d. you
Among the statements below which is only an expression
Select one:
a. true;
b. bool
c. “string1” + “string2”
d. System.out.println(“Hi!”);
e. system.in.read( );
Abstraction works by hiding the implementation details and showing only
the functions necessary.
Select one:
a. False
b. True
The equivalent of Paragraphs in coding is?
Select one:
a. Paragraphs
b. Expressions
c. Statements
d. Blocks
Loops can be stopped with a break; statement.
Select one:
a. True
b. False
Select one:
a. False
b. True
Select one:
a. String[ ] myArray;
b. String[ ][ ] myArray;
c. None of the choices
d. String myArray[ ];
e. All of the choices
________ is one of the four fundamental concepts, this is also known as data
hiding.
Select one:
h. Encapsulation
i. Different forms
j. Abstract class
Declaring an object in Java uses the new keyword to create a new object.
Select one:
a. True
b. False
The sort( ) method is always ascending.
Select one:
a. False
b. True
Among the expressions below which is a statement?
Select one:
a. bool
b. “my” + “dog”
c. true
d. number++;
e. 123/((12+2)*5)
If statements cannot be nested in switches
Select one:
a. True
b. False
Select one:
a. 2
b. 10
c. 12
d. 0
The type of loop that checks the test expression at the end.
Select one:
a. none of the choices
b. all of the choices
c. do-while
d. while
e. for
What does ‘new’ in int[ ] myArray = new int[n] do?
Select one:
d. Assigns memory for the array
The expression int[ ] myArray = new int[10] will ________ memory that can
contain 10 integers.
Select one:
b. Allocate
Select one:
True
False
Local variables are declared inside the default method.
A: False
A; False
In designing the program specification, determine first the input, then the
output
and then analyze the problem.
simplify
In programming, abstracting a problem means it.
In designing the program specification, determine first the input, then the
output
and then analyze the problem.
sub-problems
In top down approach, problems are broken down into smaller .
variabl
A Java is simply a storage with a name.
C++
Languages which use procedural programming include C, , FORTRAN,
Pascal and BASIC.
functio
Fill in the blank: In programming, another term for method . But Java
uses the term "method".
String val_1 = “Foobar”;
Val_1 = val_1.substring(4,7);
System.out.println(val_1);
Output: bar