02 - CSC 202 - Introduction to Java
02 - CSC 202 - Introduction to Java
Programming is the process of creating and designing computer programs. It involves writing a
set of instructions or code in a programming language that a computer can understand and execute
to perform specific tasks or solve particular problems.
1
• Documentation: Good programming includes documenting the code to make it
understandable to other programmers and future maintainers.
• Collaboration: Many software development projects involve teams of programmers who
collaborate on designing, coding, and maintaining complex software systems.
Low-level language is closer to the machine than the human natural language. The two major
examples are Machine and Assembly language.
• Machine Language: This is the only language a computer understands. The computer
directly executes a program written in machine language. Such programs are coded using
strings of 0’s and 1’s. It doesn’t need a translator.
• Assembly Language: uses mnemonics (symbols) to represent data and instructions. Such
a program eliminates problems associated with machine language. A computer cannot
execute directly a program written in assembly language. It requires a translator called
an assembler. Assembler is a special program designed to translate program content in
assembly language to a machine language equivalent.
For computers to read and run a program written in a High-Level Language, the source code must
be converted into machine language using an interpreter or a compiler. Compiling is the process of
converting source code into machine language. It is directly converted into machine code that the
processor can execute. By this, it tends to be faster and more efficient to execute than the
2
interpreted languages. Programming languages that are compiled are C, C++, Haskell, Go, etc.
Other programming languages that do not compile will use Interpreter to read and execute the
code. Interpreters run through programs line by line and execute each command. Interpreters are
significantly slower than compilers, but the development of just-in-time compilation (it compiles to
native code during execution to improve performance) tends to reduce the gap. Such languages
are JavaScript, PHP, Perl, Ruby, etc.
There are programming languages that can both compile as well as interpret. Examples of such
languages are Java, Python, etc.
The programmer will consider the application requirements before deciding on the programming
language to use for development. Some of the programming languages can be used for one kind
of development, while others can be used for more than one kind of development. Some of the
programming languages are:
• Java - used for Desktop software (cross-platform), Game Development, Big data technology,
Embedded Systems, Web Applications, and Mobile development (Android), can equally be
used to create apps for a range of industries, such as banking, electronic trading, e-commerce,
as well as apps for distributed computing.
• Python - can be used to develop different applications and does well in technologies such as
Artificial Intelligence, Machine Learning, Data Analytics, Data Visualization, Game
Development, Back-end web development (with frameworks like Django and Flask), Enterprise
applications and GUIs for applications.
• C – language is used to develop Operating systems and system tools, Game development,
Advanced computation and graphics, Compilers, and Enterprise software.
• C++ is used for Desktop applications and software development, Game engines and games,
system applications, real-time systems, IoT, embedded systems, cloud, containers, etc.
• C# - can be used for game development, Desktop applications (Microsoft, Windows), Web
services and web applications, server-side programming, mobile applications, etc.
• JavaScript - used to develop rich Interactive Web applications (front-end and back-end
development (Node.js)) and Mobile apps with React Native.
• Swift – used for Mobile App Development on iOS. It can be used to create apps for virtually
every Apple device, such as iPhones, iPads, Macs, Watch, and Vision Pro.
3
• Perl - is a high-level scripting language used for Network programming, GUI development,
and Web development.
• PHP - is a server-side scripting language for Back-end web development.
• Ruby - is a high-level, multi-purpose programming language for Back-end web
development.
• COBOL – used for business applications development.
• FORTRAN – designed for scientific computation and organising numbers.
• Modularity and Encapsulation: Break your code into smaller, reusable modules or functions.
Each module should have a specific purpose and well-defined inputs and outputs. Use
encapsulation to hide the internal implementation details of a module or class. Expose only the
necessary interfaces.
• Don't Repeat Yourself (DRY): Avoid duplicating code. Instead, use functions, methods, or
classes to encapsulate common functionality that can be reused throughout your program.
• Keep It Simple, Stupid (KISS): Favour simple, straightforward solutions over complex ones.
Avoid unnecessary complexity and over-engineering.
• Prioritise code clarity and simplicity to reduce the chances of bugs and make maintenance
easier.
• Single Responsibility Principle (SRP): Each function, method, or class should have a single
responsibility or reason to change. This promotes a clear and maintainable codebase.
• Open/Closed Principle (OCP): Code should be open for extension but closed for modification.
You should be able to add new features or functionality without altering existing code.
• Consistency: Be consistent in naming conventions, code structure, and style throughout your
codebase. Use consistent indentation, variable naming, and coding patterns.
4
• Testing and Test-Driven Development (TDD): Write unit tests for your code to ensure it
behaves as expected. Consider using a test-driven development approach, where you write
tests before writing the actual code.
• Error Handling: Implement robust error handling and validation to handle unexpected
situations and provide meaningful error messages.
• Performance Optimization: Optimize code for performance when necessary, but prioritise
readability and maintainability unless performance is critical. Use profiling tools to identify
bottlenecks before optimising code.
• Version Control: Use version control systems (e.g., Git) to track changes, collaborate with
others, and maintain a history of your codebase.
• Security: Be aware of common security vulnerabilities and follow best practices for secure
coding. Validate user inputs, avoid hardcoded secrets, and use secure authentication and
authorisation mechanisms.
5
• Selection is the branching of control flow based on the outcome of a condition. When the
condition is true, the 'if' block is executed; otherwise, the 'else' block is executed. The 'else'
block is optional and can be left out entirely.
• Iteration is the repetition of a block as long as a certain condition is met. The condition is
evaluated at the beginning or end of the block. The loop is terminated when the condition returns
false, and the execution continues in the next block.
• Nesting: is when a piece or block of code is placed inside another. It is used for multi-selection
and iteration.
• Subroutines are small blocks of codes designed to perform a specific task. It can contain
sequence, selection and iteration constructs.
6
creating and using abstract models to design, simulate, and generate code for complex
systems. This approach can be applied to various domains, including software development,
control systems, and embedded systems.
7
INTRODUCTION TO JAVA
What is Java?
Like English, Java has a set of rules that determine how the instructions are written. These rules are
known as its syntax. Once a program has been written, the high-level instructions are translated
into numeric codes that computers can understand and execute.
History of Java
James Gosling and his team Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun
Microsystems in 1991 initiated the Java language project. The language, initially called ‘Oak’ after
an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and later became
Java, from a list of random words.
The name Java came about in 1995 when Gosling and his team went for a cup of coffee, and the
name Java was suggested, and it struck. Java was developed from the rich experiences of the
professionals who came together to design the programming language. Thus, it is an excellent
programming language. It has a similar syntax to C/C++ programming languages but without its
complexities. Java is an elegant programming language.
Sun released the first public implementation as Java 1.0 in 1995. On 13 November, 2006, Sun
released much of Java as free and open-source software under the terms of the GNU General Public
License (GPL). On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the copyright. Java was
acquired by Oracle Corporation from Sun Microsystems in 2010.
Java was initially developed for programming intelligent electronic devices such as TVs, cell
phones, pagers, smart cards, etc. Unfortunately, the expectations of the Suns team in this area did
not develop as they envisaged. With the advent of the Internet and the World Wide Web
(WWW), the team changed their focus, and Java was developed for web-based applications. It
8
is currently being used to develop a variety of applications. Java revolutionised programming,
changing the way we think about a program's form and function.
• Object Oriented: In Java, everything is an object. Java can be easily extended since it is
based on the object model.
• Platform Independent: When Java is compiled, it is not compiled into a platform-specific
machine code, but rather into platform-independent byte code. This byte code is distributed
over the web and interpreted by the Java Virtual Machine (JVM) on whichever platform it runs
on.
• Simple: Java has a concise, cohesive set of features that makes it easy to learn and use.
• Secure: Java provides a secure means of creating Internet applications. Authentication
techniques are based on public-key encryption.
• Architecture-neutral: Java is not tied to a specific machine or Operating system architecture.
Its compiler generates an architecture-neutral object file format, which makes the compiled
code executable on many processors, with the presence of a Java runtime system.
• Portable: Java programs can execute in any environment with a Java run time system.
• Robust: Java makes an effort to eliminate error-prone situations by emphasising mainly
compile-time and runtime error checking.
• Multithreaded: With this feature, it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications
that can run smoothly.
• Interpreted: Java supports cross-platform code through the use of Java bytecode.
• High Performance: Using Just-In-Time compilers, Java enables high performance.
• Distributed: Java is designed for the distributed environment of the internet.
• Dynamic: Java is considered to be more dynamic since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount of run-time information that can
be used to verify and resolve accesses to objects on run-time.
9
Types of Java Programs
The three major Java programs are:
1. Java Stand-Alone Applications – are Java programs developed and executed on a stand-
alone local computer. These applications run directly by the Java interpreter. A standalone
application should be delivered and installed on each computer before it is run. It can have a
Command-Line Interface (CLI) or a Graphical User Interface (GUI). You have already used
many stand-alone applications such as text editors, word processors and games applications.
2. Java Applets: these are the Java applications embedded inside HTML files and can be
downloaded into a Java-capable browser. An applet can perform tasks and interact with
users on their browser's web pages without using resources from the web server after being
downloaded. Using applets, you can do anything ranging from animations to complete games
and utilities that can be executed over the Internet.
3. Java Servlets: are Java programs that run on a web server to generate dynamic web content.
In a web-based application, the client sends a request to a server. The server processes the
request and sends a response back to the client. Servlets are used to process forms. Servlets
can also process databases and perform server-side transactions. Servlets use web servers
for their execution and help generate web pages.
1. Java Standard Edition (Java SE) is the API for developing desktop-based applications. Java
SE comes bundled with the compiler, a runtime environment, and core API.
2. Java Enterprise Edition (Java EE) – is the API to develop web-based enterprise applications.
The applications are accessed on your browser. This package includes an application server,
web server, J2EE APIs, support for Enterprise JavaBeans, Java Servlets API, and Java Server
Pages (JSP) technology.
3. Java Micro Edition (Java ME) – is the API to develop mobile applications and other consumer
devices. This kit provides tools for compiling, deployment and device configuration, and
specialised APIs for each type of device.
4. Java FX – is a platform for developing desktop applications and rich internet applications
using lightweight user-interface API that can run across various devices. Applications written
10
for the Java FX platform can include links to Java programming language classes and may
be clients of Java EE platform services.
The development kits above include the APIs necessary for whatever type of applications you
develop in the Java programming language. Structurally, the Java language starts with packages.
A package is the Java language's namespace mechanism. Within packages are classes, and within
classes are methods, variables, constants, and more.
Now that we have an overview of the Java language let us begin with the technicalities of the
language.
11
instructions on the native hardware platform for which the JVM was written. Your code can run on
any chipset for which a suitable JVM implementation is available. JVMs are available for major
platforms like Linux and Windows, and subsets of the Java language have been implemented in
JVMs for mobile phones.
IntelliJ is a popular IDE for Java development. It is built on the same platform used for Android
Studio and by the same creator. IntelliJ handles basic tasks, such as code compilation and
debugging, so that you can focus on writing and testing code. In addition, you can use IntelliJ to
organise source code files into projects, compile and test those projects, and store project files in
any source repositories.
12
For us to install and use Java programs in this text, we will download the following:
• JDK 8 – Java SE Development Kit
• IntelliJ IDEA IDE
You now have a Java environment on your computer. Next, you'll install the Eclipse IDE.
13
Install Eclipse to Develop Java Programs
To download and install IntelliJ, follow these steps:
• Visit https://www.jetbrains.com/idea/download
• Select your operating system and Click on Download to start the down.
• Save the file to your computer
• Double-click on the file to start the installation.
You now have a Java environment on your computer. Next, you'll install the IntelliJ IDE.
Double on the IntelliJ Icon on your desktop to open the IDE, or click on IntelliJ from the Start menu.
14
Overview of the IntelliJ IDE:
• User Interface:
• Editor: The central area where you write and edit your code. It provides syntax
highlighting, code completion, and numerous code analysis and navigation features.
• Tool Windows: Surrounding the editor, tool windows provide access to features like
Project Explorer, version control, build tools, database tools, and more.
• Menu Bar: Contains menus for accessing various functions and settings.
• Toolbar: Provides quick access to frequently used actions and commands.
• Status Bar: Displays information about the project, version control status, and other
relevant details.
• Editor - The code editor is where you write and edit your code. IntelliJ IDEA offers features
like code completion, code generation, code inspections, refactoring tools, and smart code
analysis to help you write high-quality code.
• Projects - The Project tool window displays the structure of your project, including directories,
files, and modules. You can navigate through your project's components, create new files, and
manage dependencies from here.
• Run - You can run and debug your applications from within the IDE. IntelliJ IDEA provides run
configurations for different project types, making it easy to launch your code and debug any
issues that arise.
15
Figure 2 – Overview of the IntelliJ IDE
From the above program, the source file is named after the public class it contains, appending the
suffix “.java”, that is “Main.java”. It must first be compiled into bytecode using a Java compiler,
producing a file named Main.class. Only then will it be executed or "launched". When you click the
“Run” on the IntelliJ IDE, the program console produces the following result:
16
Brief Explanation of the Program
The first lines /* */ and //start comment statements. Comments are NOT executable and are
ignored by the compiler. But they provide useful explanations and documentation to your readers.
There are two kinds of comments:
Multi-Line Comment: begins with /* and ends with */, and may span more than one line.
Single-Line (Inline) Comment: begins with // and lasts until the end of the current line.
It starts with the access modifier “public” which tells the Java compiler that the class can be accessed
outside the program file it is declared in. A "Main" class is defined via the keyword "class", which
tells Java that it wants to define a class using the name Main. The braces { } enclose the body of
the class. In Java, the name of the source file must be the same as the name of the class with a
mandatory file extension of ".java". Hence, this file MUST be saved as " Main .java".
17
public static void main(String[] args) {
......
}
This is the entry point for program execution. Again, the braces {......} enclose the body of the
method, which contains programming statements. It starts with the access modifier “public” which
shows that the program may be accessed outside the class in which it is declared.
The “static” implies that the method “main()” may be called before an object of the class has been
created. This is necessary since the Java interpreter calls main () before any objects are made.
The “void” tells the compiler that main( ) does not return a value. As you will see, methods may also
return values.
main() starts Java program processing. Any information you need to pass to a method is received
by variables specified within the set of parentheses that follow the name of the method. These
variables are called parameters. If no parameters are required for a given method, you must
include the empty parentheses. In main( ), there is only one parameter, “String[ ] args” which
declares a parameter named “args”. This is an array of objects of the class String. Objects of type
String store character strings. In this case, args receives any command-line arguments present when
the program is executed.
Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to
understand that the Java compiler will compile classes that do not contain a main( ) method. But
the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the
compiler would still compile your program. However, the Java interpreter would report an error
because it would be unable to find the main( ) method.
System.out.println("My First Program!"); will print the string "My First Program!". In
System.out, the system is the predefined class that provide access to the system while the “out” is
the output stream that is connected to the console. The println() (meaning print line) displays the
string which is passed to it. The line ends with a semicolon (;), which shows the line is a statement.
All statements in Java end with semicolon.
18