Introduction to Programming
Introduction to Programming
What is Programming?
In simpler terms, programming is how you tell a computer what to do and how to do it. Just
like a recipe tells you how to cook a dish, programming tells the computer how to perform a
task.
Application of Programming
Websites: The code behind a website is written in languages like HTML, CSS, and
JavaScript.
Apps: Mobile applications (like Instagram or WhatsApp) are programmed using
languages such as Java or Swift.
Games: Video games are created using programming languages like C++ or Unity’s
C#.
Automation: Businesses use programming to automate tasks like sending emails,
processing data, or generating reports.
Robotics: Robots are programmed to carry out specific functions in industries like
manufacturing, healthcare, and even space exploration.
There are many programming languages, and each has its strengths and weaknesses. Here’s a
brief look at some of the most popular ones:
1. Python:
o Purpose: General-purpose language. It's easy to read and write.
o Used for: Web development, automation, data analysis, machine learning, and
more.
o Key Feature: Python has simple syntax, making it great for beginners.
2. Java:
o Purpose: A versatile language used in many different environments.
o Used for: Web applications, Android apps, enterprise-level software, and big
systems.
o Key Feature: Write once, run anywhere. Java programs can run on any device
with a Java runtime environment (JRE).
3. C++:
o Purpose: A powerful language, used for more performance-critical
applications.
o Used for: Game development, operating systems, and high-performance
applications.
o Key Feature: C++ gives the programmer more control over memory, making
it very fast.
o
4. JavaScript:
o Purpose: Mainly used to create interactive web pages.
o Used for: Front-end web development (the part of websites users interact
with) and some back-end work.
o Key Feature: Runs directly in web browsers, making it ideal for web
applications.
5. Ruby:
o Purpose: Known for its elegant and readable code.
o Used for: Web development, often with the Ruby on Rails framework.
o Key Feature: Ruby prioritizes developer happiness and productivity.
Each language is designed to solve different problems, and the choice of language depends
on the project’s requirements.
To write and run programs, you need a development environment, which is a setup that
includes tools to help you write and test your code.
Key Concepts
1. Code: This is the text that programmers write to make the computer perform tasks. It
consists of commands and statements written in a programming language.
2. Syntax: The set of rules that defines the structure of statements in a programming
language. For example, in Python, you must write print() with parentheses, or the
program will produce an error.
3. Programs vs. Applications:
o Program: A set of instructions that tells the computer what to do. It can be a
simple script to perform a task, like adding two numbers.
o Application: A more complex software solution that provides a user-friendly
interface and performs a broad set of tasks. For example, a calculator app or a
word processor like Microsoft Word.
Overview of Java and its Applications
1. Download and install the JDK from Oracle's website or use OpenJDK.
2. Choose an IDE such as Eclipse, IntelliJ IDEA, or VS Code for easier coding and
debugging.
Explanation:
A Java program is composed of several essential components that define how the program
functions and interacts with data. Each component plays a crucial role in structuring and
executing the program.
Classes
A class in Java acts as a blueprint for creating objects. It defines the properties (variables)
and behaviors (methods) that an object will have. Every Java program must have at least one
class.
Example:
Explanation:
Methods
A method is a block of code designed to perform a specific task when called. Methods allow
code reusability and modularity.
Example:
Explanation:
The add method takes two integers as input and returns their sum.
Methods can accept parameters and return values.
3. Statements
A statement in Java is an instruction that tells the program what to do. Statements end with a
semicolon (;) and can be of different types:
System.out.println("Hello, Java!");
Explanation:
Variables
A variable is a container used to store data that can change during program execution.
Variables have a data type that defines what type of data they can hold.
Example:
Types of Variables:
Local Variables: Declared inside methods and accessible only within those methods.
Instance Variables: Declared in a class but outside methods; each object gets its
copy.
Static Variables: Shared among all instances of a class.
Java provides eight built-in primitive data types. These types are the most fundamental
building blocks for storing data in Java programs. Each primitive type has a specific memory
size and range of values.
1. Integer (int)
2. Decimal (double)
double pi = 3.14159;
3. Character (char)
4. Boolean (boolean)
Data
Size Range Example
Type
byte smallNumber =
byte 1 byte -128 to 127 100;
2 short shortNumber =
short -32,768 to 32,767
bytes 32000;
8 -9,223,372,036,854,775,808 to long bigNumber =
long
bytes 9,223,372,036,854,775,807 1000000000L;
4 float decimalValue =
float Approximately ±3.4 × 10³⁸
bytes 5.75f;
A variable is a container that holds a value. It must be declared with a data type before use.
Syntax:
Examples:
A constant is a variable whose value cannot be changed after being assigned. Constants are
declared using the final keyword.
Example:
final ensures that the variable PI cannot be modified later in the program.
Attempting to reassign a value will result in a compilation error.
Type casting allows us to convert one data type into another. There are two types:
By understanding data types, variables, constants, and type conversions, we can write
efficient and error-free Java programs that handle various data values appropriately.
Operators are special symbols that perform operations on variables and values. Java provides
several types of operators:
1. Arithmetic Operators (Used for mathematical operations)
Operator Description Example
+ Addition int sum = a + b;
- Subtraction int diff = a - b;
* Multiplication int product = a * b;
/ Division int quotient = a / b;
% Modulus (Remainder) int remainder = a % b;
Example:
int a = 5, b = 3;
System.out.println(a + b); // Output: 8 (Addition)
System.out.println(a - b); // Output: 2 (Subtraction)
System.out.println(a * b); // Output: 15 (Multiplication)
System.out.println(a / b); // Output: 1 (Division)
System.out.println(a % b); // Output: 2 (Modulus)
Example:
Example:
boolean condition1 = (a > 2 && b < 5); // true
boolean condition2 = (a > 2 || b > 5); // true
boolean condition3 = !(a == b); // true
Example:
Conditional Statements
if (a > b) {
System.out.println("a is greater");
}
if (a > b) {
System.out.println("a is greater");
} else {
System.out.println("b is greater");
}
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Loops in Java
1. for Loop
Output:
0
1
2
3
4
2. while Loop
int i = 0;
while(i < 5) {
System.out.println(i);
i++;
}
3. do-while Loop
int i = 0;
do {
System.out.println(i);
i++;
} while(i < 5);
Break and Continue Statements
Output:
0
1
2
2. continue Statement (Skips the current iteration and continues with the next one)
Output:
0
1
2
4
(i == 3 is skipped)
A method is a block of code that performs a specific task. Methods improve code reusability
and modularity.
Syntax of a Method
returnType methodName(parameters) {
// method body
return value; // optional (only if returnType is not void)
}
Example: Creating and Calling a Method
Output:
Sum: 15
Explanation:
sum(int a, int b): A method that takes two integers as arguments and returns
their sum.
static: Means the method belongs to the class and can be called without creating
an object.
return a + b;: Returns the computed sum to the caller.
sum(5, 10): Calls the method and passes 5 and 10 as arguments.
Method Overloading
Method overloading allows multiple methods in the same class to have the same name but
different parameter lists (number, type, or both).
Output:
OOP is a programming paradigm that organizes software design around objects, rather than
functions or logic. It allows developers to create classes that represent real-world entities, and
objects are instances of these classes. The key principles of OOP are:
Encapsulation: Bundling data and the methods that operate on that data into a single
unit, typically a class.
Inheritance: Allows one class (child class) to inherit the properties and behaviors
(methods) from another class (parent class).
Polymorphism: Allows a method or function to behave differently based on the
object calling it (method overriding or overloading).
Abstraction: Hiding the complex implementation and showing only the necessary
details to the user.
A class is a blueprint for creating objects (instances). It defines the properties (variables) and
behaviors (methods) that objects created from the class will have.
Car(String model) {
this.model = model;
}
}
This creates an object myCar of the Car class and initializes it with the model "Toyota".
Inheritance is when one class (child class) inherits the properties and behaviors
(methods) of another class (parent class). This allows you to reuse code and extend
functionality.
Method Overriding allows a subclass to provide a specific implementation of a
method that is already defined in its superclass.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Parent Class (Animal): The Animal class has a method sound() that prints a
generic message, "Animal makes a sound".
Child Class (Dog): The Dog class extends the Animal class and overrides the
sound() method. The overridden method prints "Bark" instead of the generic
message.
When we create an object of the Dog class and call sound(), the overridden version of
sound() in the Dog class will be executed:
Inheritance: The Dog class inherits the sound() method from the Animal class,
but it overrides it with its own implementation.
Method Overriding: The Dog class provides a new implementation for the
sound() method that differs from the one in the Animal class.
Arrays
An array is a collection of elements that are of the same type. It is a data structure that can
store multiple values in a single variable. Arrays in Java are fixed in size once they are
created, and each element in the array is accessed using an index.
Example:
int[] numbers: This declares an array called numbers that will hold integer
values. The type of the array is int[] (an array of integers).
{1, 2, 3, 4, 5}: This is an array initializer, which assigns values directly to the
array. It means that the numbers array will contain 5 integers: 1, 2, 3, 4, and 5.
Once the array is initialized, you can access its elements using an index. In Java, array indices
start at 0. So, the first element has index 0, the second element has index 1, and so on.
You can access and modify the elements of the array using their indices.
System.out.println(numbers[0]); // Output: 1
System.out.println(numbers[4]); // Output: 5
Array Length:
To get the length of the array (i.e., how many elements it contains), you can use the
.length property.
System.out.println(numbers.length); // Output: 5
Modifying Array Elements:
You can change the value of any element in the array using its index.
2. Strings
A String is a sequence of characters. In Java, strings are objects of the String class. Unlike
arrays, strings are immutable, meaning once they are created, their values cannot be changed
directly.
Example:
In Java, you can perform various operations on strings, but since strings are immutable,
operations like concatenation or modification return a new string.
String Operations:
You can access individual characters in a string using the .charAt(index) method. The
index starts from 0.
System.out.println(message.charAt(0)); // Output: H
System.out.println(message.charAt(7)); // Output: J
You can use the .length() method to find the length (the number of characters) in the
string.
System.out.println(message.length()); // Output: 13
3. Concatenating Strings:
4. String Comparison:
You can compare strings using the .equals() method, which checks if the strings are
identical.
System.out.println(message.equalsIgnoreCase("HELLO, JAVA!"));
// Output: true
5. Substring:
This extracts a substring from the 7th to the 10th character (index 7 to 10), resulting in
"Java".