0% found this document useful (0 votes)
2 views

CSC 2301_201 Computer Programming I

Computer programming involves designing, writing, testing, and maintaining source code to instruct computers in various tasks. It encompasses key components like variables, control structures, and functions, and is vital for problem-solving across multiple domains. The evolution of programming languages has led to high-level languages that enhance readability and efficiency, with paradigms such as imperative, object-oriented, and functional programming shaping the approach to coding.

Uploaded by

Anasmuhammad1010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CSC 2301_201 Computer Programming I

Computer programming involves designing, writing, testing, and maintaining source code to instruct computers in various tasks. It encompasses key components like variables, control structures, and functions, and is vital for problem-solving across multiple domains. The evolution of programming languages has led to high-level languages that enhance readability and efficiency, with paradigms such as imperative, object-oriented, and functional programming shaping the approach to coding.

Uploaded by

Anasmuhammad1010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Overview of Computer Programming

Computer programming is the art and science of designing, writing, testing, and
maintaining source code for computer systems. It involves instructing a computer
to perform specific tasks by providing it with a set of instructions in a
programming language. These instructions are then translated into machine code
that the computer can execute. Programming is the backbone of software
development, enabling the creation of applications, websites, games, and various
other digital solutions.
Components of Computer Programming
i. Variables and Data Types:
Variables: These are placeholders for storing data values. For example, in
a simple program, a variable named ‘age’ could store an individual's age.
Data Types: These define the type of data a variable can hold, such as
integers, floating-point numbers, strings, etc.
ii. Control Structures:
Conditional Statements: Allow the programme to make decisions based on
certain conditions, like if-else statements.
Loops: Enable the repetition of a set of instructions until a specific
condition is met.
iii. Functions and Procedures:
Functions: Segments of code designed to perform a specific task, often
reusable throughout a programme.
Procedures: Similar to functions but do not return a value.
iv. Arrays and Collections:
Arrays: Collections of variables of the same type, accessed using an index.
Collections: More dynamic structures that can store multiple elements of
different types.
Importance of Programming in Problem-Solving
Programming is a powerful tool for problem-solving in various domains. It allows
individuals to break down complex problems into manageable tasks and develop
step-by-step solutions. The key benefits of programming in problem-solving
include:
i. Algorithmic Thinking: Programming encourages the development of
algorithms, step-by-step procedures for solving problems. This systematic
approach is crucial in problem-solving.
ii. Automation and Efficiency: Through programming, repetitive and time-
consuming tasks can be automated, increasing efficiency and reducing the
likelihood of errors.
iii. Innovation and Creativity: Programming empowers individuals to create
new solutions, whether it's developing innovative software applications,
optimising business processes, or inventing new technologies.
iv. Critical Thinking: Programmers must think critically to identify and fix
errors in their code. This analytical mindset extends to problem-solving in
various aspects of life.
v. Interdisciplinary Applications: Programming is not limited to computer
science; it is used in diverse fields such as finance, biology, physics, and
more.
Brief History and Evolution of Programming Languages
The evolution of programming languages has been a fascinating journey, driven
by the need for more efficient and user-friendly ways to communicate with
computers.
Historical Milestones:
i. Early Programming Languages
Machine Code: Early computers were programmed using this lowest-level
programming language, consisting of binary code that directly
corresponded to the machine's architecture. Each instruction was
represented by a series of 0s and 1s.
Assembly Language: To make programming more manageable, assembly
languages were developed. They used mnemonics and symbols to
represent machine code instructions, making it easier for programmers to
write and understand code.
ii. High-Level Programming Languages
Fortran (1957): Developed by IBM, Fortran was initially created for
scientific and engineering calculations. It introduced high-level constructs
like loops, conditional statements and subroutines, making it easier for
programmers to express complex mathematical computations.
COBOL (1959): COBOL was designed for business applications,
emphasising readability and ease of use. It played a significant role in data
processing and business-oriented software development.
C (1972): Created by Dennis Ritchie at Bell Labs, C became a powerful
and efficient language for system programming. It provided low-level
access to memory and hardware, making it suitable for operating systems
and embedded systems. C, with its simple syntax and powerful features,
became a foundational language for systems programming.
iii. Object-Oriented Languages
C++ (1983): Bjarne Stroustrup developed C++ as an extension of C,
introducing object-oriented programming concepts. It allowed for the
creation of classes and objects, facilitating code organisation and reuse.
Java (1995): Java aimed to solve the “write once, run anywhere” problem.
It introduced the concept of platform-independent bytecode, making it
possible to execute Java programmes on any device with a Java Virtual
Machine (JVM).
Python (1991): Guido van Rossum designed Python with a focus on
readability and simplicity. Its versatile nature and support for multiple
programming paradigms, including procedural and object-oriented,
contributed to its popularity. Python has become popular in web
development, data science, and artificial intelligence.
iv. Modern Trends
Rust (2010): Developed by Mozilla, Rust focuses on system programming
with an emphasis on memory safety, zero-cost abstractions, and
concurrency without data races. It aims to provide the performance of low-
level languages while preventing common programming errors.
Kotlin (2011): JetBrains developed Kotlin as a modern, expressive
language that runs on the Java Virtual Machine (JVM). It is interoperable
with Java, making it an excellent choice for Android app development.
Swift (2014): Apple introduced Swift as a replacement for Objective-C in
iOS and macOS development. It is designed to be more concise, safe, and
modern, with features that enhance developer productivity.
Programming Languages
Programming languages serve as crucial intermediaries between humans and
computers, facilitating the translation of human-readable instructions into
machine-executable code. Programming languages have evolved through various
stages. These include machine language, assembly language, and high-level
language.
Machine Language
Machine language is the lowest-level programming language, consisting of
binary code that directly communicates with a computer's central processing unit
(CPU). Each instruction is represented by a unique combination of 0s and 1s.
Example: Machine Language Programme
The 8086 Machine language programme for var1 = var2 + var3 is as follows:
1010 0001 0000 0000 0000 0000 0000
0011 0000 0110 0000 0000 0000 0010
1010 0011 0000 0000 0000 0000
Characteristics:
i. Binary Representation: Machine language instructions are represented in
binary, reflecting the low-level operations understood by the computer's
hardware.
ii. Processor Specific: Programmes written in machine language are tied to
the architecture of a specific processor, making them non-portable between
different types of CPUs.
iii. Difficult for Humans: Writing programmes in machine language is
extremely challenging for humans due to its complex and error-prone
nature.
iv. Direct Execution: Machine code is executed directly by the CPU, making
it the most efficient in terms of execution speed.
Assembly Language
Assembly language is a low-level programming language that provides a
symbolic representation of machine code. It uses mnemonics and symbols to
represent machine instructions, making it more readable than machine language.

Characteristics:
i. Symbolic Representation: Assembly language uses symbols and
mnemonics to represent machine instructions, making it easier for
programmers to read and write.
ii. One-to-One Correspondence: Each assembly language instruction
typically corresponds to a single machine language instruction.
iii. Processor-Specific: Like machine language, assembly language is
processor-specific, as different processors have different instruction sets.
iv. Direct Interaction with Hardware: Assembly language allows direct
interaction with hardware components, making it suitable for tasks that
require precise control over hardware resources.
High-Level Language
High-level programming languages are designed to be closer to human language,
making them more readable and easier to write. They are independent of the
underlying hardware and provide a level of abstraction from machine-specific
details.
Characteristics:
i. Abstraction: High-level languages abstract away the low-level details of
the hardware, allowing programmers to focus on the logic of their
programmes.
ii. Portability: Programmes written in high-level languages are generally
portable across different platforms, as they are not tied to the specifics of
the underlying hardware.
iii. Readability and Writability: High-level languages are designed to be
readable and writable, making it easier for programmers to understand and
express complex ideas in a more natural syntax.
iv. Automatic Memory Management: Many high-level languages include
features for automatic memory management, reducing the risk of memory-
related errors.
Examples of High-Level Languages:
i. Python: known for its simplicity and readability, Python is widely used in
web development, data science, and artificial intelligence.
ii. Java: Java's platform independence and object-oriented features make it
suitable for building a wide range of applications.
iii. C++: an extension of C, C++ adds object-oriented features, making it
powerful for system-level programming and game development.
iv. JavaScript: primarily used for web development, JavaScript is a high-
level language that runs in web browsers.

Programming Paradigm
Programming paradigms define the approach and style of computer
programming. Each paradigm provides a set of principles and practices for
designing and structuring code. Understanding different programming paradigms
allows programmers to choose the most suitable approach for a given problem.
Common Programming Paradigms
i. Imperative Paradigm: The imperative paradigm focuses on describing
the steps that a programme should take to reach a particular state. It is based
on the concept of changing programme state through a sequence of
statements. Imperative programming uses control structures like loops and
conditional statements to guide the flow of execution. Example of
imperative languages: C, FORTRAN, Pascal, and COBOL.
ii. Object-Oriented Paradigm: Object-oriented programming (OOP)
organises code around objects, which are instances of classes. Objects
encapsulate data and behavior, promoting modularity and reusability. OOP
introduces the concept of classes, which define the blueprint for objects.
Objects are instances of these classes. Key features include encapsulation,
inheritance, and polymorphism. Encapsulation involves bundling data and
methods that operate on that data within a single unit (object). This helps
in hiding the internal details of an object. Inheritance allows one class to
inherit properties and methods from another, facilitating code reuse and
creating a hierarchy of classes. Polymorphism enables objects of different
types to be treated as objects of a common type, simplifying code and
making it more adaptable. Example of object-oriented languages: Java, C#,
and Smalltalk.
iii. Functional Paradigm: The functional paradigm treats computation as the
evaluation of mathematical functions. It avoids changing state and mutable
data, relying on the concept of immutability and pure functions. Functions
in the functional paradigm are pure, meaning they produce the same output
for the same input and do not have side effects. Functions are treated as
first-class citizens, meaning they can be assigned to variables, passed as
arguments, and returned as values. Higher-order functions take other
functions as parameters. Immutability is another key feature of functional
paradigm that prevents the modification of data once it's created. Instead
of changing existing data, new data structures are created. Example of
functional languages: ML, Miranda TM, Scala, Clojure and Haskell.
iv. Logic Programming: Logic programming is based on formal logic.
Programmes in this paradigm express relationships and rules as logical
statements, and the execution involves finding solutions to logical queries.
Logic programming is characterised by distinctive features. Firstly, it
adopts a declarative style, diverging from the imperative paradigm, where
programmers articulate what needs to be achieved rather than specifying
how to achieve it. Secondly, the structure of logic programmes is built upon
rules and facts. Rules define relationships and conditions, shaping the
programme's logic, while facts provide the base knowledge. Lastly, logic
programming employs backtracking as a fundamental mechanism. This
enables the exploration of alternative solutions when searching for a
satisfying answer to a query, contributing to the language's flexibility and
problem-solving capabilities. Example of logic programming language:
Prolog.
Scripting Languages
Scripting languages are programming languages that are often interpreted and
designed for executing scripts, which are sets of commands written for a specific
runtime environment. These languages prioritise ease of use and quick
development, making them suitable for various applications. Examples: Python,
JavaScript, and Shell Scripting.
Python stands out as a high-level, general-purpose scripting language renowned
for its readability and versatility. Its syntax emphasises code readability, making
it an accessible language for both beginners and experienced developers. Python
supports multiple programming paradigms, including procedural, object-
oriented, and functional programming, providing flexibility in coding styles. One
of Python's strengths lies in its extensive standard library, offering pre-built
modules and packages that simplify the development process. Python is key in
web development (Django, Flask), data analysis (NumPy, Pandas), machine
learning (TensorFlow), automation, and network programming.
JavaScript is a versatile scripting language primarily utilised for web
development, enabling the creation of dynamic and interactive content in web
browsers. As a client-side language, JavaScript enhances user experience by
enabling functionalities such as form validation and asynchronous data retrieval.
Moreover, its versatility extends to server-side development through platforms
like Node.js, expanding its role beyond the browser. JavaScript is a cornerstone
in front-end web development, powering popular frameworks like React,
Angular, and Vue.js. It also finds application in server-side development using
Node.js, where its event-driven architecture contributes to efficient handling of
concurrent connections. Beyond web development, JavaScript is employed in
game development through frameworks like Phaser, showcasing its adaptability
across various domains.
Shell scripting involves the use of a command-line shell to execute a series of
commands in a script. It is a powerful tool for automating system tasks and
managing processes in a Unix-like environment, offering efficient and concise
solutions for various tasks. Shell scripting is indispensable in system
administration and configuration tasks, automating repetitive processes and
ensuring consistency across systems. It excels in file and data manipulation,
providing quick and efficient ways to process and analyze data. Additionally,
shell scripts are widely employed for tasks such as automated backups and
scheduled jobs (cron jobs), making them a vital component of system
maintenance and management.
Important Features of Scripting Languages
i. Interpreted Execution: Scripting languages are often interpreted rather
than compiled, allowing for immediate execution of code without the need
for a separate compilation step.
ii. Dynamic Typing: Scripting languages typically use dynamic typing,
where variable types are determined at runtime. This flexibility simplifies
code writing but may lead to runtime errors.
iii. High-Level Abstraction: Scripting languages provide high-level
abstractions, making it easier for programmers to express concepts without
dealing with low-level details.
iv. Rapid Development: The focus on ease of use and quick development
makes scripting languages ideal for tasks like automation, web
development, and system administration.

2.6.2 Applications and Advantages of Scripting Languages


Applications
i. Automation: Scripting languages are widely used for automating
repetitive tasks, such as file manipulation, data processing, and system
administration.
ii. Web Development: Languages like Python and JavaScript are commonly
used for server-side and client-side scripting, respectively, in web
development.
iii. Data Analysis and Processing: Python, with libraries like Pandas, is a
popular choice for data analysis and processing due to its readability and
extensive ecosystem.
iv. Prototyping: Scripting languages are valuable for quickly prototyping
ideas and concepts, allowing for rapid iteration during the development
phase.
Advantages
i. Readability and Conciseness: Scripting languages often have a clean and
concise syntax, promoting readability and reducing the amount of code
needed to perform tasks.
ii. Platform Independence: Many scripting languages are platform-
independent, allowing scripts to run on different operating systems without
modification.
iii. Community Support: Popular scripting languages, such as Python and
JavaScript, have large and active communities. This results in extensive
libraries, frameworks, and online resources for developers.
iv. Versatility: Scripting languages can be applied in various domains, from
system administration to data science, making them versatile tools for
different tasks.
High-Level Language Translators
High-level language translators are tools that convert human-readable code
written in high-level programming languages into machine-readable code that
computers can execute. Three main types of translators are commonly used:
assemblers, compilers, and interpreters.
Assemblers
Assemblers are tools that convert assembly language code into machine code.
Assembly language is a low-level programming language that uses symbolic
representations of machine code instructions. Assemblers are primarily used in
low-level programming for tasks where direct control over hardware resources is
essential, such as embedded systems or device drivers.
Process
i. Assembly Code: Programmers write code in assembly language, using
mnemonic symbols and labels to represent machine instructions.
ii. Assembling: The assembler translates the assembly code into machine
code, creating an executable programme.
iii. Linking: Additional steps, such as linking, may be involved to incorporate
external libraries and create a complete executable.
2.1.2 Compilers
Compilers are tools that translate entire high-level source code into machine code
or an intermediate code. The compilation process involves multiple stages,
including lexical analysis, syntax analysis, optimisation, and code generation.
Compilers are widely used in software development for creating standalone
applications, system software, and large-scale projects.
Process
i. Source Code: Programmers write code in a high-level language like C,
C++, or Java.
ii. Compilation: The compiler processes the entire source code, checking for
syntax errors and translating it into machine code or an intermediate code.
iii. Optimisation: Optionally, the compiler performs optimisation to improve
the efficiency and performance of the generated code.
iv. Linking: The linker combines the compiled code with external libraries and
generates an executable file.
Interpreters
Interpreters are tools that execute high-level source code directly without the need
for a separate compilation step. They interpret and execute the code line by line
at runtime. Interpreters are commonly used in scripting languages and for tasks
that require rapid development and testing.
Process
i. Source Code: Programmers write code in a high-level language like
Python, JavaScript, or Ruby.
ii. Interpretation: The interpreter reads and executes the source code line by
line, translating each statement into machine code or an intermediate form
on the fly.
Compilation Process: Traditional Compiler
The compilation process for traditional compilers involves several stages, each
responsible for transforming the source code into an executable programme.
Stages
i. Lexical Analysis: The source code is analyzed to identify and tokenize
individual components (tokens), such as keywords, identifiers, and literals.
ii. Syntax Analysis: The compiler checks the syntactic structure of the code
to ensure it conforms to the language's grammar rules. It generates a syntax
tree representing the code structure.
iii. Semantic Analysis: The compiler verifies the meaning of the code by
analyzing the relationships between different parts. It checks for semantic
errors and performs type checking.
iv. Intermediate Code Generation: The compiler generates an intermediate
representation of the code that is independent of the target machine. This
facilitates optimisation and simplifies the generation of machine code.
v. Code Optimisation: The compiler applies various optimisation techniques
to improve the efficiency of the generated code. optimisation may include
removing redundant code, inlining functions, and reordering instructions.
vi. Code Generation: The compiler translates the optimised intermediate
code into the machine code of the target architecture.
vii. Code Linking: External libraries and modules are linked to the generated
code to create a complete executable.
viii. Code Loading: The executable is loaded into memory for execution.
Compilation Process: Java Compiler
Java follows a similar compilation process, but with some differences due to its
platform independence and use of the Java Virtual Machine (JVM).
Java Compilation Process:
i. Java Source Code: Developers write code in Java using a high-level
syntax.
ii. Compilation: The Java compiler (‘javac’) translates the source code into
bytecode. Bytecode is an intermediate representation specific to the Java
platform.
iii. Bytecode: Instead of generating machine code, the Java compiler produces
bytecode, which is a set of instructions for the Java Virtual Machine (JVM).
iv. Java Virtual Machine (JVM): The JVM is responsible for executing Java
bytecode. It abstracts the underlying hardware, making Java programmes
platform-independent.
v. Just-In-Time (JIT) Compilation: At runtime, the JVM uses a Just-In-
Time compiler to translate bytecode into machine code for the specific
hardware it is running on.
vi. Execution: The machine code is executed by the CPU, allowing the Java
programme to run on any device with a compatible JVM.

Java Virtual Machine


The Java Virtual Machine (JVM) is a crucial component in the Java programming
language. It provides a platform-independent execution environment for Java
bytecode.
Main Features
i. Platform Independence: Java programmes are compiled into bytecode,
which is then executed by the JVM. This bytecode can run on any device
with a JVM, ensuring platform independence.
ii. Memory Management: The JVM handles memory allocation and garbage
collection, making it easier for developers to manage memory resources.
iii. Security: The JVM includes a security manager to enforce security
restrictions, preventing malicious code from causing harm.
iv. Performance Optimisation: The JVM uses Just-In-Time (JIT)
compilation to translate bytecode into machine code at runtime, improving
the performance of Java programmes.

Figure 1: JIT Compile Process (Java Programming Environment and the Java Runtime
Environment, n.d.)
Java Programmes Structure
Source Programme
Components
i. Class Definition: A Java programme typically consists of one or more
classes. Each class is defined using the ‘class’ keyword.
ii. Main Method: The ‘main’ method serves as the entry point of a Java
program. It is where the programme starts executing.
iii. Statements: Java programmes are composed of statements that perform
actions. Statements end with a semicolon (;).
Syntax:
public class ClassName {
public static void main (String [] args) {
statement 1
statement 2

Statement N
}
}

Example:
public class HelloWorld {
public static void main (String[] args) {
System.out.println(“Hello, World!”);
}
}
The above example should be typed and saved as " HelloWorld.java." It's crucial
to bear in mind that Java is case-sensitive and follows a free-form layout. Specific
words such as public, class, static, void, main, and others are designated as
reserved or keywords, and their meanings are fixed by the language. The first
line, "public class HelloWorld," signifies the creation of a new class named

40 Al-Muhibbah Open University


HelloWorld. Classes, integral to Java, serve as factories for objects, but here, the
HelloWorld class is used as a container for the programme's instructions.
Understanding these fundamentals is essential for effectively working with Java
programming.
Java requires that all programme instructions be placed inside methods and that
every method must be placed inside a class. Therefore, you must define methods
that would contain programme’s instructions and a class that holds the methods.
In this example, main() is the only method while HelloWorld is the class.
2.4.2 Escape Sequence
Escape sequences are special sequences of characters that are used to represent
certain non-printable or reserved characters in a string.
Common escape sequences:
i. Newline (\n): Represents a newline character. Example: String newLine =
“Line 1\nLine 2”;
ii. Tab (\t): Represents a tab character. Example: String tab = “Column
1\tColumn 2”;
iii. Double Quote (\”): Represents a double quote within a string. Example:
String quote = “He said, \”Hello!\””;
iv. Backslash Character (\\): Represents a backslash character. Example:
String backslash = “This is a backslash: \\”;
Overview of Java Programming Language
Java is a versatile and widely used object-oriented programming language known
for its platform independence and portability. Developed by James Gosling and
his team at Sun Microsystems in the mid-1990s, Java was designed to be a robust,
secure, and flexible language suitable for a variety of applications. One of its key
features is the "Write Once, Run Anywhere" principle, achieved through the use
of the Java Virtual Machine (JVM). Java has found extensive application in web
development, enterprise-level applications, mobile app development (especially
for Android), and large-scale systems due to its reliability, scalability, and
extensive standard library.
Principal Characteristics
i. Platform Independence: Java programmes are compiled into bytecode,
which can run on any device with a Java Virtual Machine (JVM), making
Java platform-independent.
ii. Object-Oriented: Java follows the principles of Object-Oriented
Programming (OOP), promoting modularity, code reusability, and
encapsulation.
iii. Robust and Secure: Java includes features like automatic memory
management (garbage collection) and strong type-checking, enhancing
robustness and security.
iv. Multi-threading: Java supports multi threading, allowing concurrent
execution of multiple threads within the same programmes.
2.2 Setting up Java Development Environment
Setting up a Java development environment involves a series of steps to ensure
that you have the necessary tools and configurations to write, compile, and run
Java programmes. Here is a general guide to setting up a basic Java development
environment.
Steps:
i. Install Java Development Kit (JDK): Download and install the latest
version of the Java Development Kit (JDK) from the official Oracle
website or adopt OpenJDK if you prefer an open-source alternative. Follow
the installation instructions for your operating system.
ii. Set Java Environment Variables: After installing the JDK, set the
`JAVA_HOME` environment variable to point to the directory where the
JDK is installed. Additionally, add the `bin` directory of the JDK to the
system's `PATH` variable to make Java commands accessible from any
location in the terminal or command prompt.
iii. Install an Integrated Development Environment (IDE): Choose an IDE
based on your preference. Popular Java IDEs include IntelliJ IDEA,
Eclipse, and NetBeans. Download and install the chosen IDE, following
the provided instructions.
iv. Configure the IDE: Open the IDE and configure it to use the installed
JDK. Verify that the IDE recognizes the Java installation by checking the
configured JDK version in the IDE settings.
v. Create a Java Project: In your chosen IDE, create a new Java project.
Define the project settings, including the project name, location, and any
specific libraries or frameworks you intend to use.
vi. Write and Compile a Java Programme: Create a new Java class within
the project and write a simple Java programme. Save the file with a `.java`
extension. Use the IDE's build or compile command to compile the
programme.
vii. Run the Java Programme: Once the programme is compiled
successfully, run it from within the IDE. The IDE should execute the
programme, and you should see the output in the console or terminal.
2.3 Basics of Java Syntax and Structure
This presents the fundamental elements that define the structure and rules for
writing Java programmes.
Main Syntax Elements
Class Declaration
A Java programme typically starts with the declaration of a class using the class
keyword. The following syntax represents the declaration of a Java class named
MyClass. The keyword public indicates that the class is accessible from outside
its package. The class body, enclosed within curly braces {}, is where you define
the properties (fields) and behaviors (methods) of the class.
public class MyClass {
// Class body
}

Main Method
The ‘main’ method serves as the entry point of a Java programme and is declared
as follows:
public static void main(String[] args) {
// Main method body
}

Variables and Data Types


Declare variables with specific data types (e.g., ‘int’, ‘double’, ‘String’).
int age = 25;
double temperature = 98.6;
String name = “John”;

Control Flow Statements


Use control flow statements like ‘if’, ‘else’, ‘for’, and ‘while’ to control the flow
of programmes execution.

if (condition) {
// Code block executed if the condition is true
} else {
// Code block executed if the condition is false
} Example:
int x = 10;

if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is not greater than 5");
}

for (int i = 0; i < 5; i++) {


// Code block executed in each iteration
}
Example:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}

while (condition) {
// Code block executed as long as the condition is true
}

Example:
int count = 0;

while (count < 3) {


System.out.println("Count: " + count);
count++;
}

Writing and Running a Simple Java Programme


Writing and running a simple Java programme is a fundamental step in getting
started with Java development. Here's a step-by-step guide to writing and
executing a basic Java programme.
Steps:
Write Java Code
Use a text editor or integrated development environment (IDE) to write Java code.
Save as .java File
Save the code with a .java extension, using the name of the main class.
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World!”);
}
}

Compile the Code


Open a command prompt or terminal, navigate to the directory containing the
.java file, and use the ‘javac’ command to compile the code.
javac HelloWorld.java

Run the Programme


Use the ‘java’ command followed by the name of the main class (excluding
the .class extension) to run the compiled programme.
java HelloWorld

You might also like