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

Introduction to Programming

The document provides an introduction to programming, explaining its purpose as creating instructions for computers and its applications in various fields such as web development, mobile apps, and robotics. It covers different programming languages, particularly Java, and details the development environment, key concepts, and the structure of Java programs, including classes, methods, and data types. Additionally, it discusses operators, control statements, loops, and methods in Java, emphasizing the importance of code reusability and modularity.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Introduction to Programming

The document provides an introduction to programming, explaining its purpose as creating instructions for computers and its applications in various fields such as web development, mobile apps, and robotics. It covers different programming languages, particularly Java, and details the development environment, key concepts, and the structure of Java programs, including classes, methods, and data types. Additionally, it discusses operators, control statements, loops, and methods in Java, emphasizing the importance of code reusability and modularity.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Introduction to Programming

What is Programming?

Programming is the process of creating instructions for a computer to follow. These


instructions tell the computer what to do step by step, whether it's displaying a message on
the screen, processing data, or interacting with users. Programming is like giving a set of
commands to a machine, making it do task that humans want to accomplish.

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.

Overview of Different Programming Languages

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.

Introduction to the Development Environment

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.

1. IDE (Integrated Development Environment):


o What It Is: A software application that provides comprehensive facilities to
programmers for software development.
o Features: Code editor, debugger, compiler, and other tools.
o Example: PyCharm for Python, IntelliJ IDEA for Java.
o Why Use It: An IDE can make writing and testing code easier with features
like syntax highlighting, autocompletion, and error detection.
2. Text Editors:
o What It Is: A simpler tool for writing code, compared to an IDE. It doesn't
have as many built-in features but is lightweight and fast.
o Examples: VSCode, Sublime Text, Notepad++.
o Why Use It: Text editors are faster and less resource-intensive, making them a
good choice for small projects.

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

Java is a high-level, object-oriented programming language used for developing desktop,


web, and mobile applications. It is widely known for its portability, scalability, and security
features. Java applications run on the Java Virtual Machine (JVM), making them platform-
independent, meaning they can run on any operating system with a compatible JVM.

Common Uses of Java:

 Web Development (Spring Boot, JSP, Servlets)


 Mobile App Development (Android)
 Enterprise Applications
 Game Development
 Embedded Systems

Installing Java Development Kit (JDK) and IDE

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.

Writing and Running Your First Java Program

A simple Java program to print "Hello, World!":

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Explanation:

 public class HelloWorld {} → Declares a class named HelloWorld.


 public static void main(String[] args) {} → The main method
where execution starts.
 System.out.println(); → Prints output to the console.

Run the program using:

javac HelloWorld.java // Compiles the program


java HelloWorld // Runs the compiled bytecode

Understanding the Structure of a Java Program

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:

public class MyClass {


int number; // Variable (property of the class)
public void displayNumber() { // Method (behavior of the
class)
System.out.println("The number is: " + number);
}
}

Explanation:

 public class MyClass {} defines a class named MyClass.


 int number; is a variable that stores an integer.
 public void displayNumber() is a method that prints the value of number.

Methods

A method is a block of code designed to perform a specific task when called. Methods allow
code reusability and modularity.

Example:

public class Calculator {


public int add(int a, int b) {
return a + b;
}
}

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:

 Assignment statements (e.g., int x = 5;)


 Method calls (e.g., System.out.println();)
 Control flow statements (if, for, while, etc.)
Example:

System.out.println("Hello, Java!");
Explanation:

 This statement prints "Hello, Java!" to the console.


 System.out.println(); is a method that outputs text.

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:

int num = 10; // num is an integer variable storing the value


10.

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 Basics - Data Types and Variables

Primitive Data Types

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)

 Used to store whole numbers (positive, negative, or zero)


 Size: 4 bytes (32-bit)
 Range: -2,147,483,648 to 2,147,483,647
 Example:

int num = 10;

2. Decimal (double)

 Used for numbers with decimals (floating-point values)


 Size: 8 bytes (64-bit)
 Range: Approximately ±1.8 × 10³⁰⁸
 Example:

double pi = 3.14159;

3. Character (char)

 Stores a single character (letter, digit, or symbol) using Unicode representation


 Size: 2 bytes (16-bit)
 Example:

char letter = 'A';

4. Boolean (boolean)

 Stores only two values: true or false


 Size: 1 bit (depends on the JVM implementation)
 Example:

boolean isJavaFun = true;

5. Other Primitive Data Types

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;

Declaring and Initializing Variables

A variable is a container that holds a value. It must be declared with a data type before use.

Syntax:

dataType variableName = value;

Examples:

int age = 25; // Integer variable


double height = 5.9; // Floating-point variable
char grade = 'A'; // Character variable
boolean isStudent = false; // Boolean variable
Constants and final Keyword

A constant is a variable whose value cannot be changed after being assigned. Constants are
declared using the final keyword.

Example:

final double PI = 3.14159;

 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 and Conversion

Type casting allows us to convert one data type into another. There are two types:

1. Implicit Casting (Widening Conversion)

 Automatically converts smaller data types to larger ones.


 No data loss.
 Example:

int num = 10;


double convertedNum = num; // Implicit casting (int to double)

2. Explicit Casting (Narrowing Conversion)

 Converts larger data types to smaller ones.


 Data loss may occur.
 Requires explicit casting using parentheses.
 Example:

double price = 9.99;


int roundedPrice = (int) price; // Explicit casting (double to
int)

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 and Control Statements


Operators in Java

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)

2. Relational (Comparison) Operators (Used for comparisons, returns true or false)

Operator Description Example


> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
== Equal to a == b
!= Not equal to a != b

Example:

System.out.println(a > b); // Output: true (5 is greater than 3)


System.out.println(a == b); // Output: false (5 is not equal to 3)

3. Logical Operators (Used for combining boolean expressions)

Operator Description Example


&& Logical AND (both conditions must be true) (a > 2 && b < 5)
` `
! Logical NOT (negates a boolean expression) !(a == b)

Example:
boolean condition1 = (a > 2 && b < 5); // true
boolean condition2 = (a > 2 || b > 5); // true
boolean condition3 = !(a == b); // true

4. Bitwise Operators (Used for bit-level operations)

Operator Description Example


& Bitwise AND a & b
` ` Bitwise OR
^ Bitwise XOR a ^ b
<< Left shift a << 1
>> Right shift a >> 1

Example:

System.out.println(a & b); // Output: 1 (Bitwise AND)


System.out.println(a | b); // Output: 7 (Bitwise OR)
System.out.println(a ^ b); // Output: 6 (Bitwise XOR)
System.out.println(a << 1); // Output: 10 (Left Shift)
System.out.println(a >> 1); // Output: 2 (Right Shift)

Conditional Statements

Conditional statements control the flow of execution based on conditions.

1. if Statement (Executes if the condition is true)

if (a > b) {
System.out.println("a is greater");
}

2. if-else Statement (Executes different blocks based on the condition)

if (a > b) {
System.out.println("a is greater");
} else {
System.out.println("b is greater");
}

3. switch Statement (Selects one case to execute based on a value)

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

Loops are used to repeat a block of code multiple times.

1. for Loop

Used when the number of iterations is known.

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


System.out.println(i);
}

Output:

0
1
2
3
4

2. while Loop

Used when the number of iterations is not known in advance.

int i = 0;
while(i < 5) {
System.out.println(i);
i++;
}

3. do-while Loop

Executes the block at least once before checking the condition.

int i = 0;
do {
System.out.println(i);
i++;
} while(i < 5);
Break and Continue Statements

Used to control the execution of loops.

1. break Statement (Exits the loop when a condition is met)

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


if(i == 3) break;
System.out.println(i);
}

Output:

0
1
2

(Loop stops when i == 3)

2. continue Statement (Skips the current iteration and continues with the next one)

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


if(i == 3) continue;
System.out.println(i);
}

Output:

0
1
2
4

(i == 3 is skipped)

Functions and Methods in Java


Defining and Calling Methods

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

public class Example {


// Method definition
public static int sum(int a, int b) {
return a + b;
}

public static void main(String[] args) {


int result = sum(5, 10); // Method call
System.out.println("Sum: " + result);
}
}

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).

Example: Method Overloading

public class OverloadingExample {


// Method with two int parameters
public int add(int a, int b) {
return a + b;
}

// Method with two double parameters


public double add(double a, double b) {
return a + b;
}

// Method with three parameters


public int add(int a, int b, int c) {
return a + b + c;
}

public static void main(String[] args) {


OverloadingExample obj = new OverloadingExample();
System.out.println("Sum of two ints: " + obj.add(5,
10));
System.out.println("Sum of two doubles: " +
obj.add(5.5, 10.5));
System.out.println("Sum of three ints: " + obj.add(5,
10, 15));
}
}

Output:

Sum of two ints: 15


Sum of two doubles: 16.0
Sum of three ints: 30

Key Points About Method Overloading:

 The method name remains the same.


 The number or type of parameters must be different.
 The return type does not distinguish overloaded methods.
 Overloading improves code readability and reusability.

Object-Oriented Programming (OOP)

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.

2. Defining Classes and Objects

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 class example:


class Car {
String model;

Car(String model) {
this.model = model;
}
}

 Class: Car is a class that represents the concept of a car.


 Instance Variable: String model; is an instance variable. It stores the model of
the car for each object created from the class.
 Constructor: Car(String model) is a constructor. It initializes the model of
the car when a new Car object is created. The this keyword refers to the current
object that is being created.

To create an object of the Car class:

Car myCar = new Car("Toyota");

This creates an object myCar of the Car class and initializes it with the model "Toyota".

3. Inheritance and Method Overriding

 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.

Animal and Dog class example:

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Bark");
}
}

 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:

Dog myDog = new Dog();


myDog.sound(); // Output: Bark

 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 = {1, 2, 3, 4, 5};

 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.

Accessing Array Elements:

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

 numbers[0] refers to the first element in the array (1).


 numbers[4] refers to the fifth element in the array (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.

numbers[2] = 10; // Changes the third element (3) to 10


System.out.println(numbers[2]); // Output: 10

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:

String message = "Hello, Java!";

 String message: This declares a variable message of type String.


 "Hello, Java!": This is a String literal. It represents a sequence of characters
and is assigned to the message variable.

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:

1. Accessing Characters in a String:

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

 message.charAt(0) accesses the first character of the string, which is H.


 message.charAt(7) accesses the eighth character, which is J.

2. Finding the Length of a String:

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:

You can concatenate (combine) strings using the + operator.

String newMessage = message + " Welcome!";


System.out.println(newMessage); // Output: Hello, Java!
Welcome!

4. String Comparison:

You can compare strings using the .equals() method, which checks if the strings are
identical.

String anotherMessage = "Hello, Java!";


System.out.println(message.equals(anotherMessage)); //
Output: true

If you want to compare strings without case sensitivity, use .equalsIgnoreCase().

System.out.println(message.equalsIgnoreCase("HELLO, JAVA!"));
// Output: true

5. Substring:

You can extract a part of a string using the .substring(startIndex, endIndex)


method.

String subMessage = message.substring(7, 11);


System.out.println(subMessage); // Output: Java

This extracts a substring from the 7th to the 10th character (index 7 to 10), resulting in
"Java".

You might also like