Java Notes - ISC Grade 11
1. Objects and Classes
Features of Objects:
- Identity: Unique reference (like memory address).
- State: Data or attributes (e.g., name, age).
- Behavior: Methods that define actions (e.g., run(), display()).
Attributes in a Class:
Attributes are instance variables defined inside the class but outside methods.
class Student {
int rollNumber; // attribute
String name; // attribute
}
Methods in a Class:
class Student {
int rollNumber;
String name;
void display() {
System.out.println("Roll: " + rollNumber + ", Name: " + name);
}
}
Constructors:
Constructors initialize objects. They have the same name as the class and no return type.
class Student {
int rollNumber;
String name;
Student(int r, String n) {
rollNumber = r;
name = n;
}
void display() {
System.out.println("Roll: " + rollNumber + ", Name: " + name);
}
}
2. Primitive Values, Type Casting, Variables and Expressions
Primitive Data Types:
int, byte, short, long, float, double, char, boolean
Type Casting:
int a = 10;
double b = a; // Widening
int c = (int) 5.67; // Narrowing
Variables and Expressions:
int x = 10, y = 5;
int sum = x + y;
3. Statements, Control Structures and Scope
Selection Statements:
int a = 10, b = 20;
if (a < b) {
System.out.println("a is smaller");
} else if (a == b) {
System.out.println("Equal");
} else {
System.out.println("b is smaller");
}
Iteration Statements:
// for loop
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// while loop
int j = 1;
while (j <= 5) {
System.out.println(j);
j++;
}
// do..while loop
int k = 1;
do {
System.out.println(k);
k++;
} while (k <= 5);
Jump Statements:
for (int i = 1; i <= 10; i++) {
if (i == 5) continue;
if (i == 8) break;
System.out.println(i);
}
4. Number Programs
// Check if a number is prime
int num = 29;
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
System.out.println(num + " is " + (isPrime ? "Prime" : "Not Prime"));
5. Functions/Methods
Actual and Formal Parameters:
void greet(String name) { // formal parameter
System.out.println("Hello " + name);
}
greet("Alice"); // actual parameter
Call by Value:
void change(int x) {
x = 100;
}
Call by Reference (for objects):
void modify(Student s) {
s.name = "Updated";
}
Static Members:
class Counter {
static int count = 0;
Counter() {
count++;
}
static void displayCount() {
System.out.println("Count: " + count);
}
}
Pure and Impure Functions:
- Pure Function: No side effects.
int add(int a, int b) {
return a + b;
}
- Impure Function: Changes external state.
int count = 0;
void increment() {
count++;
}