IT 112 Module 1 SY 2022 2023

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

DAVAO DEL NORTE STATE COLLEGE

INSTITUTE OF
COMPUTING

COMPUTER
PROGRAMMING
1
COURSE MODULE
AY 2022-2023

Prepared by:
JOVITO P. BOLACOY, JR. REIR ERLINDA E. CUTAD, DIT ARIEL O. GAMAO, DIT

GERTRUDE GRACE M. TAMPUS PHILIP JOHN L. PAJA KRES-ANN OCLARIT


THIS MODULE IS A PILOT TEST ONLY; NOT FOR REPRODUCTION AND DISTRIBUTION OUTSIDE
OF ITS INTENDED USE.
THIS IS INTENDED ONLY FOR THE USE OF THE STUDENTS WHO ARE OFFICIALLY ENROLLED IN
THE COURSE/SUBJECT.

©2022
Table of Contents
Module 1: Overview about Computer Program, Programming
Process, and Overview of Java

Lesson 1: Computer Programs, Algorithms, and Flowcharting


Lesson 2: History of Java and Parts of a Java Program

Module 2: Understanding Java Literals, Data Types and Variables

Lesson 1: Java Operators


Lesson 2: Java Literals and Primitive Data Types
Lesson 3: Variables

Module 3: Getting Input from the Keyboard

Lesson 1: Using BufferedReader


Lesson 2: Using JOptionPane
Lesson 3: Using Scanner

Module 4: Control Structures

Lesson 1: Decision Control Structures


Lesson 2: Repetition Control Structures
Lesson 3: Branching Statements

Module 5: Java Arrays

Lesson 1: Introduction to Arrays


Lesson 2: Multi-dimensional Arrays

COMPUTER PROGRAMMING 1
COMPUTER
PROGRAMMING
1

MODULE
1
OVERVIEW ABOUT COMPUTER
PROGRAM, PROGRAMMING
PROCESS, AND OVERVIEW OF JAVA

Prepared by:
JOVITO P. BOLACOY, JR. REIR ERLINDA E. CUTAD, DIT ARIEL O. GAMAO, DIT

GERTRUDE GRACE M. TAMPUS PHILIP JOHN L. PAJA KRES-ANN OCLARIT


THIS MODULE IS A PILOT TEST ONLY; NOT FOR REPRODUCTION AND DISTRIBUTION OUTSIDE
OF ITS INTENDED USE.
THIS IS INTENDED ONLY FOR THE USE OF THE STUDENTS WHO ARE OFFICIALLY ENROLLED IN
THE COURSE/SUBJECT.

©2022
Table of
Contents
Module 1: Overview about Computer Program, Programming
Process, and Overview of Java

Lesson 1: Computer Programs, Algorithms, and Flowcharting


Lesson 2: History of Java and Parts of a Java Program

COMPUTER PROGRAMMING 1
Module 1

Computer Programs,
Algorithms, and Flowcharting

Welcome to Module 1!

Hello! Welcome to our first module. You will be learning about the history
of computer programs, algorithm and flowchart design, Java fundamentals,
and a lot more. Are you ready? Let's go.

Module Outcomes:

At the end of this module, the students will be able to:

·Design a flowchart and an algorithm using appropriate tools and


symbols by following the program development life cycle.
Develop your first Java program using an IDE.

The following are the lessons of this module:

Lesson 1: Computer Programs, Algorithms, and Flowcharting


Lesson 2: History of Java and Parts of a Java Program

COMPUTER PROGRAMMING 1 1
Module 1: Lesson 1

Computer Programs,
Algorithms, and Flowcharting

LEARNING OUTCOMES

At the end of this lesson, the students can be able to:


·Design a flowchart and an algorithm using appropriate tools
and symbols by following the program development life cycle.

INTRODUCTION

Welcome to the first lesson in Module 1!

This lesson discusses the concepts of computer programs,


algorithms, and flowcharts. We will also be able to apply these
concepts in some activities available in this module.

Just to make sure you have a brief understanding of the topic,


we will be having a series of exercises just to keep your hype
up in dwelling about programming and how is it important in
your program.

This lesson will give you a wider view of the importance of


learning the fundamentals of programming. For this lesson,
you will be able to grasp the nature of computer programs, the
application of algorithms, pseudocode, and flowcharts to
illustrate solutions and processes for a given problem.

Are you ready? Let's get started.

COMPUTER PROGRAMMING 1 2
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

ACTIVITY

A process is a series of actions or steps taken in order to achieve a


particular end. for your activity, write a step-by-step process in
making a perfect fried egg. Make sure it should cover all of the
series of important steps. The shorter and the detailed the
process, the better.

Step 1:____________________________________________________________
Step 2:____________________________________________________________
...........:____________________________________________________________
...........:____________________________________________________________
...........:____________________________________________________________
Step (n):____________________________________________________________

ANALYSIS

Based on the activity, can you answer the following:


1. Why do we need to follow a step-step procedure in making
solutions to problems?
2. Why are instructions essential, and when do you need to apply
instructions?
3. Do you think programming needs instructions? Why?

ABSTRACTION

Programming is, quite literally, all around us. From the take-out
we order, to the movies we stream, code enables everyday actions
in our lives. Tech companies are no longer recognizable as just
software companies — instead, they bring food to our door, help
us get a taxi, influence outcomes in presidential elections, or act as
a personal trainer.

COMPUTER PROGRAMMING 1 3
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

A computer system needs hardware and software to run. Hardware is


the tangible and visible component of a computer system such as the
monitor, keyboard, mouse, to name a few. On the other hand, software is
a program that a computer uses to function which is kept in a hardware
device like a hard disk and is intangible.

In addition, programs are instructions for the processors. You need


programs to work with your computer. For example, Microsoft Word is a
word processing program that allows users to create and write documents.
A browser, such as the one you are using to view this page, is a program.

Some Types of Computer Programs

1. System Programs
These are programs that are needed to keep all the hardware and software
systems running together smoothly. Examples are operating systems like
Linux, Windows, Unix, Solaris, and macOS.

2. Application Programs
These are programs that people use to get their work done. Examples are a
word processor, game programs, and spreadsheets.

3. Compilers
Compilers are responsible for translating computer programs into machine
language. Machine language, on the other hand, is the language that the
computer understands.

A programming language is a standardized communication technique for


expressing instructions to a computer. Like human languages, each
language has its syntax and grammar. These instructions are translated
into machine language that can be understood by computers.

COMPUTER PROGRAMMING 1 4
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

Two Categories of Programming Languages

1. High-Level Programming Language


A high-level programming language is more user-friendly, to some extent
platform-independent, and abstract from low-level computer processor
operations such as memory accesses. A programming statement may be
translated into one or several machine instructions by a compiler. This
language looks more like a normal human language.

Advantages:
Much easy to learn and relatively faster to program in.
Statements naturally look like natural English language, including the
mathematical operators.
Allows the programmer to show how the algorithm solves the problem
in a clearer and more straightforward way.

2. Low-Level Programming Language


A low-level programming language has a limited number of programming
constructs, with selection and iteration being performed using compare
and branch instructions. these are much harder to learn, more time-
consuming to code, and difficult to debug.

Once a program has been translated into binary, it is referred to as a


machine code. To write a code at the processor level, we can use
assembly language that is specific to a processor architecture or family of
processors. The assembly code is written using mnemonics, abbreviated
text commands such as LDA (LOAD), STO (STORE), and ADD.

Machine code is stored in binary and looks a little like this:


001000010 101100101 01001101 01011101 00100010 00010101 11010100

Assembly language is slightly more user-friendly but is still too technical


for most people to understand and only specialist programmers can work
using it.

COMPUTER PROGRAMMING 1 5
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

The machine code we looked at previously could be converted to assembly


language as follows:
LDA181 ADD93 LDA21 STO185

It is still not very user-friendly, but it is better than working directly with
machine code. However, a CPU (processor) CAN ONLY understand
machine code so anything is written in assembly language still needs to be
translated into machine code for this to work. This is quite a fast process as
there is a direct translation that can occur between the instruction and the
address number.

Machine code is the code executed by the CPU and consists only of binary
digits 0's and 1's. Each type of processor has its own machine code
instruction set, and all programs no matter if they are written in high-level
or assembly languages will have to be translated into machine code
before being executed.

Advantages:
Assembly language is often used in embedded systems such as systems
that control a washing machine, traffic lights, or a robot.
It has features that make it suitable for the following types of
applications:
It gives complete control to the programmer over the system
components, so it can be used to control and manipulate specific
hardware components.
It has very efficient code that can be written for a particular
processor architecture, so will occupy less memory and execute
(run) faster than a compiled/interpreted high-level language.

COMPUTER PROGRAMMING 1 6
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

The terms high-level and low-level are inherently relative; it means that not
all high-level programming languages today will still be high-level shortly.

Overview of the History of Computers

Here is a table that represents the history of computers:

Year Description

The first device known to carry out calculations was the abacus. It
was invented in Asia but was used in ancient Babylon, China, and
Late Middle Ages
throughout Europe until the late middle ages. The abacus uses a
system of sliding beads on a rack for addition and subtraction.

Pascaline was a calculating device invented by Blaise Pascal, a


French philosopher and a mathematician. It had eight movable
1642 dials on wheels that could calculate sums up to eight figures long.
It can only perform addition and subtraction operations like
abacus.

Gottfried von Leibniz invented a device that was able to add,


17th century
subtract, multiple, and divide.

Joseph Jacquard, a French weaver, discovered that the weaving


instructions for his looms could be stored on needles passed
through holes and picked up threads of the correct color and
1819
texture. The idea of storing information by punching holes on a
card turned out to be of great importance in the later development
of computers.

Charles Babbages, an English mathematician and physical scientist,


designed two calculating machines- the difference engine and
analytical engine. The difference engine could automatically
perform complex operations, such as squaring numbers. The first
early and mid-1800s complete difference engine was completed in 2008 and is on
display at the Computer History Museum in Mountain View,
Californina. Most of Babbage's work is known through the writings
of his colleague, Ada Augusta, Countess of Lovelace. Augusta us
considered to be the first computer programmer.

US Census officials needed help in accurately tabulating the census


data. Herman Hollerith invented a calculating machine that ran on
end of the 19th century electricity and used punched cards to store data. Hollerith founded
the Tabulating Machine Company, which later became known as
IBM.

COMPUTER PROGRAMMING 1 7
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

The first computer-like machine was the Mark I. It was built by IBM
and Harvard University under the leadership of Howard Aiken.
1944
Punched cards were used to feed data into the machine. Mark I
was 52 feet long, weighed 50 tons, and had 750, 000 parts.

The ENIAC (Electronic Numerical Integrator and Calculator) was


1946 built at the University of Pennsylvania. It contained 18, 000 vacuum
tubes and weighed some 30 tons.

The computers that we know today use the design rules given by
John von Neumann. His design included components such as
late 1940s arithmetic logic unit, control unit, memory, and input/output
devices. Neumann's design makes it possible to store the
programming instruction and the data in the same memory space.

The UNIVAC (Universal Automatic Computer) was built and sold to


1951
the US Census Bureau.

Invention of smaller, faster, more reliable, and more energy-


efficient computer transistors. This era also saw the emergence of
the software development industry with the introduction of
FORTRAN and COBOL, two early programming languages. Later on,
1956
transistors were replaced by tiny integrated circuits or chips that
are smaller and cheaper than transistors and can contain
thousands of circuits on a single chip. They give computers
tremendous processing speed.

1970 Microprocessors was invented. It is an entire CPU on a single chip.

Stephen Wozniak and Steven Jobs designed and built the first
1977
Apple computer in the garage.

1981 IBM introduced its personal computer (PC).

Clones of the IBM PC made the personal computer even more


1980s
affordable.

People from many walks of life were able to afford computers. As


mid-1990s until today of today, modern-day computers are very powerful, reliable and
easy to use. It also has advanced features.

COMPUTER PROGRAMMING 1 7
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

THE PROGRAM DEVELOPMENT LIFE CYCLE

In programming, we follow the Program Development Life Cycle in


solving real-world problems. It is needed to examine the step-by-step
procedure and to ensure the efficiency of the solution. It contains the
following phases:
1. Problem Definition
2. Problem Analysis
3. Algorithm design and representation (pseudocode or flowchart)
4. Coding and debugging

Programming, in general, is a process of problem solving.

Step 1: Problem Definition


A problem definition is a clearly defined problem that is already half the
solution. In computer programming, it requires us to describe the problem
first before we even try to create a solution.

Example: Create a program that will determine the number of times a


name occurs in a list

Step 2: Problem Analysis


After the problem has been adequately defined, the simplest and yet the
most efficient and effective approach to solving the problem must be
formulated. Usually, this step involves breaking up the problem into
smaller and simpler subproblems.

Example Problem: – Determine the number of times a name occurs in a list

Input to the program:


list of names (let's call this nameList)
name to look for (let's call this keyName)

The output of the program:


the number of times the name occurs in a list

COMPUTER PROGRAMMING 1 7
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

Step 3: Algorithm Design and Representation

An algorithm is a clear and unambiguous specification of the steps needed


to solve a problem in a finite amount of time. It may be expressed in either:

1. Human language (English, Tagalog)


2. Graphical representation like a flowchart
3. Pseudocode – it is a cross between human language and a programming
language. It is an artificial and informal language that helps programmers
develop algorithms. The pseudocode is very similar to everyday English.

Expressing our solution through human language:


1. Get the list of names, let's call this nameList
2. Get the name to look for, let's call this the keyname
3. Compare the keyname to each of the names in nameList
4. If the keyname is the same as a name in the list, add 1 to the count
5. If all the names have been compared, output the result

Expressing our solution through a pseudocode:


1. Get nameList.
2. Get keyname.
3. Set count=0.
4. Compare keyname to nameList.
5. If keyname = name in nameList, then count + 1
6. Else, display count.

COMPUTER PROGRAMMING 1 8
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

Expressing our solution through a flowchart:

Flowchart

In the dictionary definition, a flowchart is a schematic representation of a


sequence of operations, as in a manufacturing process or computer
program. Technically, a flowchart is a graphical representation of the
sequence of operations in an information system or program. Information
system flowcharts show how data flows from source documents through
the computer to final distribution to users. Program flowcharts show the
sequence of instructions in a single program or subroutine. Different
symbols are used to draw each type of flowchart.

A flowchart shows the:


shows the logic of an algorithm
emphasizes individual steps and their interconnections (e.g. control
flow from one action to the next)

COMPUTER PROGRAMMING 1 9
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

Flowchart Symbols and Representation

Note: These are just guidelines for commonly used symbols in creating flowcharts. There are more
flowchart symbols, and you can use any symbols in creating your flowcharts as long as you are
consistent in using them.

Step 4: Coding and Debugging


After constructing the algorithm, it is now possible to create the source
code. Using the algorithm as a basis, the source code can now be written
using the chosen programming language.

Debugging
Debugging is the process of fixing some errors (bugs) in your program.

The terms "bug" and "debugging" are popularly attributed to Admiral


Grace Hopper in the 1940s. While she was working on a Mark II computer
at Harvard University, her associates discovered a moth stuck in a relay
and thereby impeding operation, whereupon she remarked that they were
"debugging" the system.
COMPUTER PROGRAMMING 1 10
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

EXAMPLE PROBLEM 1:
Write an algorithm to find the area of a rectangle.

Pseudocode: Flowchart:
Step 1: Start
Step 2: Get l, b values
Step 3: Calculate A=l*b
Step 4: Display A
Step 5: Stop

EXAMPLE PROBLEM 2:
Write an algorithm for calculating the simple interest of an amount.

Pseudocode: Flowchart:
Step 1: Start
Step 2: Get P, n, r value
Step 3: Calculate SI=(p*n*r)/100
Step 4: Display SI
Step 5: Stop

EXAMPLE PROBLEM 3:
Write an algorithm that will determine if a number is positive or
negative.

Pseudocode: Flowchart:
Step 1: Start
Step 2: Get num
Step 3: Check if(num>0), print "Num is positive."
Step 4: Else, display "Num is negative."
Step 5: Stop

COMPUTER PROGRAMMING 1 11
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

TYPES OF ERRORS

1. Compile-time error or syntax errors


A syntax error occurs if there is a syntax error in the code. The compiler
will detect the error, and the program will not compile. At this point, the
programmer is unable to form an executable program that a user can run
until the error is fixed.

2. Runtime Errors
Compilers are not perfect, and so they cannot 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.

COMPUTER PROGRAMMING 1 12
Module 1: Lesson 1 - Computer Programs, Algorithms, and Flowcharting

APPLICATION

Write an algorithm (pseudocode and flowchart) for the problem


below:
1. Suppose that the cost of sending an international fax is
calculated as follows: Service charges ₱3.00, ₱0.20 per page for
the first ten pages, and ₱0.10 for each additional page. Design
an algorithm (pseudocode) that asks the user to enter the
number of pages to be faxed. The algorithm then uses the
number of pages to be faxed to calculate the amount due.
2. A mobile phone app allows a user to press a button that starts
a timer that counts seconds. When the user presses the button
again, the timer stops. Write pseudocode that accepts the
elapsed time in seconds and displays the value in minutes and
seconds. For example, if the elapsed time was 130 seconds,
the output would be 2 minutes and 10 seconds.

You can refer to the example problems at the top on how to


answer the application. Use appropriate symbols and terms.

CLOSURE:
Great job! You have finished Lesson 1 of this module. Now, you
are already prepared to move to Lesson 2 of this module.
Congratulations!
COMPUTER PROGRAMMING 1 13
Module 1: Lesson 2
History of Java and Elements of a
Java Program
LEARNING OUTCOMES

Distinguish the different types of operators and their usage;


Discuss the history of Java and the groups of Java operators;
Differentiate Java operators: Arithmetic, Relational, Bitwise,
Boolean, and Assignment.

INTRODUCTION

Before digging deeper into the world of programming, we need


to understand the history of Java, how it started, and the
reason behind it.
We will also get to know the basic parts of a Java program and
would be able to run it using our IDE.
In this lesson, you will learn about all of them. So, let’s get
started!

ACTIVITY

Answer the following questions:


1. Which is the better tool for learning programming—
flowcharts or pseudocode? Cite any educational research
you can find.
2. What should be the first programming language a future
programmer should study? Why?

COMPUTER PROGRAMMING 1 14
Module 1: Lesson 2 - History of Java and Parts of a Java Program

ANALYSIS

1. What is the importance of a programming language in our day-


to-day life?
2. What program do you want to develop once you master
programming?
3. Do you see yourself as a future programmer? Why or why not?

ABSTRACTION

HISTORY OF JAVA

Java was created in 1991 by James Gosling, et.al of Sun


Microsystems. Initially called Oak, in honor of the tree outside
Gosling's window, its name was changed to Java because there
was already a language called Oak.

The original motivation for Java is the need for platform-


independent language that could be embedded in various
consumer electronic products like toasters and refrigerators.

One of the first projects developed using Java was a personal


hand-held remote control named Star 7. At about the same time,
the World Wide Web and the Internet were gaining popularity.
Gosling et. al. realized that Java could be used for Internet
programming.

COMPUTER PROGRAMMING 1 15
Module 1: Lesson 2 - History of Java and Parts of a Java Program

While Java is viewed as a programming language to design applications for the


Internet, it is, in reality, a general all-purpose language that can be used
independently of the Internet.

Uses of Java

Here are some important Java applications:


It is used for developing Android Apps
Helps you to create Enterprise Software
Wide range of Mobile java Applications
Scientific Computing Applications
Use for Big Data Analytics
Java Programming of Hardware devices
Used for Server-Side Technologies like Apache, JBoss, GlassFish, etc.

Java Versions and Release Dates

COMPUTER PROGRAMMING 1 16
Module 1: Lesson 2 - History of Java and Parts of a Java Program

Components Of Java Programming Language

A Java Programmer writes a program in a human-readable language called


source code. Therefore, the CPU or chips never understand the source code
written in any programming language.

These computers or chips understand only one thing, which is called machine
language or code. These machine codes run at the CPU level. Therefore, it
would be different machine codes for other models of CPU.

However, you need to worry about the machine code, as programming is all
about the source code. The machine understands this source code and
translates them into machine understandable code, which is an executable
code.

All these functionalities happen inside the following 3 Java platform


components:
1. Java Development Kit (JDK)
2. Java Virtual Machine (JVM)
3. Java Runtime Environment (JRE)

Java Development Kit (JDK)


JDK is a software development environment used for making applets and Java
applications. The full form of JDK is Java Development Kit. Java developers can
use it on Windows, macOS, Solaris, and Linux. JDK helps them to code and run
Java programs. It is possible to install more than one JDK version on the same
computer.
Why use JDK?

Here are the main reasons for using JDK:


JDK contains tools required to write Java programs and JRE to execute
them.
It includes a compiler, Java application launcher, Appletviewer, etc.
Compiler converts code written in Java into byte code.
Java application launcher opens a JRE, loads the necessary class, and
executes its main method.

COMPUTER PROGRAMMING 1 17
Module 1: Lesson 2 - History of Java and Parts of a Java Program

Java Virtual Machine (JVM):


Java Virtual Machine (JVM) is an engine that provides a runtime environment to
drive the Java Code or applications. It converts Java bytecode into machine
language. JVM is a part of the Java Run Environment (JRE). In other
programming languages, the compiler produces machine code for a particular
system. However, the Java compiler produces code for a Virtual Machine
known as Java Virtual Machine.

Why JVM?
Here are the important reasons of using JVM:
JVM provides a platform-independent way of executing Java source code.
It has numerous libraries, tools, and frameworks.
Once you run a Java program, you can run on any platform and save lots of
time.
JVM comes with JIT (Just-in-Time) compiler that converts Java source code
into low-level machine language. Hence, it runs faster than a regular
application.

Java Runtime Environment (JRE)


JRE is a piece of software that is designed to run other software. It contains the
class libraries, loader class, and JVM. In simple terms, if you want to run a Java
program, you need JRE. If you are not a programmer, you don't need to install
JDK, but just JRE to run Java programs.

Why use JRE?


Here are the main reasons of using JRE:
JRE contains class libraries, JVM, and other supporting files. It does not
include any tool for Java development like a debugger, compiler, etc.
It uses important package classes like math, swing, util, lang, awt, and
runtime libraries.
If you have to run Java applets, then JRE must be installed in your system.

COMPUTER PROGRAMMING 1 18
Module 1: Lesson 2 - History of Java and Parts of a Java Program

Different Types of Java Platforms


There are four different types of Java programing language platforms:
1. Java Platform, Standard Edition (Java SE):
Java SE's API offers the Java programming language's core functionality. It
defines all the basis of types and objects to high-level classes. It is used for
networking, security, database access, graphical user interface (GUI)
development, and XML parsing.

2. Java Platform, Enterprise Edition (Java EE):


The Java EE platform offers an API and runtime environment for developing
and running highly scalable, large-scale, multi-tiered, reliable, and secure
network applications.

3. Java Programming Language Platform, Micro Edition (Java ME):


The Java ME platform offers an API and a small-footprint virtual machine
running Java programming language applications on small devices, like mobile
phones.

4. Java FX:
JavaFX is a platform for developing rich internet applications using a
lightweight user-interface API. It user hardware-accelerated graphics and
media engines that help Java take advantage of higher-performance clients
and a modern look-and-feel and high-level APIs for connecting to networked
data sources.

Phases of a Java Program

COMPUTER PROGRAMMING 1 19
Module 1: Lesson 2 - History of Java and Parts of a Java Program

JAVA PROGRAM STRUCTURE


It is necessary to know the exact structure of the Java program, and this lesson
contains a detailed description of it. This lesson is essential for you before
proceeding to learn more advanced lessons of Java programming. Here, in this
chapter, you will study the structure of the Java program. Such as how to create a
simple Java program and what its different sections mean. Java program structure
means - the way to write a java program or general format.

Basic Structure of Java Programs


A Java program involves the following sections:
Package Statement
Import Statements
Class Definition
Main Method Class
Main Method Definition

COMPUTER PROGRAMMING 1 20
Module 1: Lesson 2 - History of Java and Parts of a Java Program

A Simple Java Program

Let's take a look at this example:

You have to keep in mind that, Java code is case sensitive. To write a Java
program, you must have to define class first. The name of the class in Java
(which holds the main method) is the name of the Java program, and the same
name will be given in the filename. As mentioned above in the sample program;
The name of the class is "Hello" which the main method is, then this file will be
named "Hello.java".

public class Hello This creates a class called Hello.


All class names must start with a capital letter.

{} Two curly brackets {...} are used to group all the


commands, so it is known that the commands belong
to that class or method. We call it code block.

/*This is The compiler ignores the comment block. Comment


a comment.*/ can be used anywhere in the program to add info
about the program or code block, which will be helpful
for developers to understand the existing code in the
future easily.
This is a C-Style comment or a multiline comment.

public static void When the main method is declared public, it means
that it can also be used by code outside of its class, due
to which the main method is declared public.
The word static is used when we want to access a
method without creating its object, as we call the main
method, before creating any class objects.
The word void indicates that a method does not return
a value. main() is declared as void because it does not
return a value.

COMPUTER PROGRAMMING 1 21
Module 1: Lesson 2 - History of Java and Parts of a Java Program

main() main is a method; this is a starting point of a Java


program.
You will notice that the main method code has been
moved to some spaces left. It is called indentation
which is used to make a program easier to read and
understand.

//This is a This is another comment and does not affect the flow
comment. of the program.
C++ Style comments start with // and all the text after
// are treated as comments.

String[] args It is an array where each element of it is a string, which


has been named as "args". If your Java program is run
through the console, you can pass the input parameter,
and main() method takes it as input.

Statements contain one or more lines of code


System.out.println
terminated by a semicolon.
("Hello Java");
This statement is used to print text on the screen as
output, where the system is a predefined class, and out
is an object of the PrintWriter class defined in the
system. The method println prints the text on the
screen with a new line. You can also use the print()
method instead of println() method. All Java statement
ends with a semicolon.

Java Identifiers
Java identifiers are tokens that represent names of variables, methods, classes,
etc. These are case-sensitive which means that the identifier Hello is not the
same as hello.

Identifiers must begin with either a letter, an underscore “_”, or a dollar sign
“$”. Letters may be lower or upper case. Subsequent characters may use
numbers 0 to 9.

Identifiers cannot use Java keywords like class, public, void, etc. We will
discuss more Java keywords later.

Examples: Hello, main, System, out

COMPUTER PROGRAMMING 1 22
Module 1: Lesson 2 - History of Java and Parts of a Java Program

Java Keywords
Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code. These are predefined words by Java so they cannot be
used as a variable or object name or class name.

List of Java Reserved Keywords

abstract assert boolean break byte case catch


char class continue default do double
else enum extends final finally float for
if implements import instanceof int interface long
native new null package private protected
public return short strictfp super switch
synchronized this throw throws transient try
void volatile while

Java Escape Characters


A character preceded by a backslash (\) is an escape sequence and has a special
meaning to the compiler.

The following table shows the Java escape sequences.

Let us take a look at this example:

The output of the program is:

COMPUTER PROGRAMMING 1 23
Module 1: Lesson 2 - History of Java and Parts of a Java Program

Netbeans IDE
Netbeans IDE started as a student project known as Xelfi in the past, is a popular
IDE developed with the goal to create a Delphi-like IDE for Java. First developed in
1996, it has grown into a full-fledged IDE for Enterprise scaled software
development. With its excellent integrated abilities like the connection manager,
integrated Glassfish server, and resource managers, Netbeans IDE makes
development quite easy for novice developers. This article has been created with
the goal to guide every developer on how to make the most out of Netbeans IDE
and its features.

An integrated development environment (IDE) is software for building


applications that combines common developer tools into a single graphical user
interface (GUI).

IDEs increase programmer productivity by combining common activities of


writing software into a single application: editing source code, building
executables, and debugging.

An IDE that knows the syntax of your language can provide visual cues. Keywords,
words that have special meaning like a class in Java, are highlighted with different
colors.

The biggest benefit to using an IDE is that it allows you to code and run Java
programs on your own computer.

Creating Your First Project in Netbeans IDE

1.Let us start with the creation of the first project. To start with the first
project, either navigate to File -> New Project or simply press the New Project
button as described above. It should open up a small window as shown below.

COMPUTER PROGRAMMING 1 24
Module 1: Lesson 2 - History of Java and Parts of a Java Program

2. Select Java application in the right-side panel and click Next.


The next step asks for the selection of project name, location, and folder. Select
the necessary details and click next. The below image shows these details filled in.

With on click of Finish, you should be able to see that your main class is
automatically created. The project shows up in the Projects window and the
MainClass shows up in the editor. A snapshot of how it appears is shown below.

3. Build the project.


Once the code is ready, the next step is to build and execute the project. In the
top bar, you would be able to see two buttons to build the project. The buttons
are Build and Clean & Build respectively. To explain the purpose of both the
buttons, one needs to have a basic understanding of what happens when a
project is built.
Build: F11
Clean & Build: Shift+F11

COMPUTER PROGRAMMING 1 25
Module 1: Lesson 2 - History of Java and Parts of a Java Program

APPLICATION

Write a Java program that has a class name, MyFirstJavaProgram. You


need to display the following:

Your full name


Age
Address
School Graduated
No. of siblings
Name of siblings
Motto in life

CLOSURE:
Congratulations, in completing this lesson, you may now proceed
to Module Assessment!

COMPUTER PROGRAMMING 1 26
Module
Assessment
Create a Java program that has a class name, Module1Assessment_LastName.
Display the following information by following the given form below. In your code,
you need to add the necessary information and display your output with clarity
and organization of content.

COMPUTER PROGRAMMING 1 27
Module
Summary
For a program to work properly, you must develop correct
logic. Logical errors are much more difficult to locate than
syntax errors.
Developing a program involves problem definition, problem
analysis, algorithm design, and representation (pseudocode or
flowchart), and coding and debugging.
Java was developed by James Gosling with his team in Sun
Microsystems in 1991.
Java is a multi-platform, object-oriented, and network-centric
programming language Java is a general-purpose, class-based,
object-oriented programming language.
Java Platform is a collection of programs that help
programmers to develop and run Java applications efficiently.
Meaning of Java: Java is a multi-platform and network-centric
programming language.
It is mainly used for developing Android Apps and Enterprise
Software.
2009, Oracle Corporation acquired Sun Microsystems and took
ownership of three key Sun software assets: Java, Solaris, and
MySQL.
The best feature of the Java is that it is one of the easiest
programming languages to learn.
Four types of Java Programming language platforms are: 1)
Java Platform, Standard Edition (Java SE) 2) Java Platform,
Enterprise Edition (Java EE) 3) Java Platform, Micro Edition (Java
ME) 4) JavaFX
A computer is an electronic device capable of performing
computations.
The computer only understands electronic signals or binary
signals.
Assembler is an advanced technology that converts source
core to corresponding machine code (110001..) and feeds to
your processor.
COMPUTER PROGRAMMING 1 28
REFERENCES
Farrel, J. (2015). Programming logic and design introductory (8th
ed.). Andover: Cengage Learning.
Goswami. (2016). Computer fundamentals and programming.
Andover: Cengage Learning
Sun Microsystems, Inc. (2015). JEDI introduction to programming
[PDF file]. Retrieved from
https://edu.netbeans.org/contrib/jedi/Intro-to-
Programming1/student-manual.pdf
Pomperada, J.R. (2016). Introduction to java programming.
Hoboken, New Jersey: Wiley

COMPUTER PROGRAMMING 1 29

You might also like