Java Programming Notes
Java Programming Notes
Explanation:
In short: JDK = JRE + development tools, and JRE = JVM + libraries. To write and run Java programs, you need the
JDK installed.
Syntax:
javac [Link] // compiles the program
java FileName // runs the compiled program
Example:
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Output:
Hello, World!
Explanation:
Save the file as [Link] (the file name must match the public class name). Running 'javac
[Link]' creates [Link]. Running 'java HelloWorld' executes the program and prints the
message to the screen.
Syntax:
// package declaration (optional)
// import statements (optional)
class ClassName {
// fields and methods
public static void main(String[] args) {
// program logic
}
}
Example:
public class Structure {
public static void main(String[] args) {
[Link]("This is the basic structure of a Java program");
}
}
Output:
This is the basic structure of a Java program
Explanation:
The class name (Structure) matches the file name ([Link]). The main() method is the entry point where
execution begins.
Syntax:
public static void main(String[] args) {
// code to execute
}
Example:
public class MainDemo {
public static void main(String[] args) {
[Link]("main() method started execution");
}
}
Output:
main() method started execution
Explanation:
'public' allows the JVM to call it from outside the class, 'static' means it can run without creating an object, 'void'
means it returns nothing, and 'String[] args' allows command-line arguments to be passed.
1.9 Comments
Concept:
Comments are non-executable lines used to explain code. Java supports three types of comments.
Syntax:
// single-line comment
/* multi-line
comment */
/** documentation comment (Javadoc) */
Example:
public class CommentDemo {
public static void main(String[] args) {
// This line prints a message
[Link]("Comments explained");
/* This is a
multi-line comment */
}
}
Output:
Comments explained
Explanation:
The compiler ignores comments; they exist only to make code readable for humans and do not affect the
program's output.
Unit 2: Basic Programming
2.1 Variables
Concept:
A variable is a named memory location used to store a value that can change during program execution. Every
variable in Java must be declared with a data type before use.
Syntax:
dataType variableName = value;
Example:
public class VariableDemo {
public static void main(String[] args) {
int age = 20;
[Link]("Age: " + age);
}
}
Output:
Age: 20
Explanation:
Here 'age' is a variable of type int storing the value 20, which is then printed using [Link]().
Syntax:
int a;
double b;
char c;
boolean d;
Example:
public class DataTypeDemo {
public static void main(String[] args) {
int num = 10;
double price = 99.5;
char grade = 'A';
boolean pass = true;
[Link](num + " " + price + " " + grade + " " + pass);
}
}
Output:
10 99.5 A true
Explanation:
Each variable is declared with its matching data type: int for whole numbers, double for decimals, char for a
single character, and boolean for true/false values.
2.3 Identifiers
Concept:
Identifiers are the names given to variables, methods, classes, and other elements in a program. They must start
with a letter, underscore (_), or dollar sign ($), and cannot use Java keywords or contain spaces.
Syntax:
int studentAge; // valid identifier
int _count; // valid
int 2total; // invalid – cannot start with a digit
Example:
public class IdentifierDemo {
public static void main(String[] args) {
int studentAge = 21;
[Link]("Student age is " + studentAge);
}
}
Output:
Student age is 21
Explanation:
'studentAge' is a valid identifier used as a variable name, following Java's naming rules.
2.4 Keywords
Concept:
Keywords are reserved words in Java that have a predefined meaning and cannot be used as identifiers.
Examples include class, public, static, void, int, if, else, for, while, return.
Example:
public class KeywordDemo {
public static void main(String[] args) {
int number = 5;
if (number > 0) {
[Link]("Positive number");
}
}
}
Output:
Positive number
Explanation:
In this example, 'public', 'class', 'static', 'void', 'int', and 'if' are all Java keywords, each serving a specific fixed
purpose in the language.
2.5 Literals
Concept:
A literal is a fixed value directly written in the source code, such as a number, character, or text, that is assigned
to a variable.
Syntax:
int a = 10; // integer literal
double b = 5.5; // floating literal
char c = 'A'; // character literal
String s = "Hello"; // string literal
boolean flag = true; // boolean literal
Example:
public class LiteralDemo {
public static void main(String[] args) {
int marks = 90;
char grade = 'A';
String name = "Kumar";
[Link](name + " scored " + marks + " and got grade " +
grade);
}
}
Output:
Kumar scored 90 and got grade A
Explanation:
90, 'A', and "Kumar" are literals — fixed constant values assigned directly to variables.
Syntax:
// Implicit (widening)
double d = intValue;
// Explicit (narrowing)
int i = (int) doubleValue;
Example:
public class TypeCastDemo {
public static void main(String[] args) {
int num = 10;
double d = num; // implicit conversion
double price = 99.9;
int p = (int) price; // explicit casting
[Link]("d = " + d);
[Link]("p = " + p);
}
}
Output:
d = 10.0
p = 99
Explanation:
'num' (int) is automatically converted to double. 'price' (double) is manually cast to int, which truncates the
decimal part (99.9 becomes 99).
Syntax:
import [Link];
Scanner sc = new Scanner([Link]);
int x = [Link]();
String s = [Link]();
Example:
import [Link];
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Your age is " + age);
}
}
Output:
Enter your age: 22
Your age is 22
Explanation:
The program pauses at [Link]() and waits for the user to type a number. Whatever the user enters (here, 22)
is stored in 'age' and printed.
Syntax:
[Link]("text");
[Link]("text");
[Link]("%d %s", intValue, stringValue);
Example:
public class OutputDemo {
public static void main(String[] args) {
[Link]("Hello ");
[Link]("World");
[Link]("Marks: %d, Name: %s", 85, "Ravi");
}
}
Output:
Hello World
Marks: 85, Name: Ravi
Explanation:
print() keeps the cursor on the same line, println() moves to a new line, and printf() formats the number (%d)
and string (%s) inside the output text.
Unit 3: Operators
3.1 Arithmetic Operators
Concept:
Arithmetic operators (+, -, *, /, %) are used to perform basic mathematical operations on numeric values.
Syntax:
a + b a - b a * b a / b a % b
Example:
public class ArithmeticDemo {
public static void main(String[] args) {
int a = 10, b = 3;
[Link]("Sum: " + (a + b));
[Link]("Remainder: " + (a % b));
}
}
Output:
Sum: 13
Remainder: 1
Explanation:
'+' adds the two numbers, and '%' (modulus) gives the remainder after division (10 divided by 3 leaves
remainder 1).
Syntax:
a = b;
a += b; // same as a = a + b;
Example:
public class AssignmentDemo {
public static void main(String[] args) {
int a = 5;
a += 3;
[Link]("a = " + a);
}
}
Output:
a = 8
Explanation:
'a += 3' is shorthand for 'a = a + 3', so 5 + 3 gives 8.
3.3 Relational Operators
Concept:
Relational operators (==, !=, >, <, >=, <=) compare two values and return a boolean result (true or false).
Syntax:
a == b a != b a > b a < b a >= b a <= b
Example:
public class RelationalDemo {
public static void main(String[] args) {
int a = 10, b = 20;
[Link](a < b);
[Link](a == b);
}
}
Output:
true
false
Explanation:
Since 10 is less than 20, 'a < b' evaluates to true, while 'a == b' evaluates to false because they are not equal.
Syntax:
a && b a || b !a
Example:
public class LogicalDemo {
public static void main(String[] args) {
int age = 20;
boolean hasID = true;
[Link](age >= 18 && hasID);
}
}
Output:
true
Explanation:
Both conditions (age >= 18 is true, and hasID is true) are true, so the && (AND) operator returns true.
Syntax:
-a +a !flag
Example:
public class UnaryDemo {
public static void main(String[] args) {
int a = 5;
[Link](-a);
}
}
Output:
-5
Explanation:
The unary minus operator reverses the sign of the value, converting 5 to -5.
Syntax:
a++; ++a; a--; --a;
Example:
public class IncrementDemo {
public static void main(String[] args) {
int a = 5;
a++;
[Link]("a = " + a);
}
}
Output:
a = 6
Explanation:
'a++' increases the value of a by 1, changing it from 5 to 6.
Syntax:
a & b a | b a ^ b ~a a << 1 a >> 1
Example:
public class BitwiseDemo {
public static void main(String[] args) {
int a = 5, b = 3;
[Link](a & b);
}
}
Output:
1
Explanation:
5 in binary is 101 and 3 is 011. The bitwise AND (&) compares each bit, giving 001, which equals 1 in decimal.
Syntax:
variable = (condition) ? valueIfTrue : valueIfFalse;
Example:
public class TernaryDemo {
public static void main(String[] args) {
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Max: " + max);
}
}
Output:
Max: 20
Explanation:
Since a > b is false (10 is not greater than 20), the ternary operator selects b (20) as the result.
Syntax:
result = a + b * c; // multiplication happens before addition
Example:
public class PrecedenceDemo {
public static void main(String[] args) {
int result = 10 + 5 * 2;
[Link]("Result: " + result);
}
}
Output:
Result: 20
Explanation:
Multiplication has higher precedence than addition, so 5 * 2 = 10 is calculated first, and then 10 + 10 = 20.
Unit 4: Control Statements
4.1 if Statement
Concept:
The if statement executes a block of code only if a given condition evaluates to true.
Syntax:
if (condition) {
// code executes if condition is true
}
Example:
public class IfDemo {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
[Link]("Number is positive");
}
}
}
Output:
Number is positive
Explanation:
Since 10 > 0 is true, the code inside the if block runs and prints the message.
Syntax:
if (condition) {
// executes if true
} else {
// executes if false
}
Example:
public class IfElseDemo {
public static void main(String[] args) {
int num = -5;
if (num > 0) {
[Link]("Positive");
} else {
[Link]("Not positive");
}
}
}
Output:
Not positive
Explanation:
Since -5 is not greater than 0, the condition is false, so the else block runs.
4.3 Nested if
Concept:
A nested if is an if statement placed inside another if (or else) block, allowing multiple levels of conditions to be
checked.
Syntax:
if (condition1) {
if (condition2) {
// executes if both conditions are true
}
}
Example:
public class NestedIfDemo {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
[Link]("Allowed to drive");
}
}
}
}
Output:
Allowed to drive
Explanation:
The outer if checks age >= 18 (true), and the inner if checks hasLicense (true), so the message is printed.
Syntax:
if (condition1) {
// ...
} else if (condition2) {
// ...
} else {
// ...
}
Example:
public class ElseIfDemo {
public static void main(String[] args) {
int marks = 75;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 60) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
}
}
Output:
Grade B
Explanation:
75 is not >= 90, so the first condition fails, but it is >= 60, so 'Grade B' is printed and the remaining conditions are
skipped.
Syntax:
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Example:
public class SwitchDemo {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
}
}
}
Output:
Wednesday
Explanation:
Since day equals 3, the program jumps directly to 'case 3' and prints 'Wednesday', then break exits the switch.
Syntax:
break;
continue;
Example:
public class BreakContinueDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
if (i == 5) {
break;
}
[Link](i);
}
}
}
Output:
1
2
4
Explanation:
When i == 3, continue skips printing that value and moves to the next iteration. When i == 5, break stops the
loop entirely, so 5 is never printed.
Unit 5: Looping Statements
5.1 while Loop
Concept:
The while loop repeats a block of code as long as a given condition remains true. The condition is checked before
each iteration.
Syntax:
while (condition) {
// code to repeat
}
Example:
public class WhileDemo {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
}
}
Output:
1
2
3
4
5
Explanation:
The loop prints and increments 'i' until the condition (i <= 5) becomes false.
Syntax:
do {
// code to repeat
} while (condition);
Example:
public class DoWhileDemo {
public static void main(String[] args) {
int i = 1;
do {
[Link](i);
i++;
} while (i <= 3);
}
}
Output:
1
2
3
Explanation:
The loop body executes first, printing 1, 2, and 3, and then stops once i becomes 4 and the condition fails.
Syntax:
for (initialization; condition; update) {
// code to repeat
}
Example:
public class ForDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link](i);
}
}
}
Output:
1
2
3
4
5
Explanation:
The loop starts at i=1, runs while i <= 5, and increases i by 1 after each iteration, printing values 1 through 5.
Syntax:
for (dataType element : array) {
// code using element
}
Example:
public class EnhancedForDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int n : numbers) {
[Link](n);
}
}
}
Output:
10
20
30
Explanation:
The loop automatically goes through each element of the 'numbers' array and prints it, without needing an
index.
Syntax:
for (initialization; condition; update) {
for (initialization; condition; update) {
// inner loop code
}
}
Example:
public class NestedLoopDemo {
public static void main(String[] args) {
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 2; j++) {
[Link]("i=" + i + " j=" + j);
}
}
}
}
Output:
i=1 j=1
i=1 j=2
i=2 j=1
i=2 j=2
Explanation:
For each value of i, the inner loop runs completely through both values of j before i increases again.
Syntax:
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
[Link]("*");
}
[Link]();
}
Example:
public class StarPatternDemo {
public static void main(String[] args) {
int rows = 3;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
[Link]("*");
}
[Link]();
}
}
}
Output:
*
**
***
Explanation:
The outer loop controls the row number, and the inner loop prints one '*' for each value up to the current row,
forming a triangle.
Unit 6: Arrays
6.1 One-Dimensional Arrays
Concept:
A one-dimensional array is a collection of elements of the same data type stored in a single row of contiguous
memory locations, accessed using an index starting from 0.
Syntax:
dataType[] arrayName = new dataType[size];
dataType[] arrayName = {value1, value2, ...};
Example:
public class ArrayDemo {
public static void main(String[] args) {
int[] marks = {80, 90, 70};
[Link](marks[0]);
[Link](marks[1]);
}
}
Output:
80
90
Explanation:
'marks' is an array storing three values. marks[0] accesses the first element (80) and marks[1] accesses the
second (90), since indexing starts at 0.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
Example:
public class TwoDArrayDemo {
public static void main(String[] args) {
int[][] matrix = {{1, 2}, {3, 4}};
[Link](matrix[0][1]);
[Link](matrix[1][0]);
}
}
Output:
2
3
Explanation:
matrix[0][1] accesses the element in row 0, column 1 (value 2), and matrix[1][0] accesses row 1, column 0 (value
3).
Syntax:
int[] arr = new int[3];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
Example:
public class ArrayInitDemo {
public static void main(String[] args) {
int[] arr = new int[3];
arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
[Link](arr[2]);
}
}
Output:
15
Explanation:
The array is first created with a size of 3, and then each index is assigned a value individually. arr[2] holds 15.
Syntax:
static returnType methodName(dataType[] arr) {
// use arr
}
Example:
public class ArrayMethodDemo {
static void printArray(int[] arr) {
for (int val : arr) {
[Link](val);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
printArray(numbers);
}
}
Output:
1
2
3
Explanation:
The array 'numbers' is passed to the printArray() method, which loops through and prints each element.
Syntax:
for (int i = 0; i < [Link]; i++) {
// process arr[i]
}
Example:
public class ArrayOperationsDemo {
public static void main(String[] args) {
int[] arr = {12, 45, 3, 67, 21};
int sum = 0, max = arr[0], min = arr[0];
for (int i = 0; i < [Link]; i++) {
sum += arr[i];
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
[Link]("Sum: " + sum);
[Link]("Average: " + (sum / [Link]));
[Link]("Largest: " + max);
[Link]("Smallest: " + min);
}
}
Output:
Sum: 148
Average: 29
Largest: 67
Smallest: 3
Explanation:
The loop goes through every element once: adding each value to 'sum', and updating 'max'/'min' whenever a
larger or smaller value is found. Average is sum divided by the number of elements.
Unit 7: Methods
7.1 Defining Methods
Concept:
A method is a named block of code that performs a specific task and can be executed (called) whenever needed,
helping to organize and reuse code.
Syntax:
returnType methodName(parameters) {
// method body
}
Example:
public class MethodDefDemo {
static void greet() {
[Link]("Hello from a method!");
}
public static void main(String[] args) {
greet();
}
}
Output:
Hello from a method!
Explanation:
'greet' is a method with no return value (void) and no parameters. It is defined once and then called from
main().
Syntax:
methodName(arguments);
Example:
public class MethodCallDemo {
static void showMessage() {
[Link]("Method called successfully");
}
public static void main(String[] args) {
showMessage();
}
}
Output:
Method called successfully
Explanation:
Writing 'showMessage();' inside main() transfers control to the method, executes its code, and then returns back
to main().
Syntax:
static void methodName(dataType parameter) {
// use parameter
}
methodName(argument);
Example:
public class ParameterDemo {
static void greet(String name) {
[Link]("Hello, " + name);
}
public static void main(String[] args) {
greet("Priya");
}
}
Output:
Hello, Priya
Explanation:
'name' is the parameter defined in the method, and "Priya" is the argument passed when the method is called.
Syntax:
returnType methodName(parameters) {
return value;
}
Example:
public class ReturnDemo {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
int result = square(5);
[Link]("Square: " + result);
}
}
Output:
Square: 25
Explanation:
The method 'square' takes a number, calculates its square, and returns the result (int), which is then stored in
'result' and printed.
Syntax:
returnType methodName(int a) { ... }
returnType methodName(int a, int b) { ... }
Example:
public class OverloadDemo {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
[Link](add(2, 3));
[Link](add(2.5, 3.5));
}
}
Output:
5
6.0
Explanation:
Java chooses the correct 'add' method to run based on the argument types: integers call the int version, and
decimals call the double version.
Syntax:
void method() {
int localVar = 10; // accessible only inside this method
}
Example:
public class ScopeDemo {
static void display() {
int localVar = 25;
[Link]("Local variable: " + localVar);
}
public static void main(String[] args) {
display();
}
}
Output:
Local variable: 25
Explanation:
'localVar' is declared inside the display() method, so it only exists and is only accessible while that method is
executing.
Syntax:
returnType methodName(parameters) {
if (baseCondition) {
return baseValue;
}
return methodName(smallerInput);
}
Example:
public class RecursionDemo {
static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
[Link]("Factorial of 4: " + factorial(4));
}
}
Output:
Factorial of 4: 24
Explanation:
factorial(4) calls factorial(3), which calls factorial(2), and so on until factorial(0) returns 1 (the base case). The
results are then multiplied together: 4×3×2×1 = 24.
Unit 8: Object-Oriented Programming
8.1 Class
Concept:
A class is a blueprint or template that defines the properties (fields) and behaviors (methods) that its objects will
have. It does not occupy memory on its own until an object is created.
Syntax:
class ClassName {
// fields
// methods
}
Example:
class Student {
String name;
int age;
}
public class ClassDemo {
public static void main(String[] args) {
[Link]("Student class defined");
}
}
Output:
Student class defined
Explanation:
'Student' is a class with two fields (name and age). No object has been created yet, so these fields don't hold any
real values.
8.2 Object
Concept:
An object is an instance of a class, created using the 'new' keyword. It has its own copy of the fields defined by
the class and can use the class's methods.
Syntax:
ClassName objectName = new ClassName();
Example:
class Student {
String name = "Anu";
}
public class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student();
[Link]([Link]);
}
}
Output:
Anu
Explanation:
's1' is an object of the Student class, created using 'new'. It can access the field 'name' defined in the class using
the dot (.) operator.
Syntax:
ClassName objectName = new ClassName(arguments);
Example:
class Book {
String title = "Java Basics";
}
public class CreateObjectDemo {
public static void main(String[] args) {
Book b1 = new Book();
[Link]([Link]);
}
}
Output:
Java Basics
Explanation:
'new Book()' creates a new object 'b1' in memory, and '[Link]' accesses its field to print the book's title.
8.4 Constructors
Concept:
A constructor is a special method automatically called when an object is created. It has the same name as the
class and no return type, and is typically used to initialize an object's fields.
Syntax:
class ClassName {
ClassName() {
// initialization code
}
}
Example:
class Car {
String brand;
Car() {
brand = "Toyota";
}
}
public class ConstructorDemo {
public static void main(String[] args) {
Car c1 = new Car();
[Link]([Link]);
}
}
Output:
Toyota
Explanation:
When 'new Car()' is executed, the constructor runs automatically and sets 'brand' to "Toyota" before the object
is used.
Syntax:
[Link] = parameterName;
Example:
class Student {
String name;
Student(String name) {
[Link] = name;
}
}
public class ThisDemo {
public static void main(String[] args) {
Student s1 = new Student("Karthik");
[Link]([Link]);
}
}
Output:
Karthik
Explanation:
Since the parameter and the field are both named 'name', '[Link]' refers to the object's field, distinguishing it
from the parameter, so it correctly stores "Karthik".
Syntax:
class ClassName {
int instanceVar; // instance member
static int staticVar; // static member
}
Example:
class Counter {
static int count = 0;
Counter() {
count++;
}
}
public class StaticDemo {
public static void main(String[] args) {
new Counter();
new Counter();
[Link]("Count: " + [Link]);
}
}
Output:
Count: 2
Explanation:
'count' is static, so it is shared across all objects. Each time a new Counter object is created, the constructor
increases the same shared 'count' value, resulting in 2 after two objects are created.
Unit 9: OOP Concepts
9.1 Inheritance
Concept:
Inheritance allows one class (subclass/child) to acquire the fields and methods of another class
(superclass/parent) using the 'extends' keyword, promoting code reuse.
Syntax:
class Parent {
// fields and methods
}
class Child extends Parent {
// additional fields and methods
}
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output:
Animal makes a sound
Explanation:
'Dog' inherits the sound() method from 'Animal' using 'extends', so an object of Dog can directly call it without
redefining it.
Syntax:
class Parent {
void display() { ... }
}
class Child extends Parent {
@Override
void display() { ... }
}
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
public class OverrideDemo {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output:
Dog barks
Explanation:
'Dog' redefines the sound() method with its own behavior. When called on a Dog object, the overridden (child)
version runs instead of the parent's version.
9.3 Polymorphism
Concept:
Polymorphism means 'many forms' — it allows the same method call to behave differently depending on the
object that invokes it. It is commonly achieved through method overriding (runtime polymorphism) and method
overloading (compile-time polymorphism).
Syntax:
Parent obj = new Child();
[Link](); // calls the child's overridden version
Example:
class Shape {
void draw() {
[Link]("Drawing a shape");
}
}
class Circle extends Shape {
@Override
void draw() {
[Link]("Drawing a circle");
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
}
}
Output:
Drawing a circle
Explanation:
Even though the reference type is 'Shape', the actual object is 'Circle', so the overridden draw() method of Circle
is executed — this is runtime polymorphism.
9.4 Abstraction
Concept:
Abstraction means hiding internal implementation details and showing only the essential features to the user. In
Java, it is achieved using abstract classes and interfaces.
Syntax:
abstract class ClassName {
abstract void methodName();
}
Example:
abstract class Shape {
abstract void draw();
}
class Square extends Shape {
void draw() {
[Link]("Drawing a square");
}
}
public class AbstractionDemo {
public static void main(String[] args) {
Shape s = new Square();
[Link]();
}
}
Output:
Drawing a square
Explanation:
'Shape' is an abstract class with an abstract method draw() that has no body. 'Square' must provide its own
implementation, which is what actually runs.
9.5 Interfaces
Concept:
An interface is a fully abstract type that defines a set of methods (without implementation) that a class must
implement, using the 'implements' keyword. It supports full abstraction and multiple inheritance of behavior.
Syntax:
interface InterfaceName {
void methodName();
}
class ClassName implements InterfaceName {
public void methodName() { ... }
}
Example:
interface Vehicle {
void start();
}
class Bike implements Vehicle {
public void start() {
[Link]("Bike starts with a kick");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Vehicle v = new Bike();
[Link]();
}
}
Output:
Bike starts with a kick
Explanation:
'Bike' implements the 'Vehicle' interface and provides the actual code for the start() method, which is then
executed when called.
9.6 Encapsulation
Concept:
Encapsulation is the practice of bundling data (fields) and methods together in a class while restricting direct
access to the fields using access modifiers like 'private', and providing controlled access through public getter
and setter methods.
Syntax:
class ClassName {
private dataType field;
public dataType getField() { return field; }
public void setField(dataType value) { field = value; }
}
Example:
class Student {
private int marks;
public void setMarks(int m) {
marks = m;
}
public int getMarks() {
return marks;
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
Student s1 = new Student();
[Link](85);
[Link]("Marks: " + [Link]());
}
}
Output:
Marks: 85
Explanation:
'marks' is private, so it cannot be accessed directly from outside the class. It can only be set and read using the
public setMarks() and getMarks() methods, which protects the data.