Sei sulla pagina 1di 110

JAVA PROGRAMMING

CORE COMPETENCIES
TABLE OF CONTENT

UNIT 1
JAVA BASICS

LESSON 1 – Java technology and the Java


programming language
LESSON 2 – Object – Oriented Programming

LESSON 3 – Basic concept of any computer language

LESSON 4 – Programming design fundamental

LESSON 5 – Object – Oriented concept and java

UNIT 2
CONTROL STRUCTURE

LESSON 6 – Variables and Data type

LESSON 7 – Arithmetic and Relational Operators

LESSON 8 – Arrays

LESSON 9 – Java String and Methods

LESSON 10 – Getting program Input


CHAPTER I

Unit Learning Objectives:

1. Create a foundation of understanding of the world of ICT;


2. Understand and demonstrate the principle and concepts of java programming;
3. Performing object-oriented analysis and design
LESSON 1

Java Technology and the Java


Programming Language
About the Java Technology

According to Oracle Java Documentation, Java technology is both a


programming language and a platform.

The Java Programming Language

Java programming language considered as a high-level language that can be


characterized by all the of the following buzzwords:

1. Simple – java was designed to make it much easier to write bug free code. The
language is small so it’s easy to become fluent.

2. Object- Oriented – OOP is a programming language model organized around


objects rather than “action” and data rather than logic.

3. Distributed – Java is Distributed Language means because the program of java


is compiled onto one machine which can be easily transferred to machine and
executes them on another machine.

4. Multithreaded and Interactive – code is divided into small parts like these
code of java is divided into smaller parts those are executed by java compiler

5. Dynamic and Extensible code – with the help of OOPS java can provide
Inheritance that help to reuse the code which can be pre-defined and also uses all
the built in functions of java and classes.

6. Architecture Neutral – or the platform independent. This means that the


programs written on one platform can run on any other platform without having to
rewrite or compile them. It is also known as “Write-once-run-anywhere” approach.

7. Portable – the portability actually comes from architecture-neutrality.

8. High Performance - java programs are compiled to portable intermediate form


know as bytecodes, rather than to native machine level instructions.

9. Robust – The multiplatform environment of the web places extraordinary


demands on a program, because the program must execute reliably in a variety of
systems.
10. Interpreted – Java is both compiled and interpreted in java compiler which
translated into java source file to bytecodes.
Introduction of Java
- Write-once-run-anywhere is the main goal of java creator James Gosling by
Sun Microsystem in 1991. The first java version was released in 1995. Sun
Microsystem was acquired by the Oracle Corporation in 2010. In 2006 sun
started to make Java available under the GNU General Public License
(GPL). Later on Oracle continues this project called OpenJDK.

History of java

What is Java?
• Is an object-oriented programming language
• Is both a programming language and a platform
• Java is hardware-independent and can run on various operating systems
• As a programming language, it
– Contains specifications for writing or coding programs
– Has a compiler for checking syntax and converting programs to
bytecodes
– Has a rich set of APIs (Application Programming Interfaces) that can
be reused and modified
 As a platform, it
– Converts bytecodes into executable code
– Has a JVM (Java Virtual Machine) to run java
programs on various operating systems

Java

• Was created in 1991 by James Gosling, et al. of Sun Microsystems


• It was originally designed for consumer electronic devices and was called
Oak
• With the advent of the Internet, Sun developed a browser named HotJava
using Oak
• In 1994, Sun renamed Oak to Java and released a free alpha version of the
JDK (Java Developer’s Kit) composed of Java and HotJava
• In 1996, Netscape Communications Corp announced support for Java
applets which was later included in version 2.0 of the Navigator browser
• Development Tools
– Compiler, launcher and documentation tools are in the JDK
• Application Programming Interface
– Contains classes ready to be used in programs
• Deployment Technologies
– Contains software for deploying applications to end users

The Java Platform

• A platform is the hardware or software environment where a program runs


• This usually refers to the operating system and the underlying hardware

The Java Platform

• The Java platform is different in that it is a software-only platform that runs


on top of a
hardware platform
• It has 2 components:
- Java Virtual Machine (JVM)
- Java Application Programming Interface (API)

The Java Virtual Machine (JVM)

• The Java “interprets” bytecodes, and through its java launcher tool, runs the
application
program
• It sits on top of the operating system. Each
operating system has its own JVM.

Bytecodes is the machine language of the JVM. Source code is written on a text
file with a .java extension.
This source code is compiled by the java compiler and produces bytecodes with a
.class extension.

There is a JVM for most operating systems (Windows, Linux, Unix, MacOS)

Note: This makes Java “portable”, e.g., the same program (in bytecodes) can be
“ported” and run on other operating systems without need for recompilation.

Features of a Java Program

• Object-oriented
• Distributed
• Interpreted
• Robust
• Secure
• Architecture Neutral
• Portable
• High Performance
• Multi-threaded
• Dynamic
• A tool used to create, debug and execute a Java program
Java Comments

• Single line comment


//This is a single line comment

• Multi-line comment

//This is a comment spreading


//over two lines or more
or
/*
This is a comment spreading over two lines or more
*/

• Javadoc comment – starts with a single forward slash and two asterisks (/**)
and ends with an asterisk and one slash (*/). Each line of the comment starts
with one asterisk
/**
* This is a Javadoc comment
*/
EXERCISE TIME! NO. 01

Name: _______________________ Strand: __________________


Score: ___________________

What are the characteristic of a JAVA PROGRAMMING LAGUAGE? Enumerate your


answers.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

Define the Following:

1. Object-Oriented Programming –

2. Architectural Neutral –

3. Dynamic and Extensible code –

4. Portable –

5. Robust –

What are the types of Java comments?

1.
2.
3
LESSON 2

Object – Oriented Programming


Object – Oriented Programming

- is a programming language style organized around objects rather than


“action” and “data” rather than logic. below are four core concept of Object
oriented programming in the following sequence:

 Inheritance
 Encapsulation
 Abstraction
 Polymorphism

The image above shows that the puppy Labrador inherits the properties of the sire
(father dog). Similarly, in java, there are actually two classes:

1. Parent class (Super or Base class)


2. Child class (Subclass or Derived class)
Single Inheritance:

Class A Single inheritance – It allows to inherits the properties to


another. It enables a derived class to inherit the properties and
behavior form single parent class.
Class B
Java syntax for single inheritance:

Class A
{
-------------
Class B Extends A {
}
Multilevel Inheritance:

Class A Multilevel Inheritance – a class having more than one parent


A class but at different level. In the flowchart, Class A is the
parent of Class B, Class B is the parent of Class C. So in this
Class B case Class C implicitly inherits the properties and methods of
A Class A along with the Class B.
Class C
A
Java syntax for Multilevel inheritance:

Class A {
}
Class B Extends A {
---
}
Class C Extends B {
----
}

Hierarchical Inheritance:

Class A Hierarchical Inheritance – a class having more than one child


A classes (sub classes) or in other words, having more than one
child.
Class A Class A
A A
Java syntax for Hierarchical inheritance:

Class A {
---
}
Class B Extends A {
---
}
Class C Extends A {
---- }
Hybrid Inheritance:
Class A Hybrid Inheritance – is the combination of more than one
A inheritance and multilevel inheritance. The flowcharts show
that, Class A is a parent for Class B and C, in other hands
Class B Class C Class B and C are the parent of Class D which basically the
A A
only child of Class B and C.

Class D
A
Object Orientation Programming: Encapsulation

Encapsulation - is the process where you bind your data in order to make it safe
from any modification. Similarly, through encapsulation the methods and variables
of a class are well hidden and safe.

Let us look at the code below to get a better understanding of encapsulation:

Explanation:

I have decided create a Class Student which has a private variable name. We have
also created a getter and setter methods which we can get and set the name of a
student. Through these process, any class which has plan to access the name
variable has to do it using these getter and setter methods.
Object Orientation Programming: Abstraction

Abstraction – refers to the quality of dealing with the ideas rather than events. Its
main goal is to handle complexity by hiding unnecessary details from the user.
Example, I’m a pineapple juice addict. So, when I finish my breakfast, I go into my
kitchen, switch on the blender machine and make a juice.
In other words, you just interact with a simple interface that doesn’t require any
knowledge about the internal implementation. You need to know how to use your
blender machine to make a juice. The thing you don’t need to know how the
blender machine is working internally to make a juice.

Abstraction in two ways:

a) Abstract Class
b) Interface

Abstract Class – it has the ability to hide the internal implementation details.
Similar to the blender machine you just need to know which methods of the object
are available for the specific operation. But you don’t need to understand how this
method is implemented and which kinds of action it has to perform to create the
expected result.

Note: You can achieve 0-100% abstraction using abstract class.


In order to use abstract class, you have to inherit it from another class where you
have to provide implementation for the abstract method.

Interface – java is a blueprint of class or you can say it is a collection of abstract


methods and static constant. Along with abstraction, interface also helps to achieve
multiple inheritance in java.

Note: You can achieve 100% abstraction using interfaces.


So an interface basically is a group of related methods with empty bodies. Let us
understand interfaces better by taking an example of a “ParentCar” interface with
its related methods.

Java syntax:

Public interface ParentCar {


Public void changeGear( int newValue );
Public void speedup( int increment );
Public void applybrakes( int decrement);
}
Sample Syntax:

public class Audi implements ParentCar


{
int speed=0;
int gear=1;
public void changeGear( int value){
gear=value;
}
public void speedUp( int increment)
{
speed=speed+increment;
}
public void applyBrakes(int decrement)
{
speed=speed-decrement;
}
void printStates(){
System.out.println("speed:"+speed+"ge
ar:"+gear);
}
public static void main (String [] args) {
// TODO Auto-generated method stub
Audi A6= new Audi ();
A6. speedUp (50);
A6. printStates ();
A6. changeGear (4);
A6. SpeedUp(100);
A6. printStates ();
}
}
Polymorphism: In Java, compile time polymorphism refers to a process in which
a call to an overloaded method is resolved at compile time rather than at run time.
Method overloading is an example of compile time polymorphism. Method
Overloading is a feature that allows a class to have two or more methods having
the same name but the arguments passed to the methods are different. Unlike
method overriding, arguments can differ in:

1.Number of parameters passed to a method


2. Datatype of parameters
3. Sequence of datatypes when passed to a method.

class Adder {
Static int add(int a, int b)
{
return a+b;
}
static double add( double a, double b)
{
return a+b;
}

public static void main(String args[])


{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
EXERCISE TIME! NO. 02

Name: _______________________ Strand: __________________


Score: ___________________

What are the classification of inheritance?

1.
2.
3.
4.

What are the two types of Classes?

1.
2.

Define the following:

1. Inheritance –

2. Encapsulation –

3. Abstraction –

Explain the Syntax of Abstraction. Page 19


LESSON 3

5 basic concepts of any programming language


Basic concepts of any programming language
1. Variables
2. Control Structures
3. Data Structures
4. Syntax
5. Tools

What is variable type?

- A variable serve as the carrier which holds the value while the java program
is executed. There are three types of variable in java: Local, Instance and
Static.

Note: for more details and exam for variable in java please visit:
tutorials.jenkov.com/java/variables.html#java-variable-types
1. LOCAL VARIABLES

- A local variable cannot be defined with the “static” keyword. Take note that
you can use variable within that method and the other methods on the class
are not aware that the variable exists.
- It also reserved area allocated in memory. In other words, you can just
change the value of it.

Example:

Int data = 50; // here data is variable

2. INSTANCE VARIABLES

- It is called instances because its value is instance specific and is not shared
among instances.

Class page {
Public String pagename;
// instance variable with public access
private int pagenumber;
//instance variable with private access
}
3. STATIC VARIABLE

- A variable which declared as static is called static variable. The Memory


allocation for static variable happens only once when the class is loaded in
the memory.

// static method
static void ml ()
{
System.out.println(“from m1”);
}

Public static void main (String [] args)

// calling ml without creating any object of class Test


m1();
}
}

Expected output:
From 1

If you need to do computation in order to initialize your static variable, you can
declare a static block that gets executed exactly once, when the class is first loaded.
Consider the following java program demonstration use of static blocks.
Example Syntax

//static block
static {
System.out,println (“Static block initialized”);
b =a * 4;
}

//static variable
static int a = 10;
static int b;

Public static void main (String [] args)


{
System.out.println (“from main”);
System.out.println (“value of a : ” + a);
System.out.println (“from main” + b);
}
}

Expected output:

Static block initialized.


Form main
Value of a : 10
Value of b : 40
Quality Requirements
• Reliability
• Robustness
• Usability
• Portability
• Maintainability
• Efficiency / Performance

Programming Methodologies and Approaches

• Structured or Procedural
– Breaks down a complex problem into modules or procedures
(decomposition)
– Uses top-down and/or bottom-up approach
– Object-oriented
– Objects are defined to accomplish a task
– Objects are things, people, entities that are naturally part of the
program.
– O-O makes software representations of these entities
Problem Definition
– Define problem statement and decide problem boundaries
– Understand problem statement, requirements, required output
• Problem Analysis
– Determine and gather required resources to solve the problem
• Algorithm Development
– Develop step by step procedure(s) using the given specification
• Coding and Documentation
– Uses a programming language to write or implement actual
programming instructions (CL, C++, Java, C#, etc.)
• Testing and Debugging
– Test the program whether it is solving the problem for various input
data or not
– Test whether it is providing the desired output or not
• Maintenance
– Problems encountered needs enhancements
EXERCISE TIME! NO. 03

Name: _______________________ Strand: __________________


Score: ___________________

Test I.

Differentiate between Instance and Static variables.

Create your own syntax for the following:

1. Static

2. Local

3. Instance

Test II. Hands-on activity.


Note: Actual activity will be given during the class time.
LESSON 4

Programming Design Tools


Program Development Tools

At the programming level, the following tools help in designing programs:


• HIPO Chart
• Narratives
• Flowchart
• Pseudocode

HIPO Chart - Hierarchical Input-Process-Output


• A tool used for Problem Definition and Problem Analysis
• Helps clarify ambiguous portions of the specifications

Narratives
• Program logic is described and communicated through
the use of words
• Procedures / steps maybe narrated via complete sentences or phrases –
maybe numbered

Narratives – Sample Problem


A deck of 10 cards contains numbers ranging from 0 to 9, where 0 indicates the
end of file. Calculate and print the average of the sum of squares
Narratives – Sample Problem Solution

Step 1: Set COUNTER to 1.

Step 2: Set SUM-SQUARES to 0.

Step 3: Read a card (containing a NUMBER).

Step 4: If NUMBER = 0, then go to step 9.

Step 5: Square the NUMBER.

Step 6: Accumulate the sum of the squared number,


i.e., add the squared number to SUM-SQUARE.

Step 7: Increment counter, i.e. add 1 to COUNTER.

Step 8: Go to step 3.

Step 9: Compute for the average of the sum of squares,


i.e., divide SUM-SQUARE by COUNTER and store in AVERAGE

Step 10: Print the AVERAGE.

Step 11: End the program.


Flowchart

• Is used to graphically present the solution to a problem. It uses flowcharting


symbols linked together in a “flow” that will arrive at the solution.

• Among the tools, it is the easiest to understand because of it is visual appeal.


However, the chart can get very cluttered and disorganized when working on
complex problems.

Pseudocode

• Describes the logical flow of the solution to the problem through English-
like code that closely resembles the actual programming language to be
used.

• There are no rigid syntax rules in pseudocode.

• More emphasis is placed in the logic of the solution rather than the syntax of
the language.

HIPO chart

The HIPO Chart will be used throughout the course as the tool for
problem definition and analysis.

To derive a HIPO Chart, questions such as these may be asked:


• What are the outputs required?
• What are the inputs needed to produce the outputs?
• What are the processes needed to transform the inputs to the desired
outputs?
Simple Adding Problem

Given 2 numbers, print the sum of the 2 numbers Using HIPO,

1. Define the outputs needed

2. What inputs are provided? What other inputs are needed to produce the
output?

2. What inputs are provided?


What other inputs are needed to produce the output?

3. What processes are needed to transform the inputs to the desired outputs?
Guidelines in developing the HIPO

• Outputs should be determined first before inputs or processes. This


establishes the objective and scope of the solution. Limit the outputs
to those that are required in the specifications.

• Outputs are easy to identify because they usually follow verbs like
“display”, “print” or “generate”.

 Inputs are also given in the specifications. In simple problems, the


inputs clearly lead to the outputs. In complex problems, this may not be
visible outright, but on further refinement of the solution.

 Processes contain the actions taken to transform the inputs to outputs.


This can be stated in English and do not have to conform to any
programming language.

 Actions on processes are executed sequentially, e.g., from top to


bottom. Numbering the steps signify the order of execution.
Flowchart
– are used in designing and documenting or program. According to
Wikipedia a flowchart is described as “cross-functional” it is when the chart
is divided into different vertical or horizontal parts, to describe the control of
different organizational units. A cross-functional flowchart will also help the
programmers to correctly identify the location or maps for performing an
action or making a decision, note that each organizational unit have different
parts and functions.

Common Symbols of flowchart

SHAPE NAME DESCRIPTION


Indicates the beginning and the
Terminal end of a program.

Represent a set of operations that


Process changes value, form or location
data.
Shows the conditional statement
Decision the operation is commonly a
yes/no question or true/false
situation.
Show the order or a sequence of
Flowline operation.
Shows named process which
Predefined defined elsewhere.
Process

Indicates the process of inputting


Input/output and outputting data.
Pseudo code
– Is a term which often used in programming and algorithm base
fields. It is a methodology that allows the programmer to
represent the implementation of an algorithm.

Algorithm – It’s an organized logical sequence of the action or approach


towards a particular problem, A programmer implement an algorithm to solve
a problem.

Advantages of Pseudocode

- Improves the readability of any approach. It’s one of the best


approaches to start implementation of an algorithm.
- Acts as a bridge between the program and the algorithm or flowchart.
- The main goal of pseudo code is to explain what exactly each line of a
program should do, hence making the code construction phase easier
for the programmer.

HOW TO WRITE A PSEUDO-CODE?

Follow the link: https://www.geeksforgeeks.org/how-to-write-a-


pseudo-code/
EXERCISE TIME! NO. 04

Name: _______________________ Strand: __________________


Score: ___________________

Test I.

Problem1:
• Given 3 whole numbers, print out the average of the 3 numbers.
 Create a HIPO chart that would show your solution to the problem.

Problem2:
 A list contains names of students. Count how many times the name “Ana”
appears in the list.
 Create a HIPO chart that would show your solution to the problem.
Problem3:
• A box contains balls with different colors. Count the number of balls per
color and display the total of all colors.
• Create a HIPO chart that would show the solution to
the problem

Test II.

Good for (50 points)


Create 1 situation that can apply using Pseudo-code and flowchart.
LESSON 5

Object-Oriented Concepts and


Java
What is Object-oriented Technology?

• Object-oriented methodology models real-world objects


• Programs and software are built from these objects
• In contrast, structured approach focuses on tasks and procedures

Benefits of OO Technology
• Ease of use
• Productivity
• Easy testing, debugging, and maintenance
• Reusable
• More thorough data analysis, less development time, and more accurate
• Data is safe and secure
• Sharable

Benefits of OO Programming Approach


• Better abstractions (modelling information
and behavior together)
• Better maintainability (more comprehensible, less fragile)
• Better reusability (classes as encapsulated components)
Building Blocks of OOP

Classes and Objects


• Java programs are built using classes and objects.
• The JDK itself has a rich set of classes that can be used and re-used.

• Class
– Is a blueprint or template of an object
– It represents broad groups of objects
– It contains elements common to a group of objects
– Example:
• Animal
• Vehicle
• Object
– Is an instance of a class
– It is a specific occurrence of a class
– Objects have state and behavior
– Example:
• Cat is an instance of the class Animal
• Car is an instance of the class Vehicle
– A cat has several states: asleep, alive, lost
– Its behavior could be: eating, jumping, etc.
• The basic structure in object-oriented programming languages are a class.
• Java programs are built using classes and objects.
• A class is:
– a template or a blueprint
– Made up of attributes and behavior
– Attributes are represented by variables and behavior is revealed
through methods

An example of a class (from Chapter 1)


– class Student

class name
attributes /
variables

Attributes/ variable
attributes / variables

behavior / methods
Defining a class

In Java, a class is identified by a class name. To define or declare a class:


class < ClassName > {

[ attribute/variable declarations ]
[ behavior/method declarations ]
}

• Conventions used
– Italicized words bounded by < > are programmer- supplied
– Text in [ ] are optional
– Most object-oriented languages, such as Java, are case-sensitive.
Therefore, Student is different from student.

Method

1. Specifies the behavior(s) of a particular class, and is defined within a class


2. Contains a statement or set of statements that a
- program must do or accomplish
3. Identified by a method name, followed by a pair of
- open and close parentheses
4. It may or may not be bounded by a return statement

Defining a method
• – To define or “declare” a method:
• return-type < methodName > ( ) {
• [statement 1];
• [statement 2];
• [return <variableName>]
• }
What does Class mean?

A class, in the context of Java, are templates that are used to create objects, and to
define object data types and methods. Core properties include the data types and
methods that may be used by the object. All class objects should have the basic
class properties. Classes are categories, and objects are items within each category.

The above example is a class tree, and the string is the class data type. A class
declaration is made up of the following parts: 


• Modifiers
• Class name
• Keywords
• Class body within curly brackets {}

This may be explained with a hypothetical example of a tree and types of trees.
Generally, a tree should have branches, stems and leaves. Thus, if Banyan is a tree,
Banyan should have all of the characteristics of a tree, such as branches, stems and
leaves. It is impossible to say that a pigeon is a tree, because the pigeon does not
have branches, stems and leaves. Similarly, basic Java object properties are defined
within that object’s corresponding class.

This definition was written in the context of Java


Procedure:

Steps in program coding using a text editor and


console:
1. Open a text editor such as Notepad or WordPad (for Windows); vi for Linux
or Unix.
2. Write or type your source code (as shown above) in the text editor.
3. Save your file as: HelloWorld.java. Don’t forget that your file should have an
extension of
“.java”.

4. Compile your program:


- In Windows, open another window in the MS-Dos command prompt
- Go to the folder where your program HelloWorld.java is saved.
- To compile, type the command:
javac HelloWorld.java
- Make sure there are no syntax (or typing) errors.

5. Running your program:


5a. If the compilation from the previous step
was successful, a HelloWorld.class file is
created on the current directory. Check to see if this file exists.
5b. To run your program, type the command:
java HelloWorld
EXERCISE TIME! NO. 06

Name: _______________________ Strand: __________________


Score: ___________________

Problem:

Instruction:
 Write a program that would print out “Hello World!”
 Using the steps in program development from chapter 1:

1. Problem Definition:
Print out “Hello World!”

2. Problem Analysis using HIPO Chart

3. Program coding using java

CHAPTER II
LESSON 6

Variables and Data Types


Data Types
Programs use 2 general types of data:

• Constants
o Values remain constant and do not
change.
o Literals are unnamed constants.
• Variables
o Can hold different values. The values can
be changed anywhere in the program

Variables
- are named memory locations whose contents may vary or differ over time.
The name serves as an address to the location and gives access to the value that the
variable holds.

- At any given time, a variable holds one value

- Unlike literals, variables have to be declared

A variable declaration is a statement that contains the variable’s data type


and identifier

• The data type describes the following:


– What values can be held by the variable
– How the variable is stored in memory
– What operations can be performed on the variable
• To declare a variable:
< data type > < identifier or variable name > [= initial value];
• The variable name should comply with naming conventions for identifiers
Variable Declaration

• Examples of variable

declaration: String name;


int age;

• Example of variable

declaration and initialization:


String name = “Ana”;
int age = 18;

Types of Variables

• Variables can also be classified according to its contents and/or how they
will be stored in memory.

In general, programs use the following types of variables:

 Numeric variables
Holds numbers or digits and can be used for mathematical computations.
• Textual data
Holds text, such as letters of the alphabet, and
other characters

• Boolean data
Holds a value of true or false

Primitive Data Types

• The Java programming language defines eight primitive data types for each
of the variable types:
– For logical: boolean
– For textual: char
– For numerical:

Integers: byte, short, int, long


Floating point: float, double

Boolean Variables and Literals

• The boolean literals true or false can be assigned as values to any boolean
variable.
• A boolean variable can hold any of the boolean literals: true or false.
• To declare variables of type boolean:
boolean < identifier or variable-name >

• Example:
boolean result = true;

• The example declares a variable named result that is of boolean data type
and assigns it the boolean literal true
Char
– is a single Unicode character. A Unicode character is represented by 16-
bits and includes symbols

 and other special characters


– character literals are enclosed in single quotes (‘ ‘).
– Example of char literals:

 ‘A’ ‘1’ ‘b’ ‘\’’


– If the single quote is included in the string, add the escape character \ before
the single quote

 char
– To declare variables of type char:
char < identifier or variable-name >

Example:

char gender = ‘F’;

Integers

- Are whole numbers with a sign (positive or negative)


Example of integer literals:
+23
-100
123456789
50L

(note: no commas are used when coding integer literals; 50L is an integer
value whose data-type is long)
Numeric Variables and Literals

• Integers from different number systems (base 8, base 10 and base 16) can
also be represented.

– Example: The number 12 is represented as follows:


In decimal (base 10): 12
In hexadecimal (base 16): 0xC In octal (base 8): 014

The following are the different integer data types and their range of values:

Integer Size Integer Data Type Range

8 bits byte -27 to 27 – 1

16 bits short -215 to 215 – 1

32 bits int -231 to 231 – 1

64 bits long -263 to 263 – 1


• To declare integer variables:
byte < identifier or variable-name >
short < identifier or variable-name >
int < identifier or variable-name >
long < identifier or variable-name >

Example:

int noOfDaysInAMonth

Floating Point
- Are fractional numbers with a decimal point.
- They may be positive or negative.

Example:

3.1416, -20.5, 3.14F, 6.02e23

There are 2 types of floating point literals or variables:

1. float
2. double

• float literals are followed by an “f” or “F”, while double literals have a “d”
or “D” at the end.
• If neither is present, the default data type is double.

• Floating point literals can also be expressed in standard format or in


scientific notation.

Example:

583.45 (standard)

5.8345e2 (scientific)
Floating point data types have the following ranges:

Float Size Float Data Type Range

32 bits float -231 to

231 – 1
64 bits double -263 to

263 – 1

• To declare floating point variables:

float < identifier or variable-name >

double < identifier or variable-name >

Example:
float area;
double salary;
The String Class

String
– A cluster of characters.
– String literals are enclosed in double quotes (“ “).

Example of String literals:


“blue” “ABC 123”
“40-D C.P. Garcia Ave., Quezon City”

– If the double quote is included in the string, add the escape character \ before the
double quote

• To declare variables of type String:


String < identifier or variable-name >

• Example:
String message

• String is not a primitive data type. String is defined as a class in the


java.lang package. String literals and variables are objects or instances of the
String class.

Assigning Values to Variables

• The assignment operator “=“ is used to assign


values to variables.

• The following can be assigned or “moved to” a


variable:
– Literals
– Another variable
• Both sides of the assignment variable should be
of the same data type
The declaration

String name = “Ana”;

 can be broken down into 2 statements:


String name; // declaration statement

name = “Ana”; // assignment statement

1. It is always good to initialize variables as you


declare them.

2. Use descriptive names for your variables.


Example: a variable that contains a student’s grade may be named studentGrade
and not just random letter and numbers.

3. In object-oriented programming, variable names begin with a lowercase


letter. The starting letter of succeeding words are capitalized.
EXERCISE TIME! NO. 05

Name: _______________________ Strand: __________________


Score: ___________________
LESSON 7

Arithmetic and Relational Operators


What are Operators?

• Operators are needed to transform or manipulate data


• Mathematical computations, comparison of two values or setting initial
values of variables are made possible by using arithmetic or relational
operators
• Operators are important in that a miscalculation, missed value or wrong
comparison may compromise the integrity of a whole module or a whole
program

The two types of operators in this section are:


– Arithmetic operators
– Relational operators

 An arithmetic or logical expression is formed by a combination of variables


or literals and an operator

 Format for an arithmetic or logical expression:


< operand1 > operator < operand2 >
where operand1 or operand2 could be any literal
or variable name

• Arithmetic operators perform mathematical


calculations on two numeric operands

Operator Description

+ Addition
- Subtraction

* Multiplication

/ Division

% Remainder after Division

• Examples of arithmetic expressions:


length * width
12.345 + 67.893 + 75.9004
• Expressions with mixed operands are evaluated
using rules of precedence
• Rules of precedence dictate the order of evaluation. In this order,
certain parts of the expression gets executed first before others

• For arithmetic operators, the rules of precedence


(or order of evaluation) are:
1. Expressions in parentheses
2. Multiplication and Division, from left to right
3. Addition and subtraction, from left to right
• The assignment operator “=“ has the lowest
precedence

• In the expression,
answer = 4 + 6 * 2
the result of the expression would be 16.

• However, if it were modified to:


answer = (4 + 6) * 2
the result of the expression would be 20. This value would then be assigned to
the variable answer.

• Java also has unary increment and decrement operators that increase or
decrease the value of a variable by 1
o Increment operator
< operand1 > ++
o Decrement operator
< operand1 > --
where operand1 could be any literal or variable name

• Example:
the expression,
count = count + 1; could be written as
count ++;
• Increment and Decrement operators could be
postfix or prefix as shown below

Increment and Decrement Operators

Operator Use Description

++ op++ the value of op was evaluated before it


was incremented

++ ++op the value of op was evaluated after it


was incremented

-- op-- the value of op was evaluated before it


was incremented
-- --op the value of op was evaluated after it
was incremented

• Relational or conditional operators perform comparison of two literals or


two variables, or any combination of both.
• The evaluation of a conditional expression results in a boolean value of
either true or false

• Example: the expression


age > 18
will evaluate to only one value: true or false

Relational Operators

Operator Name Description

== Equal to Evaluates as true if its operands are equivalent

> Greater than Evaluates as true when the left operand is greater than
the right operand

< Less than Evaluates as true when the left operand is less than
the right operand
Operator Name Description

>= Greater than or Evaluates as true when the left


equal to operand is greater than or equal to the
right operand

<= Less than or equal to Evaluates as true when the left


operand is less than or equal to the
right operand

!= Not equal to Evaluates as true when both operands


are not equal
Boolean Logical Operators

• All of the binary logical operators combine two boolean values to form a
resultant boolean value
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else

• Effect of logical operation


A B A|B A&B A^B !A

FALSE FALSE FALSE FALSE FALSE TRUE

TRUE FALSE TRUE FALSE TRUE FALSE


FALSE TRUE TRUE FALSE TRUE TRUE

TRUE TRUE TRUE TRUE FALSE FALSE

It is the single equal sign (=)


Format:
vartype = expression;

The variable type must be compatible with the type of expression


int x, y, z;
x = y = z = 100; //set x, y and z to 100

Special ternary (3-way) operator replacing certain


types of if-then-else statements
Format:
expression1 ? expression2 : expression3
here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluation; otherwise, expression3 is
evaluate

Highest
++ (postfix) -- (postfix

++ (prefix) -- (prefix) ~ ! + (unary) - (unary) (type-


cast)
* / %
+ -
>> >>> <<
> >= < <= Instance of
== !=
&
^
|
&&
||
?:
->
= Op=
Lowest

• Raise the precedence of the operations that are


inside them
a >> (b + 3) or (a >> b) + 3
• Sometimes used to help clarify the meaning of an
expression
a | 4 + c >> b & 7
(a | (((4 + c) >> b) & 7))
EXERCISE TIME! NO. 07

Name: _______________________ Strand: __________________


Score: ___________________

1. Determine the result of the following conditional expressions, given the


following variables and their values:

int a = 250; int c = 350;


int b = 300; int d = 250;

a>b
b <= c
a >= d
c != d

2. Which of the following evaluates to 10?

a. 3 + 5 * 2
b. 5 + 20 / 4
c. 25 / 2 + 3
d. all of the above

3. What is the value of the expression


27 – 7 * 3 / 3?
LESSON 8

Arrays
What is an Array?

Array Definition

• An array is a collection of a fixed number of homogeneous data items or


elements
- Collectiona
A group of data that are logically related.

- Fixed number
Once an array is declared, the size is fixed and cannot be altered.

- Homogeneous
Elements are of the same data type with the same characteristics.

Characteristics of an Array

• Array-name

- All elements in the array are referenced or accessed through the array-
name.
- Naming arrays follow the conventions for naming identifiers.

• Dimension

- Elements in an array can be grouped into sub-groups or categories.


The sub-groups are called dimensions.
- An array having 1 group is called a single-dimension or one-
dimensional array. An array having more than 1 group is called a
multi-dimensional array.
• Size
- The number of elements that an array can contain is called its size.

• Subscript

- Subscripts define the relative position of an element in an array.


Subscripts always start with position 0.
- The number of subscripts used depends on the number of dimensions
an array has. A single-dimension array has 1 subscript. A 2-
dimensional array has 2 subscripts.

- A subscript or index is used to reference or access a particular element


in an array.

- Example:
To access or reference the color “red” in the colorArray:
colorArray[0]
To access or reference the name “Cathy” in the
FemaleNames row of the names array:
names[0][3]

• One-dimensional array
colorArray

red yellow blue green white

colorArray[ 0]
colorArray[ 4]
array name: colorArray
elements : red, yellow, blue, green
array size: 5
• Two-dimensional array
names

Array Declaration
• Arrays, like variables, are declared and initialized.
• To declare an array,

data-type [] <array-name>;

- data-type – specifies what type of data the array can hold.


Arrays do not support multiple data-types.
- array-name – specifies the array’s name using the naming
rules for identifiers.
- [ ] – empty pair of square brackets differentiates an array declaration
from a normal variable declaration.
• Declaring an array does not create the array. It only reserves the array name
as a “placeholder” for the location of the actual contents of the array.
• A declaration such as:

String [] daysOfTheWeek;

Will allocate storage in memory named daysOfTheWeek


• The declaration,

String daysOfTheWeek [];


and instantiation,

daysOfTheWeek = new String [7];

can be combined in one statement:

String daysOfTheWeek [] = new String [7];

• An array can also be instantiated or initialized by directly


populating it with data.
• Example:
String [] daysOfTheWeek =
{“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”,
“Saturday” };

• Exercise 10.1
Write the statements that will declare and initialize the following arrays:
1. The first ten letters of the alphabet.
2. The ages of 5 students: 16, 20, 17, 18, 17
3. The salaries of employees. Note: Initialize array elements to 0.
4. The Boolean values “true”, “false”, “true”, “false”.
5. The grades of 7 students. Assign specific grades to each element.
 Note:
1. Like variables, arrays should be initialized once they are declared.
2. String and character arrays should be explicitly initialized to blanks.
Arrays - Sample Program

• Sample Program to print all the members of an array:

public class ArraySample {


public static void main (String [] args) { int ages [] =
new int [100];
for (int i=0; i<100; i++) {
System.out.println(ages[i]);
}
}
}

• The length field of an array contains the number of


elements in the array.
• The length field is used with the dot “.” operator in after
the array-name.
• Example:
ages.length

• When traversing arrays, use the length field as the loop control variable in a
for loop. This will allow the loop to adjust to different-sized arrays.
• Use named constants in declaring the sizes of arrays to make them easy to
change.
Example:
final int ARRAY_SIZE = 1000;
int [] ages = new int [ARRAY_SIZE];
• Multidimensional arrays are implemented as array of
• arrays.
• Multidimensional arrays are declared by appending the appropriate
numbered bracket pairs after the array name.

Example:

//integer array 512 x 128 elements

int twoD [] [] = new int [512] [128];

//character array 8 x 16 x 24

char [] [] [] threeD = new char [8] [16] [24];

//String array 4 rows x 2 columns


String [ ] [ ] dogs = {{“terry”, “brown”},
{“Kristin”, “white”},
{“toby”, “gray”},
{“fido”, “black”},
};
• Arrays are powerful structures when combined with for loops. They can
eliminate writing several lines of code and minimize errors.
• The following are common uses of arrays in designing programs:
• Replacing Nested Decisions
• Searching for Values
• Using Parallel Arrays
• Searching with Range Values
EXERCISE TIME! NO. 08

Name: _______________________ Strand: __________________


Score: ___________________

Problem 1:

The Human Resource department of a company provides its employees with


an annual health insurance coverage. Aside from the employee himself, the health
insurance provider can cover up to 3 dependents per employee. The HR
department conducted a survey of 15 employees and asked for the number of their
dependents. Write a program that will summarize the number of dependents that
employees have. A sample of the report is shown below.

Problem 2:
In a store, an order is placed for an item indicating the item number and quantity.
Design a program that would validate the item number. Do this by
searching through the valid item numbers of the store.
The store only has six item codes as follows: 106, 108, 307, 405, 457, 688
Prompt the user for an item code. If the item code is valid, display the
message, “Item available.” If the item code is invalid, display “Item not
found.”
Problem 3:

Revise Exercise 10.3 to include the following:


The user has requested to print the price of the item that was being searched for. If
found, print the appropriate message and display the item code.

Solution:
• Use a parallel array to store the prices.
• Only one subscript will traverse both the items array and the
prices array.

Problem 4:

• As a marketing strategy for the store, discounts are made available to


customers who purchase a large number of items. Print out the
discount for the selected item. The discounts are as follows:

Quantity Discount (%)

0–3 0%

4–6 5%

7 – 10 10%

11 or more 15%
LESSON 9

Java Strings and Method


Java String – Definition

Unlike primitive data types, java Strings are objects derived from the String
class.
• A string is a series of Unicode characters held under a variable name.

Example: “Java”

String someText = “Java”;

In the first line, “Java” is a String literal.


The second line tells Java to set up string object named
someText which contains the four characters “J”, “a”, “v”, “a”.

• Strings are created by declaring a variable whose type is


String and assigning a String literal.

Example:
String greeting = “Hello World”;

Creating Strings

• Another way to create a String is by using the new


keyword and a constructor
• The String class has 13 constructors that allow you to provide different types
to construct the String.
Example:
char [] helloArray = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’};
String helloString = new String (helloArray); System.out.println(helloString);
String Methods

• The String class has several useful methods that can be used for manipulating,
comparing, accessing and formatting Strings:

public char charAt (int index) Returns the character located in the specified index

public int compareTo (String Compares this String with the specified parameter.
anotherString) Returns a negative value if this string comes
lexicographically before the other string, 0 if both of the
strings have the same value and a positive value if this
string comes after the other string lexicographically

public int compareToIgnoreCase (String Like compareTo() but ignores the case used in this
anotherString) String and the specified String
public boolean equals (Object anObject) Returns true if this String has the same sequence of
characters as that of the Object specified, which should be
a String object or if it doesn’t match the sequence
of symbols in this string, the method returns false

public boolean equalsIgnoreCase (String Like equals() but ignores the case used in this String and
anotherString) the specified String

public int length() Returns the length of the String

public String replace (char oldChar, char Returns the String wherein all occurrences of the oldChar
newChar) in this String is replaced with newChar

public String substring (int beginIndex, Returns the substring of this String starting at the
int endIndex) specified beginIndex up to the endIndex

public char toCharArray() Returns the character array equivalent of this string

public String trim() Returns a modified copy of this String wherein the
leading and trailing white spaces are removed

public static String valueOf( - ) Takes in a simple data type such as Boolean, integer, or
character, or it takes in an object as a parameter and
returns the String equivalent of the specified parameter
String Example

public class StringDemo {

public static void main(String[] args) { String name = "Christine"; System.out.println


("Name: " + name);
/* charAt */
System.out.println ("The 5th character of name: " + name.charAt (4) );
/* compareTo */
System.out.println ("Christine compared to Abigail: " + name.compareTo
("Abigail") ); System.out.println ("Abigail compared to Christine: " +
"Abigail".compareTo (name) ); System.out.println ("Christine compared to christine:
"+
name.compareTo ("christine") );
/* compareToIgnoreCase */
System.out.println ("Christine compared to (ignore case) christine: " +
name.compareToIgnoreCase ("christine") );
Method Declaration

A Method
• Is a block of code or a set of statement(s) that
accomplish a specific task.
• Example:

public void setName (String temp) {


name = temp;
}
• In the example, the method setName has only one function or purpose:to set
the value of an instance variable name.

• Methods define the behavior(s) of a class. They are members of the class.
They are usually located after declaration of the fields or variables
of the class, and before the main() method.

• To declare a method:

access-modifier return-type <methodName> (parameter list) {


[statement-1]; [statement-2];
[return] <variableName>;
}
Structure of a Method

• Parts of the method:


- Method Name
• An identifier which is usually a verb that describes what the
method does. Method names follow the naming conventions
for identifiers.
- Return Type
• All methods in java are required to have a return-type.
• A method that returns a value should specify the data-type of
the return value. This could be any one of the primitive data
types or a reference type.
• If the method does not return any value, the return-type is void.
Return-type

Example 1:

double computeAverage()

The method computeAverage() returns a value whose datatype


is a double.

Example 2:

void printMessage()

The method printMessage() does not return a value. Hence, the return-type is
void.

Body of the method

• Contains statement(s) that are executed when the method is called.


• Example:
void computeAverage() {
average = ((mathGrade + scienceGrade + englishGrade)/3);
}
Return statement

- Returns a value to the calling method.


- The value being returned should have the same data-type specified as
that specified in the method declaration.

Example:

double computeAverage() {
double average = ((mathGrade + scienceGrade + englishGrade)/3);
return average;
}

If the method’s return-type is void, there is no need for a return statement.


• A method can have only one return statement.

Parameter list or Argument list

• Aside from returning a value, a method can also accept values passed
by other methods. This is done by specifying parameters after the
method name.
• Parameters are enclosed in parentheses () and separated by
commas.
• Parameters are variables which will hold values that will be used
inside the body of the method.
• Example:
double computeAverage (double mGrade, double sGrade, double eGrade) { double
average = (mGrade + sGrade + eGrade) / 3
}
• Variables in a parameter list should be declared, e.g., the data-type
must be specified.

Access modifier
• Specifies which classes can access or call the method.
• If an access modifier is not specified the default access modifier is
applied.

Variables in Methods

• The body of a method contains statements that use


variables.
• Variables declared inside a method are called local variables.
• Local variables are visible only to the methods where they are declared.
They are not accessible from the rest of the class.

Scope of a Variable

• The scope of a variable determines where the variable


can be accessed and how long it will exist in memory.
• A variable’s scope is:
- inside the block where it is declared. All statements that will
use the variable have to come after the declaration statement.
• If the variable is declared in an inner block, it cannot be accessed in the
outer block since it no longer exists in the outer block.
Example:
public static void main (String args [] ) { int i = 0;
{
int j = 0;
}
}
• The variable i is accessible inside the main method, and in the inner block.
• The variable j is accessible inside the inner block only.

There are two types parameters passed to a method. Those that are passed by
value and those passed by reference.

Pass-by-Value:
• All primitive data types that are passed to a method are passed by
value.
• When a variable is passed-by-value to a method, the actual value of
the variable is received and stored in the method’s parameter list.
• Inside the method, changing the value of the parameter will
not affect the original variable passed.

Example – Pass by value (cont’d):

public static void test (int j) {


// change the value of parameter j j = 33;
}
Pass-by-Reference:
- Variables that are passed-by-reference are: Strings, arrays and
objects.
- When a variable is passed-by-reference to a method, a reference or
pointer to an actual value is passed. The parameter in the method
declaration receives the reference or pointer.
- Inside the method, changing the value of the parameter can change the
original values since the reference points to the location where the
actual values are stored.

Example - Pass by reference:

public class TestPassByReference {


public static void main (String [] args) { int ages [] = {10, 11, 12};
// print the array values
for (int i=0; i<ages.length; i++) {
System.out.println(ages[i] + “ “);
}
// call method test and pass the array reference test(ages);
// print array values again
for (int i=0; i<ages.length; i++) { System.out.println(ages[i] + “ “);
}
} // end of main
Example - Pass by reference (cont’d):
public static void test( int arr[] ); {
// change values of array
for (int i=0; i<arr.length; i++) { arr[i] = i + 50;
}
} // end of test method
} // end of class

• Types of Variables:
- Instance Variables (or non-static fields)
- Class Variables (or static fields)
- Local Variables
- Parameters

• Instance Variables (non-static fields)


• An object’s state is stored in instance variables, or variables
without the static keyword.

• Each instance of a class, or object, has its own copy of instance


variables. Changing the value of a variable does not affect other
objects instantiated from the same class.

• Class Variables (static fields)


• Variables declared with the static keyword.
• There is only 1 copy of a static variable, therefore, any
changes to its value affects other instances of the class.

• Local Variables
• Temporary variables declared and used in a method.
• Local variables are only visible in the method where they are
declared. They are not accessible outside the method.
• Parameters
• Temporary variables declared in the method definition.
• Like local variables, they exist only in the method and are not
accessible outside the method.
EXERCISE TIME! NO. 09

Name: _______________________ Strand: __________________


Score: ___________________

Test I.
Enumeration:

1. What are the types of variable?

2. What are the parts of method?

Test II.

Instruction: Declaring and creating methods


• Create a program that includes methods. (20 points)
Test II.

Make a program using the if-else that will prompt the user to enter a number.
Your program will determine if the number is positive or negative. If the number is positive,
print “POSITIVE” and add the number by 7, and print its result. If the number is negative, print
“POSITIVE” and add the number by 5 and print its result.

Sample Outpost

Enter a number: 2

Positive

2 when added to 7 is 10

Sample Outpost

Enter a number: -10

Negative

-10 when added to 5 is -5


LESSON 10

Getting Program Input


Getting Program Input

Programs get data or inputs from external sources: from users or


from files. Often, programs interact with users by getting input from the
keyboard.

Another way to pass data to programs is through the command


line when the java command is issued.

This chapter explains getting input from these sources:


- From the command line
- From the keyboard

A java application can accept any number of arguments


from the command line.

• Command-line arguments allow the user to affect the


operation of a program when it is invoked.

• The user enters arguments when invoking the program by specifying them
after the name of the class to be run.

For example, a java application program called “AverageGrade” takes in three


numbers and prints out the average grade.

• To run this program, you enter the following on the MS- Dos command line
(for Windows) or in the unix command line:

java AverageGrade 90 60 80

Note: The arguments are separated by spaces


Command Line Arguments

• The inputs supplied with the java command are passed as an


argument to the main method of the class.

• The main method public static void main (String [] args) accepts the
arguments and stores it in an array of String named args.

The arguments get stored in the args array as:

args [0] = “90”


args [1] = “60”
args [2] = “80”

• Remember that args is an array of Strings, therefore, numbers passed to the


program from the command-line will be stored as Strings.
• For numbers to be usable, the parseInt method of the Integer class can be
used to convert a String argument to an integer:

int firstArg = 0;
if (args.length > 0) {
firstArg = Integer.parseInt(args[0]);
}

 Before using command line arguments, always check the number of


arguments before accessing the array elements.
 Accessing an element beyond what was given will generate an exception or
an error.

For example, if a program needs 5 inputs from the user, the following code will
check if 5 arguments have been provided:
If (args.length != 5) {
System.out.println(“Invalid number of arguments”);
System.out.println(“Please enter 5 arguments”);
}
else {
// some statements here
}

For example, if a program needs 5 inputs from the user, the following code will
check if 5 arguments have been provided:

If (args.length != 5) {
System.out.println(“Invalid number of arguments”);
System.out.println(“Please enter 5 arguments”);
}
else {
// some statements here
}
Command Line Arguments in NetBeans

• To pass command-line arguments in NetBeans:


1. In the main menu, click on “Run” then select “Set Project
Configuration”. In the sub-menu, select “Customize”.
Passing Command-Line Arguments in NetBeans

1. Enter the data to be passed to the program in the input box


labeled “Arguments”. Click the “OK” button at the bottom.
2. Run the program.
Getting Input Using BufferedReader

User inputs can be passed to a program by using java’s Reader classes. One
such class is the BufferedReader class.

The BufferedReader class is found in the java.io package.

To use the class and its methods, the following packages must be imported:

- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.IOException;

Program code using BufferedReader:

import java.io.BufferedReader; import


java.io.InputStreamReader; import java.io.IOException;
public class GetKeyboardInput {
public static void main (String [] args ) {
BufferedReader dataIn = new BufferedReader (new
InputStreamReader(System.in));
String name = “”;
System.out.print (“Please enter your name: ”);
- Program code using BufferedReader – cont’d

try {
name = dataIn.readLine();
} catch (IOException e) { System.out.println(“IO
Error”);
}
System.out.println(“Hello ” + name);
}
}

Explanation of Program code:

- Importing the java.io package is necessary to be able to use the classes


in the package: BufferedReader and InputStreamReader. The class
IOException handles IO exceptions or errors that may occur during
runtime.
The statement

BufferedReader dataIn =
new BufferedReader(newInputStreamReader(System.in));

- declares and creates an object dataIn which is of type BufferedReader.dataIn is


“chained” to another object of type InputStreamReader, which, in turn, reads the
standard input device of System.in.

The statement(s)

try {
name = dataIn.readLine();
} catch (IOException e) { System.out.println(“IO
Error”);
}
- The try and catch blocks are necessary in case IO errors occur during program
execution.
In the try block, the statement:

name = dataIn.readLine();

reads a line from the object dataIn (which is connected to the standard input
device, System.in) and stores it in the String name.

- The statement
System.out.println(“Hello ” + name);
prints the String, name.

 Another way to get input from the user is by using the


JOptionPane class which is found in the javax.swing package.

JOptionPane makes it easy to pop up a dialog box that prompts the user for a
value or informs them of something.
Program code using JOptionPane:

import javax.swing.JOptionPane; public class PopUpInput {


public static void main (String [] args ) {
String name = “”;
name = JOptionPane.showInputDialog(“Please enter your
name: ”); String msg = “Hello ” + name + “!”;
JOptionPane.showMessageDialog (null, msg);
}

Explanation of Program code:


The statement
import javax.swing.JOptionPane;
is necessary to be able to use the JOptionPane class
and its methods in the javax.swing package.

• In the statement
name = JOptionPane.showInputDialog(“Please enter your name: ”);
• The showInputDialog method of the JOptionPane class displays a
dialog box with a message, a textfield and an OK button like the one
shown below.
• When the user keys in a value in the textfield, it is
stored in the String variable name.

• The output message is assembled in the statement: String msg = “Hello ” +


name + “!”;

• The statement,

JOptionPane.showMessageDialog (null, msg);


displays a dialog box containing the message and
an OK button.
EXERCISE TIME! NO. 10

Name: _______________________ Strand: __________________


Score: ___________________

TEST I.

Create a program that will compute the average grades.

Subject Midterm Final Average


PROGRAMMING 80 82
MATH 82 83
SCIENCE 77 84
PHILO 81 85
IT FUNDAMENTAL 90 86
FILIPINO 82 85
TEST II.

Determine what gets printed out from the program segments below.

int num = 9;
if (num ! = 9)
{
num = num + 1;
num = num * 2;
}

num = num + 5;
System.out.println(“num is “ + num);

OUTPUT
TEST III

int num = 4;

int numOne = 5;

int numTwo = 8;

if ( numOne < numTwo )

{
num = num * 2;
num = num – 2;
}
else

{
num = num – 2;
num = num * 2;

}
System.out.println(“num is” + num);

OUTPUT
Sources

Department of Information and Communication Technology

https://www.gov.ph/web/department-of-information-and-communications-technology-office

https://www.google.com/search?client=firefox-b-d&q=arrays

https://www.w3schools.com/java/

https://www.cs.cmu.edu/afs/cs.cmu.edu/user/gchen/www/download/java/LearnJava.pdf

Potrebbero piacerti anche