[Go to site: main page, start]

0% found this document useful (0 votes)
2 views39 pages

Java Programming Notes

This document provides comprehensive study notes on Java programming, covering its introduction, features, applications, and essential components like JDK, JRE, and JVM. It includes sections on writing and running Java programs, basic programming concepts such as variables, data types, and operators, along with practical examples. The content is structured into units that guide the reader through fundamental Java concepts and syntax.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views39 pages

Java Programming Notes

This document provides comprehensive study notes on Java programming, covering its introduction, features, applications, and essential components like JDK, JRE, and JVM. It includes sections on writing and running Java programs, basic programming concepts such as variables, data types, and operators, along with practical examples. The content is structured into units that guide the reader through fundamental Java concepts and syntax.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Programming

Complete Study Notes with Concepts, Syntax, and Simple Examples


Unit 1: Introduction to Java
1.1 What is Java?
Concept:
Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995 (now owned
by Oracle). It was designed to be simple, portable, and secure, following the principle 'Write Once, Run
Anywhere' (WORA) — a Java program compiled on one platform can run on any other platform that has a Java
Virtual Machine (JVM).

1.2 Features of Java


Concept:
Java has several features that make it one of the most popular programming languages for building reliable,
cross-platform applications.
● Simple – easy to learn syntax, similar to C/C++ but without complex features like pointers.
● Object-Oriented – everything is organized around classes and objects.
● Platform Independent – compiled code (bytecode) runs on any device with a JVM.
● Secure – no explicit pointers, runs inside a protected JVM environment.
● Robust – strong memory management and exception handling.
● Multithreaded – supports running multiple tasks (threads) at the same time.
● Portable – bytecode can be moved and executed on any platform.
● High Performance – Just-In-Time (JIT) compiler improves execution speed.

1.3 Applications of Java


Concept:
Java is used across many domains because of its portability and reliability.
● Web applications (e.g., using servlets, JSP, Spring).
● Mobile applications (Android apps are primarily written in Java/Kotlin).
● Desktop GUI applications (using Swing or JavaFX).
● Enterprise software (banking systems, ERP software).
● Embedded systems and IoT devices.
● Scientific and big data applications.

1.4 JDK, JRE, and JVM


Concept:
These three components work together to develop and run Java programs.
● JVM (Java Virtual Machine) – an abstract machine that executes Java bytecode. It makes Java platform-
independent by converting bytecode into machine code for the specific operating system.
● JRE (Java Runtime Environment) – provides the libraries and JVM needed to run Java applications, but
does not include development tools like the compiler.
● JDK (Java Development Kit) – a complete package that includes the JRE plus development tools such as
the compiler (javac) needed to write and compile Java programs.

Explanation:
In short: JDK = JRE + development tools, and JRE = JVM + libraries. To write and run Java programs, you need the
JDK installed.

1.5 Installing Java (JDK)


Concept:
Before writing Java programs, the JDK must be installed and configured on the computer.
● Download the JDK installer from Oracle's official website (or use OpenJDK).
● Run the installer and follow the setup steps.
● Set the JAVA_HOME environment variable to the JDK installation folder.
● Add the JDK's 'bin' folder to the system PATH variable so java and javac commands work from any
location.
● Verify installation by opening Command Prompt/Terminal and typing: java -version and javac -version.

1.6 Writing, Compiling, and Running a Java Program


Concept:
A Java program is first written in a .java file, then compiled into bytecode (.class file) using javac, and finally
executed using the java command.

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.

1.7 Structure of a Java Program


Concept:
Every Java program follows a general structure: an optional package declaration, optional import statements, a
class definition, and inside the class, the main method along with other members.

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.

1.8 main() Method


Concept:
The main() method is the starting point of execution for any standalone Java application. The JVM looks for this
exact method signature to start running the program.

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

2.2 Data Types


Concept:
Java has two categories of data types: primitive (byte, short, int, long, float, double, char, boolean) which store
simple values directly, and non-primitive (String, arrays, classes) which store references to objects.

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.

2.6 Type Conversion and Type Casting


Concept:
Type conversion changes a value from one data type to another. It can be implicit (automatic, smaller type to
larger type, also called widening) or explicit (manual, larger type to smaller type, also called narrowing, done
using casting).

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

2.7 Input using Scanner


Concept:
The Scanner class (from [Link] package) is used to read input entered by the user through the keyboard.

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.

2.8 Output using print(), println(), and printf()


Concept:
Java provides three common ways to display output: print() prints without a new line, println() prints and moves
to the next line, and printf() prints formatted output using format specifiers.

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

3.2 Assignment Operators


Concept:
Assignment operators assign values to variables. Java also provides compound assignment operators (+=, -=,
*=, /=, %=) that combine an operation with assignment.

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.

3.4 Logical Operators


Concept:
Logical operators (&& AND, || OR, ! NOT) combine multiple boolean expressions and return a boolean result.

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.

3.5 Unary Operators


Concept:
Unary operators act on a single operand. Examples include unary minus (-), unary plus (+), and logical NOT (!).

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.

3.6 Increment and Decrement Operators


Concept:
The increment (++) and decrement (--) operators increase or decrease a variable's value by 1. They can be used
in pre form (++a, before use) or post form (a++, after use).

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.

3.7 Bitwise Operators


Concept:
Bitwise operators (&, |, ^, ~, <<, >>) work directly on the individual bits of integer values.

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.

3.8 Ternary Operator


Concept:
The ternary operator (? :) is a shorthand for an if-else statement. It evaluates a condition and returns one of two
values depending on whether it is true or false.

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.

3.9 Operator Precedence


Concept:
Operator precedence determines the order in which operators are evaluated in an expression. Operators with
higher precedence (like * and /) are evaluated before those with lower precedence (like + and -).

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.

4.2 if-else Statement


Concept:
The if-else statement executes one block of code if the condition is true, and a different block if it is false.

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.

4.4 else-if Ladder


Concept:
The else-if ladder is used to test multiple conditions in sequence, executing the block for the first condition that
is true.

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.

4.5 switch Statement


Concept:
The switch statement selects one of many code blocks to execute based on the value of a variable, offering a
cleaner alternative to a long else-if ladder.

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.

4.6 break and continue


Concept:
'break' immediately exits a loop or switch statement, while 'continue' skips the current iteration of a loop and
moves to the next one.

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.

5.2 do-while Loop


Concept:
The do-while loop is similar to the while loop, but it checks the condition after executing the loop body, so the
body always runs at least once.

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.

5.3 for Loop


Concept:
The for loop is used when the number of iterations is known in advance. It combines initialization, condition, and
update in a single line.

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.

5.4 Enhanced for Loop


Concept:
The enhanced for loop (also called for-each) is used to iterate over arrays or collections without using an index
variable.

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.

5.5 Nested Loops


Concept:
A nested loop is a loop placed inside another loop. The inner loop completes all its iterations for each single
iteration of the outer loop.

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.

5.6 Pattern Programs


Concept:
Pattern programs use nested loops to print shapes made of characters or numbers, and are commonly used to
practice loop logic.

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.

6.2 Two-Dimensional Arrays


Concept:
A two-dimensional array stores data in a table-like structure of rows and columns, useful for representing grids
or matrices.

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

6.3 Array Initialization


Concept:
Arrays can be initialized either at the time of declaration with fixed values, or later by assigning values to
individual index positions.

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.

6.4 Passing Arrays to Methods


Concept:
An array can be passed as an argument to a method, allowing the method to access or modify its elements
directly.

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.

6.5 Array Programs (Sum, Average, Largest, Smallest, Search)


Concept:
Arrays are commonly used to perform operations like calculating the sum, average, finding the largest/smallest
value, or searching for an element by looping through all the elements.

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

7.2 Method Calling


Concept:
Calling a method means executing the code inside it by writing its name followed by parentheses, optionally
passing values it needs.

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

7.3 Parameters and Arguments


Concept:
Parameters are variables listed in a method's definition to receive input values, while arguments are the actual
values passed to the method when it is called.

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.

7.4 Return Type


Concept:
The return type of a method specifies the data type of the value it sends back to the caller using the 'return'
keyword. If a method returns nothing, its return type is 'void'.

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.

7.5 Method Overloading


Concept:
Method overloading allows multiple methods in the same class to have the same name but different parameter
lists (different number or types of parameters).

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.

7.6 Scope of Variables


Concept:
The scope of a variable defines the region of the program where it can be accessed. Local variables (declared
inside a method) are only accessible within that method, while instance/class variables have wider scope.

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.

7.7 Recursion (Basic)


Concept:
Recursion is a technique where a method calls itself to solve a smaller instance of the same problem, continuing
until it reaches a base case that stops the recursive calls.

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.

8.3 Creating Objects


Concept:
Objects are created by using the 'new' keyword followed by a call to the class's constructor, which allocates
memory and initializes the object.

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.

8.5 this Keyword


Concept:
The 'this' keyword refers to the current object of the class. It is commonly used to distinguish between instance
variables and parameters that have the same name.

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

8.6 Instance and Static Members


Concept:
Instance members belong to individual objects (each object has its own copy), while static members belong to
the class itself and are shared by all objects of that class.

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.

9.2 Method Overriding


Concept:
Method overriding occurs when a subclass provides its own implementation of a method that is already defined
in its superclass, replacing the parent's version when called on the subclass object.

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.

You might also like