Handout
Handout
Programming languages are essential tools that enable humans to communicate with computers. They serve as a
medium through which programmers can write instructions that a computer can execute. A programming
language consists of a set of rules and syntax that dictate how code is written and structured. These languages
allow developers to create software applications, websites, and systems that perform a wide range of tasks.
A programming language can be defined as a formal language comprising a set of instructions that can be used
to produce various kinds of output, including software applications, algorithms, and data processing. The primary
purpose of a programming language is to facilitate communication between the programmer and the computer,
allowing the programmer to express computational tasks in a way that the computer can understand and execute.
Programming languages can be categorized into three types: machine language, assembly language and high-
level languages
1. Machine Languages. Machine language, also known as machine code, is the lowest-level programming
language that a computer can execute directly. It consists of binary instructions (0s and 1s) specific to a
computer's architecture
Characteristics
2. Assembly Languages. Assembly language is one level above machine language. It uses symbolic codes
(mnemonics) to represent machine code instructions, making it easier for humans to read and write than
machine language
Characteristics:
3. High-Level Languages. These languages are closer to human languages and are designed to be easy to
read and write. Examples include Python, Java, and C#.
Characteristics:
Procedural Programming: This paradigm is based on the concept of procedure calls, where a program is structured
as a sequence of procedures or routines. Languages like C and Pascal are examples of procedural programming
languages.
Object-Oriented Programming (OOP): OOP is centered on the concept of objects, which can contain data and
methods. This paradigm promotes code reusability and modularity. Popular OOP languages include Java, C++,
and Python.
Functional Programming: This paradigm treats computation as the evaluation of mathematical functions and
avoids changing state or mutable data. Languages such as Haskell and Lisp are known for their functional
programming capabilities.
Logic Programming: In this paradigm, programs are expressed in terms of relations, and computation is performed
through logical inference. Prolog is a well-known logic programming language.
Declarative Programming: This paradigm focuses on what the program should accomplish rather than how to
achieve it. SQL is a prominent example of a declarative programming language.
To effectively write and manage code, programmers utilize various tools that enhance productivity and streamline
the development process. These tools can be categorized into several types:
Integrated Development Environments (IDEs): IDEs are comprehensive software applications that provide
developers with tools for writing, testing, and debugging code. Examples include Visual Studio, Eclipse, and
IntelliJ IDEA.
Compilers: A compiler is a tool that translates source code written in a programming language into machine code
that a computer can execute. Examples include GCC for C/C++ and javac for Java.
Debuggers: Debuggers are tools that help programmers identify and fix errors in their code. They allow
developers to step through code execution, inspect variables, and analyze program flow. Examples include GDB
and the debugging tools integrated into IDEs.
Version Control Systems: These systems help developers manage changes to source code over time, allowing for
collaboration and tracking of modifications. Git is one of the most widely used version control systems.
Text Editors: Simple text editors are often used for writing code. While they may lack the features of IDEs, they
are lightweight and can be customized. Examples include Sublime Text and Visual Studio Code.
Language Translators
Language Translators in computing refer to software applications or systems that convert programming
instructions from one language into another, typically into a form that the computer can execute directly. These
translators facilitate communication between humans and computers by bridging the gap between high-level
programming languages (easier for humans) and machine code (understandable by computers).
Types of Language Translators
Language translators can be categorized into three primary types: compilers, interpreters, and assemblers. Each
type serves a unique purpose in the translation process.
Compiler: A compiler translates the entire source code of a programming language into machine code
before execution. This process results in an executable file that can be run independently of the source
code. Java uses a two-step compilation process, where the source code is first compiled into bytecode,
which is then interpreted by the Java Virtual Machine (JVM).
Interpreter: An interpreter translates source code into machine code line-by-line at runtime. This means
that the code is executed immediately, which can be beneficial for debugging and testing. However,
interpreted programs may run slower than compiled ones due to the overhead of translation during
execution.
Assembler: An assembler translates assembly language, a low-level programming language, into machine
code. This process is essential for programming at the hardware level, allowing developers to write
instructions that are closely aligned with the architecture of the computer.
The compilation process in Java involves several key steps that transform Java source code into executable
bytecode. Understanding this process is vital for effective Java programming.
1. Writing Source Code: The programmer writes the Java source code in a text editor or an Integrated
Development Environment (IDE) using the .java file extension.
2. Compilation: The Java compiler (javac) takes the source code and compiles it into bytecode, which is
stored in .class files. This bytecode is platform-independent, allowing it to run on any system with a
compatible JVM.
3. Execution: The Java Virtual Machine (JVM) interprets the bytecode and executes it on the host machine.
The JVM acts as an intermediary, translating bytecode into machine code specific to the underlying
hardware.
Both compilers and interpreters have their advantages and disadvantages, which can influence a programmer's
choice of tools and languages.
Advantages of Compilers:
o Faster execution time since the entire code is translated before execution.
o Optimization opportunities during the compilation process, leading to more efficient machine
code.
o Detection of syntax errors before runtime, allowing for easier debugging.
Advantages of Interpreters:
o Immediate execution of code, which is beneficial for testing and debugging.
o Platform independence, as the same code can run on any system with the appropriate interpreter.
o Flexibility in modifying code on the fly without the need for recompilation.
While compilers and interpreters offer distinct advantages, they also come with certain drawbacks.
Disadvantages of Compilers:
o Longer initial compilation time, which can slow down the development process.
o Less flexibility, as changes to the code require recompilation.
Disadvantages of Interpreters:
o Slower execution time due to line-by-line translation.
o Potential for runtime errors that may not be caught until the code is executed.
In Java development, understanding the role of language translators is essential for effective programming. The
Java compiler and JVM work together to ensure that Java code is executed efficiently and correctly.
Java Compiler (javac): The Java compiler is responsible for converting Java source code into bytecode.
It performs syntax checking and generates .class files that can be executed by the JVM.
Java Virtual Machine (JVM): The JVM interprets the bytecode and executes it on the host machine. It
provides a runtime environment that abstracts the underlying hardware, allowing Java programs to run
on any platform with a compatible JVM.
DATA TYPES
Data types are fundamental to programming as they define the type of data a variable can hold. In Java, data types
are categorized into two main groups: primitive data types and reference data types.
1. Primitive Data Types: These are the basic data types provided by Java. They are predefined by the
language and cannot be further divided into simpler components. There are eight primitive data types:
boolean - Represents a true or false value.
Default value: false
byte - An 8-bit signed integer.
Range: -128 to 127.
Default value: 0
char - Represents a single character (Unicode).
Enclosed in single quotes.
Default value: \u0000 (null character)
short - A 16-bit signed integer.
Range: -32,768 to 32,767.
Default value: 0
int - A 32-bit signed integer.
Range: -2,147,483,648 to 2,147,483,647.
Default value: 0
*Note that integers are typically used for whole numbers unless you need larger or smaller ranges
provided by other types like long or byte.
long - A 64-bit signed integer.
It is used when dealing with very large numbers beyond what int can handle.
float - A floating-point number with precision up to six decimal places.
Range varies but generally between approximately ±3e38.
double - A double-precision floating-point number with precision up to fifteen decimal places.
Range varies but generally between approximately ±1e308.
2. Reference Data Types: These refer to objects and arrays. They are created using classes and can hold
multiple values. Examples include:
String: Represents a sequence of characters.
Arrays: Represents a collection of similar data types.
Classes: User-defined data types that can encapsulate data and methods.
Understanding data types is essential for memory management and performance optimization in Java
programming. Each data type has its own size and range, which can affect the efficiency of the program.
VARIABLES
Variables are containers for storing data values. In Java, a variable must be declared before it can be used.
The declaration includes the data type and the variable name.
dataType variableName;
Initialization. Assigning a value to a variable is known as initialization. This can be done at the time of
declaration or later in the code:
variableName = value;
Example:
Variables can be classified into different types based on their scope and lifetime:
1. Local Variables. Declared within a method and accessible only within that method.
2. Instance Variables. Declared within a class but outside any method, accessible to all methods in the
class.
3. Static Variables. Declared with the static keyword, shared among all instances of a class.
OPERATORS
Operators are special symbols that perform operations on variables and values. Java provides a rich set of
operators, which can be categorized as follows:
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus)
= (Simple assignment)
+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
Operators are essential for performing calculations, making decisions, and controlling the flow of a
program.
PROGRAMMING ERRORS
Errors in programming can be categorized into three main types: syntax errors, runtime errors, and logical
errors.
1. Syntax Errors. These occur when the code violates the grammatical rules of the programming language.
Common examples include missing semicolons, mismatched parentheses, and incorrect variable
declarations. Syntax errors are usually caught by the compiler.
2. Runtime Errors. These occur during the execution of the program. They can be caused by various issues,
such as dividing by zero, accessing an out-of-bounds array index, or using null references. Runtime
errors can lead to program crashes.
3. Logical Errors. These occur when the program runs without crashing, but produces incorrect results.
Logical errors are often the hardest to detect and fix, as they require a thorough understanding of the
program's logic.
To minimize errors, programmers should adopt best practices such as code reviews, debugging techniques,
and thorough testing.
Steps in Programming
Programming is a systematic process that involves several steps to develop a functional software
application. Understanding these steps is crucial for any aspiring programmer, especially in a language like Java.
This section will outline the essential steps in programming, focusing on proper pseudo coding constructs,
algorithms, and flowcharting.
1. Understanding the Problem. Before writing any code, it is vital to understand the problem you are trying to
solve. This involves:
Identifying the requirements of the program.
Understanding the input and output.
Clarifying any constraints or limitations.
2. Planning the Solution. Once the problem is understood, the next step is to plan the solution. This can be done
through:
Pseudocode: Writing a high-level description of the algorithm using plain language.
Flowcharts: Creating a visual representation of the steps involved in the solution.
4. Writing Pseudocode. Pseudocode is an informal way of programming that uses a structured but plain
language to outline the logic of the program. It helps programmers focus on the logic without getting
bogged down by syntax.
4. Developing the Algorithm. An algorithm is a step-by-step procedure for solving a problem. It is essential to
develop a clear and efficient algorithm before coding. The algorithm should include:
5. Flowcharting. Flowcharting is a graphical representation of the algorithm. It uses various shapes to denote
different types of actions or steps in a process.
6. Coding. After planning and designing the solution, the next step is to write the actual code in Java. This involves
translating the pseudocode and algorithm into Java syntax. Key considerations include:
Using proper syntax and structure.
Implementing error handling.
Testing the code for correctness.
7. Testing and Debugging. Testing is a critical step in programming. It involves running the program with various
inputs to ensure it behaves as expected. Debugging is the process of identifying and fixing errors in the code.
Techniques include:
Unit testing individual components.
Integration testing to ensure components work together.
Using debugging tools to trace errors.
8. Documentation. Proper documentation is essential for maintaining and understanding the code in the future.
This includes:
Commenting on code to explain complex logic.
Creating user manuals or guides.
Maintaining a change log for version control.
These three concepts are fundamental tools in programming and software development. They help in planning,
designing, and implementing programs efficiently.
PSEUDOCODE
Pseudocode is a detailed yet readable description of what a program or algorithm should do. It uses natural
language combined with programming-like elements to outline the steps of an algorithm without adhering to any
specific syntax.
It serves as a blueprint for translating logic into actual code in any programming language. Pseudocode is
not executable by computers but helps humans understand the logic behind an algorithm.
Characteristics of Pseudocode
Written in plain English
Hardware and software independent
Easy to modify and translate into actual code
Focuses on logic rather than syntax
Best Practices
Use clear, consistent terminology
Keep statements simple
Include all necessary steps
Use proper indentation for structure
Example
BEGIN
Input radius
Calculate area = π * radius * radius
Calculate circumference = 2 * π * radius
Display area
Display circumference
END
FLOWCHARTS
A flowchart is a visual representation of a process or algorithm using standardized symbols and shapes
connected by arrows to show the sequence of steps.
Flowcharts visually illustrate how different parts of an algorithm interact with each other, making it easier
to understand complex processes at a glance
Best Practices
Maintain consistent symbol sizes
Use clear labels
Keep lines straight and neat
Follow standard flowchart convention
Example:
ALGORITHMS
An algorithm is a well-defined procedure that takes some input and produces output through a series of
computational steps.
It provides instructions on how to solve problems using data structures.
Algorithms serve as recipes for solving computational problems efficiently by specifying exactly what
needs to be done at each step.
The algorithm should include:
Initialization of variables.
Input and output specifications.
Logical steps to achieve the desired outcome
History of JAVA
Java was originally developed by James Gosling at Sun Microsystems and released in 1995. The language
was designed for interactive television, but it was too advanced for the digital cable television industry at the time.
The first public implementation was Java 1.0 in 1995, which allowed applets to be embedded in web browsers.
Java 1.0 (1995): The initial release that introduced the core features of the language.
Java 2 (1998): Introduced the Swing graphical API and the Collections Framework.
Java 5 (2004): Added generics, annotations, enumerated types, and the enhanced for loop.
Java 8 (2014): Introduced lambda expressions and the Stream API, enhancing functional programming
capabilities.
Java 11 (2018): A long-term support release that included several new features and enhancements.
Java's design principles emphasize portability, security, and performance, making it a popular choice for
enterprise-level applications, mobile applications, and web development.
The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to run Java programs.
It is a crucial component of the Java Runtime Environment (JRE) and provides a platform-independent way of
executing Java bytecode.
Java bytecode is an intermediate representation of Java source code that is generated when a Java program
is compiled. This bytecode is a set of instructions specifically designed for the Java Virtual Machine (JVM),
enabling the execution of Java programs across different platforms without modification.
The concept of "Write Once, Run Anywhere" (WORA) is central to Java's design, allowing the same
bytecode to be executed on any device with a compatible JVM, which interprets the bytecode into machine-
specific code at runtime
Loading: The JVM loads class files from the file system or network.
Bytecode Verification: Ensures that the bytecode adheres to the Java language specifications and does not
violate access rights.
Execution: The JVM executes the bytecode using either an interpreter or a Just-In-Time (JIT) compiler.
Memory Management: The JVM manages memory through garbage collection, which automatically
reclaims memory used by objects that are no longer referenced.
The JVM allows Java to achieve its "write once, run anywhere" capability, as it abstracts the underlying
hardware and operating system.
Characteristics of Bytecode
Platform Independence: Bytecode can be executed on any platform that has a compatible JVM.
Efficiency: Bytecode is more compact than source code, making it easier to transmit over networks.
Security: The JVM performs bytecode verification to ensure that the code adheres to Java's security
constraints.
Bytecode serves as a bridge between the high-level Java programming language and the low-level machine
code, allowing for efficient execution and portability.
In Java, an interface is a reference type, similar to a class that can contain only constants, method
signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or
constructors.
Java is a widely-used programming language that is known for its portability, performance, and ease of
use. Understanding the basic syntax and semantics of Java is crucial for any programmer.
1. Java Structure. Every Java program consists of at least one class and one main method. The structure of a
simple Java program is as follows:
Class Declaration. Every piece of code must reside within a class. The class name should start with an uppercase
letter, and the filename must match the class name followed by the .java extension.
2. Statements and Semicolons. Each statement in Java must end with a semicolon (;). For example:
System.out.println("Hello, World!");
3. Curly Braces. Curly braces {} are used to define blocks of code, such as the body of classes and methods. They
denote where a block begins and ends.
4. Case Sensitivity. Java is case-sensitive, meaning that identifiers like myVariable and MyVariable would be
considered different.
5. Comments. These are essential for documenting code. In Java, there are two types of comments:
6. Identifiers. These are names given to classes, methods, variables, etc. They must start with a letter (a-z or A-
Z), underscore (_), or dollar sign ($) and can contain letters, digits (0-9), underscores, or dollar signs.
7. Data Types Java is a statically typed language, meaning that all variables must be declared with a data type.
The primary data types in Java include:
4. Input and Output Statements. Input and output operations are fundamental in programming. In Java, the primary
classes used for input and output are System.out for output and Scanner for input.
Output Statements. The most common way to output data in Java is through the `System.out.println()` method.
This method prints the specified message to the console.
Input Statements. To read input from the user, the Scanner class is used. Here’s how to use it:
import java.util.Scanner;
5. Formatting Output. Java provides the `printf` method for formatted output. This method allows you to format
strings, numbers, and other data types.
6. Variable Declaration and Object Instantiation Understanding how to declare variables and instantiate objects
is fundamental in Java programming.
Variable Declaration. In Java, variables must be declared before they can be used. The syntax for declaring a
variable is:
dataType variableName;
For example:
int age;
String name;
Object Instantiation. To create an object in Java, you use the `new` keyword followed by the class constructor.
For example:
Here’s a complete example that combines variable declaration and object instantiation:
Logic formulation and problem-solving are essential skills that every programmer must develop. This section will
delve into the fundamental concepts of arithmetic expressions, relational expressions and logical expressions.
Understanding these concepts will empower students to write efficient and effective Java programs.
Arithmetic Expressions Arithmetic expressions are the backbone of any programming language, including Java.
They allow programmers to perform mathematical calculations and manipulate numerical data. In Java, arithmetic
expressions can include the following operators:
Example:
sum = a + b; // sum is 15
difference = a - b; // difference is 5
remainder = a % b; // remainder is 0
2. Relational Expressions Relational expressions are used to compare two values. They return a boolean result
(true or false) based on the comparison. In Java, the following relational operators are commonly used:
Example:
(x == y) // False
3. Logical Expressions Logical expressions are used to combine multiple boolean expressions. They are crucial
for controlling the flow of a program. The primary logical operators in Java include:
Selection Structure
Java provides several selection structures that allow developers to control the flow of execution based on
specific conditions. These structures enable decision-making in programs, allowing different actions to be taken
depending on whether certain conditions evaluate to true or false. The primary selection structures in Java include
if, if-else, if-else-if ladder, and switch.
1. If Statement. The simplest form of a conditional statement, the if statement executes a block of code only if a
specified condition is true. If the condition is false, the block is skipped.
Syntax:
if (condition) {
}
condition. This is a boolean expression that can be evaluated to either true or false.
The code within the curly braces {} will only execute if the condition is true.
Example:
if (number > 5) {
In this example, since number (which is 10) is indeed greater than 5, the output will be:
If you change the value of number to a value less than or equal to 5, such as 3, the message will not be printed
because the condition will evaluate to false.
2. If Else Statement. The if-else statement allows for two possible paths: one if the condition is true and another
if it is false. This structure is useful for straightforward binary decisions.
Syntax:
if (condition) {
} else {
Example:
} else {
}
Here, if the score is 60 or higher, "You passed the exam." will be printed; otherwise, "You failed the exam." will
be displayed.
3. If-Else If Statement / If-Else If Ladder. The if-else if construct is used when you need to evaluate multiple
conditions sequentially. It allows you to check a series of conditions and execute the corresponding block of code
for the first condition that evaluates to true. If none of the conditions are true, an optional else block can be
executed.
Syntax
if (condition1) {
// code block for condition1
} else if (condition2) {
// code block for condition2
} else if (condition3) {
// code block for condition3
} else {
// code block if none of the conditions are true
}
Example. Consider the following example that determines the grade based on a numerical score:
In this example, the program checks the value of score against multiple conditions. Since the score is 85,
the output will be "Your grade is: B".
4. Nested If. A nested if statement is an if statement placed inside another if statement. This construct allows
for more complex decision-making by evaluating additional conditions based on the outcome of a previous
condition.
Syntax:
if (condition1) {
// code block for condition1
if (condition2) {
// code block for condition2
}
}
condition1 is evaluated first. If it is true, the program checks condition2.
If both conditions are true, the inner block executes.
Example. Consider the following example that checks if a person is eligible to vote based on their age and
citizenship status.
In this example, the outer if checks if the person is at least 18 years old. If true, the inner if checks if the person
is a citizen. Depending on the values of age and isCitizen, the program will output the appropriate message.
If-Else If: Best used when you have multiple conditions that are independent of each other. It provides a
straightforward way to evaluate conditions in a linear fashion.
Nested If: Useful when you need to evaluate additional conditions based on the outcome of a previous
condition. It allows for more complex decision-making but can lead to less readable code if overused.
5. Switch Statement. The switch statement provides a way to execute one block of code among
many based on the value of a variable. It is particularly useful when checking a single variable
against multiple constants.
Syntax
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
// more cases...
default:
// default code block
}
In Java, the switch statement can test the following types of variables:
*Important Points. The values used in the case statements must be of the same type as the variable being
switched on and must be constants or literals.
*The switch statement cannot be used with boolean expressions or directly with arrays or collections like
ArrayLists.
Example
Here's a simple example demonstrating the use of a switch statement with different types:
In this example:
The first switch uses an integer variable to determine the name of the day.
The second switch uses a string variable to identify the type of fruit.