1.
Introduction to Programming
● Programming is the process of writing instructions for a computer to execute.
● Java is an object-oriented, compiled language used in this course.
● Syntax refers to the rules that define the structure of valid programs.
● Semantics refers to the meaning or behavior of the written code.
2. Structure of a Java Program
A basic Java program consists of:
java
Copy code
public class Main {
public static void main(String[] args) {
// Code here
}
}
● Comments are used to describe code:
○ Single-line: //
○ Multi-line: /* */
3. Variables and Data Types
● Primitive data types:
○ int for integers
○ double for decimal numbers
○ char for single characters
○ boolean for true/false
● Reference data types:
○ String for sequences of characters
○ Arrays, objects, etc.
● Constants are declared using the final keyword:
java
Copy code
final double PI = 3.14159;
4. Operators
● Arithmetic: +, -, *, /, %
● Comparison: ==, !=, <, >, <=, >=
● Logical: &&, ||, !
● Assignment: =, +=, -=, *=, etc.
5. Control Structures
Conditional Statements
java
Copy code
if (x > 0) {
System.out.println("Positive");
} else if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
Switch Statement
java
Copy code
switch (value) {
case 1:
// code
break;
default:
// code
break;
}
Loops
● For loop:
java
Copy code
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
● While loop:
java
Copy code
while (condition) {
// code
}
● Do-while loop:
java
Copy code
do {
// code
} while (condition);
6. Methods
● A method defines a reusable block of code:
java
Copy code
public static int sum(int a, int b) {
return a + b;
}
● Parameters are the inputs; return values are outputs.
● Methods must be called by name to be executed.
7. Arrays
● Declaration:
java
Copy code
int[] numbers = new int[5];
● Initialization:
java
Copy code
int[] numbers = {1, 2, 3, 4, 5};
● Accessing elements:
java
Copy code
int x = numbers[0];
● Getting length:
java
Copy code
int length = numbers.length;
8. Object-Oriented Programming (Introduction)
● A class is a blueprint for creating objects:
java
Copy code
public class Car {
String model;
int year;
}
● Creating an object:
java
Copy code
Car myCar = new Car();
myCar.model = "Civic";
● Constructors initialize object attributes when created.
9. Strings
● Strings are objects used to store text.
● Common methods:
○ length()
○ toUpperCase()
○ charAt(int index)
○ substring(start, end)
○ equals(String other)
○ indexOf(String s)
10. User Input with Scanner
● The Scanner class is used to read user input:
java
Copy code
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
String name = sc.nextLine();
11. Types of Errors
● Syntax Error: Violates Java language rules; prevents compilation.
● Runtime Error: Occurs during execution (e.g., divide by zero).
● Logic Error: Program runs but produces incorrect results.