Java Notes
Unit-1
Prepared by
Faculty Incharge
Ms. V. Karpaga Varshini
Lecturer
DCN
UNIT 1
Introduction to OOPS and JAVA
Object-Oriented Paradigm (OOP)
A programming paradigm based on the concept of objects, which are instances of classes.
Objects encapsulate data and behavior together.
Core Concepts of OOP:
1. Classes and Objects
o Class: A blueprint or template defining attributes (data) and methods (functions).
o Object: An instance of a class, representing an entity with state and behavior.
2. Encapsulation
o Bundling data (attributes) and methods (functions) that operate on the data into a
single unit (class).
o Controls access to the inner workings through access modifiers (like private,
public).
3. Inheritance
o Mechanism where a new class (child/subclass) inherits attributes and methods
from an existing class (parent/superclass).
o Promotes code reuse and establishes a hierarchy.
4. Polymorphism
o Ability of different classes to respond to the same method call in different ways.
o Often achieved through method overriding (in subclasses) and method
overloading.
5. Abstraction
o Hiding complex implementation details and showing only essential features of an
object.
o Helps manage complexity and focus on interactions.
Difference between Procedure Oriented Programming and Object
Oriented Programming
Parameter Procedural Programming (POP) Object-Oriented Programming (OOP)
Focus Emphasizes functions (procedures) Emphasizes data (objects) and their
and the sequence of actions. properties/behaviors.
Program Large programs are divided into Programs are divided into smaller units
Division smaller units called functions. called objects (instances of classes).
Approach Follows a top-down design Follows a bottom-up design approach.
approach.
Data Hiding No proper way to hide data; global Data can be hidden using encapsulation and
data is accessible by all functions, access modifiers (public, private, protected),
leading to less security. making it more secure.
Code Limited code reusability; code often High code reusability through features
Reusability needs to be rewritten. like inheritance.
Real-World Difficult to model real-world problems Easier to model real-world entities by combining
Modeling as data and functions are separate. data and functions into objects.
Core Uses functions, subroutines, and Uses objects, classes, inheritance,
Concepts global variables. polymorphism, encapsulation, and abstraction.
Examples C, Pascal, FORTRAN, BASIC. Java, C++, Python, C#, Ruby.
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts
Class
In object-oriented programming, a class is a blueprint from which individual objects are created
(or, we can say a class is data type of an object type). In Java, everything is related to classes
and objects. Each class has its methods and attributes that can be accessed and manipulated
through the objects.
Examples of Class
1. public class Main
2. {
3. public static void main(String[] args) {
4. [Link]("Hello World");
5. }
6. }
7.
8. // create a Student class
9. public class Student {
10. // Declaring attributes
11. String name;
12. int rollNo;
13. String section;
14.
15. // initialize attributes
16. Student(String name, int rollNo, String section){
17. [Link]= name;
18. [Link] = rollNo;
19. [Link] = section;
20. }
21. // print details
22. public void printDetails() {
23. [Link]("Student Details:");
24. [Link]([Link]+ ", "+", " + [Link] + ", " + section);
25. }
26. }private static int MAX = 5;
27.
28. /// <summary>
29. /// Select this entire code block and
30. /// click to the "Format text as code"
31. /// to change the styling. We will use your style
32. /// preference when formatting.
33. /// </summary>
34. public void TestMethod()
35. {
36. // Try highlighting the line below.
37. // We will try to highlight using your highlighting preference.
38. [Link]("Select this line and click Highlight line button");
39. }
40.
Object
In object-oriented programming, an object is an entity that has two characteristics (states and
behavior). Some of the real-world objects are book, mobile, table, computer, etc. An object is a
variable of the type class, it is a basic component of an object-oriented programming system. A
class has the methods and data members (attributes), these methods and data members are
accessed through an object. Thus, an object is an instance of a class.
Example of Objects
1. // create a Student class
2. public class Student {
3. // Declaring attributes
4. String name;
5. int rollNo;
6. String section;
7.
8. // initialize attributes
9. Student(String name, int rollNo, String section){
10. [Link]= name;
11. [Link] = rollNo;
12. [Link] = section;
13. }
14. // print details
15. public void printDetails() {
16. [Link]("Student Details: ");
17. [Link]([Link]+ ", " + [Link] + ", " + section);
18. }
19.
20. public static void main(String[] args) {
21. // create student objects
22. Student student1 = new Student("Robert", 1, "IX Blue");
23. Student student2 = new Student("Adam", 2, "IX Red");
24. Student student3 = new Student("Julie", 3, "IX Blue");
25.
26. // print student details
27. [Link]();
28. [Link]();
29. [Link]();
30. }
31. }
32. Output
33. Student Details: Robert, 1, IX Blue
34. Student Details: Adam, 2, IX Red
35. Student Details: Julie, 3, IX Blue
36.
Inheritance
In object-oriented programming, inheritance is a process by which we can reuse the
functionalities of existing classes to new classes. In the concept of inheritance, there are two
terms base (parent) class and derived (child) class. When a class is inherited from another class
(base class), it (derived class) obtains all the properties and behaviors of the base class.
Example of Inheritance
1. // create a Student class
2. public class Student extends Person {
3. // Declaring attributes
4. int rollNo;
5. String section;
6.
7. // initialize attributes
8. Student(String name, int rollNo, String section){
9. super(name);
10. [Link] = rollNo;
11. [Link] = section;
12. }
13. // print details
14. public void printDetails() {
15. [Link]("Student Details: ");
16. [Link]([Link]+ ", " + [Link] + ", " + section);
17. }
18.
19. public static void main(String[] args) {
20. // create student objects
21. Student student1 = new Student("Robert", 1, "IX Blue");
22. Student student2 = new Student("Adam", 2, "IX Red");
23. Student student3 = new Student("Julie", 3, "IX Blue");
24.
25. // print student details
26. [Link]();
27. [Link]();
28. [Link]();
29. }
30. }
31. Output
32. Student Details: Robert, 1, IX Blue
33. Student Details: Adam, 2, IX Red
34. Student Details: Julie, 3, IX Blue
Polymorphism
The term "polymorphism" means "many forms". In object-oriented programming, polymorphism
is useful when you want to create multiple forms with the same name of a single entity. To
implement polymorphism in Java, we use two concepts method overloading and method
overriding.
The method overloading is performed in the same class where we have multiple methods with
the same name but different parameters, whereas, the method overriding is performed by using
the inheritance where we can have multiple methods with the same name in parent and child
classes.
Example of Polymorphism
1. // create a Student class
2. public class Student {
3. // Declaring attributes
4. String name;
5. int rollNo;
6. String section;
7.
8. // initialize attributes
9. Student(String name, int rollNo, String section){
10. [Link]= name;
11. [Link] = rollNo;
12. [Link] = section;
13. }
14. // print details
15. public void printDetails() {
16. [Link]("Student Details: ");
17. [Link]([Link]+ ", " + [Link] + ", " + section);
18. }
19.
20. // print details without section if required
21. public void printDetails(boolean hideSection) {
22. [Link]("Student Details: ");
23. [Link]([Link]+ ", " + [Link] + ", " + (hideSection ? "" : section));
24. }
25.
26. public static void main(String[] args) {
27. // create student objects
28. Student student1 = new Student("Robert", 1, "IX Blue");
29. Student student2 = new Student("Adam", 2, "IX Red");
30. Student student3 = new Student("Julie", 3, "IX Blue");
31.
32. // print student details
33. [Link]();
34. [Link](true);
35. [Link](false);
36. }
37. }
38. Output
39. Student Details: Robert, 1, IX Blue
40. Student Details: Adam, 2,
41. Student Details: Julie, 3, IX Blue
Abstraction
In object-oriented programming, an abstraction is a technique of hiding internal details and
showing functionalities. The abstract classes and interfaces are used to achieve abstraction in
Java.
The real-world example of an abstraction is a Car, the internal details such as the engine,
process of starting a car, process of shifting gears, etc. are hidden from the user, and features
such as the start button, gears, display, break, etc are given to the user. When we perform any
action on these features, the internal process works.
Example of Abstraction
1. abstract class Vehicle {
2. public void startEngine() {
3. [Link]("Engine Started");
4. }
5. }
6. public class Car extends Vehicle {
7. private String color;
8.
9. public Car(String color) {
10. [Link] = color;
11. }
12.
13. public void printDetails() {
14. [Link]("Car color: " + [Link]);
15. }
16.
17. public static void main(String[] args) {
18. Car car = new Car("White");
19.
20. [Link]();
21. [Link]();
22. }
23. }
24. Output
25. Car color: White
26. Engine Started
27.
28.
Encapsulation
In an object-oriented approach, encapsulation is a process of binding the data members
(attributes) and methods together. The encapsulation restricts direct access to important data.
The best example of the encapsulation concept is making a class where the data members are
private and methods are public to access through an object. In this case, only methods can
access those private data.
Example of Encapsulation
1. // create a Student class
2. public class Student {
3. // Declaring private attributes
4. private String name;
5. private int rollNo;
6. private String section;
7.
8. // initialize attributes
9. Student(String name, int rollNo, String section){
10. [Link]= name;
11. [Link] = rollNo;
12. [Link] = section;
13. }
14. // print details
15. public void printDetails() {
16. [Link]("Student Details: ");
17. [Link]([Link]+ ", " + [Link] + ", " + section);
18. }
19.
20. public static void main(String[] args) {
21. // create student objects
22. Student student1 = new Student("Robert", 1, "IX Blue");
23. Student student2 = new Student("Adam", 2, "IX Red");
24. Student student3 = new Student("Julie", 3, "IX Blue");
25.
26. // print student details
27. [Link]();
28. [Link]();
29. [Link]();
30. }
31. }
32. Output
33. Student Details: Robert, 1, IX Blue
34. Student Details: Adam, 2, IX Red
35. Student Details: Julie, 3, IX Blue
36.
37.
BENEFITS OF OOP (OBJECT-ORIENTED PROGRAMMING)
• By using objects and classes, you can create reusable components, leading to less
duplication and more efficient development.
• It provides a clear and logical structure, making the code easier to understand, maintain,
and debug.
• OOP supports the DRY (Don't Repeat Yourself) [Link] principle encourages
minimizing code repetition, leading to cleaner, more maintainable code. Common
functionalities are placed in a single location and reused, reducing redundancy.
• By reusing existing code and creating modular components, OOP allows for quicker and
more efficient application development
APPLICATIONS OF OOP
• Software development
• GUI development
• game development
• mobile app development
• web development
• database systems
• AI/ML
JAVA FEATURES
• Simple
• Object-Oriented
• Platform Independent
• Portable
• Secure
• Robust
• Multithreaded
• High Performance
• Distributed
• Dynamic
Java Development Environment
Java Development Environment (in simple terms):
• JDK (Java Development Kit) – Used to write and run Java programs
• JRE (Java Runtime Environment) – Used to run Java programs
• JVM (Java Virtual Machine) – Executes Java bytecode
• Compiler (javac) – Converts Java code into bytecode
• IDE (Integrated Development Environment) – Helps write, run, and debug code (e.g.,
Eclipse, IntelliJ)
COMMENTS
Comments are statements in a Java program that are not executed by the compiler.
They are used to explain the code, make it easy to understand, and help with documentation.
Types of Comments:
• Single-line comment (//) – Used for one line
• Multi-line comment (/* */) – Used for multiple lines
• Documentation comment (/** */) – Used to generate JavaDoc
Uses:
• Improves readability
• Helps in understanding and maintaining code
DATA TYPES
Java Data Types
Primitive Data Types
1. byte – Stores small whole numbers
2. byte b = 10;
3. short – Stores larger whole numbers than byte
4. short s = 200;
5. int – Stores whole numbers
6. int a = 1000;
7. long – Stores very large whole numbers
8. long l = 50000L;
9. float – Stores decimal numbers
10. float f = 5.5f;
11. double – Stores large decimal numbers
12. double d = 99.99;
13. char – Stores a single character
14. char c = 'A';
15. boolean – Stores true or false
16. boolean isJavaFun = true;
17.
Non-Primitive Data Types
1. String – Stores a sequence of characters
2. String name = "Java";
3. Array – Stores multiple values of same type
4. int[] numbers = {1, 2, 3};
5. Class – Blueprint for creating objects
6. class Student { }
7. Object – Instance of a class
8. Student s1 = new Student();
9. Interface – Used to achieve abstraction
10. interface Test { }
11.
VARIABLES
A variable in Java is a container used to store data.
Each variable has:
• a data type
• a name
• a value
Syntax
1. dataType variableName = value;
Example:
1. int age = 15;
2.
Rules for Naming Variables
• Must start with a letter, _ or $
• Cannot start with a number
• No spaces allowed
• Cannot use Java keywords
• Should be meaningful (camelCase is preferred)
Valid: marks, _count, totalSum
Invalid: 1num, class, total marks
Types of Variables in Java
1. Local Variable
• Declared inside a method
• Used only within that method
• Must be initialized before use
Example:
1. class Test {
2. void show() {
3. int x = 10; // local variable
4. [Link](x);
5. }
6. }
7.
2. Instance Variable
• Declared inside a class but outside methods
• Each object has its own copy
• Default values are provided by Java
Example:
1. class Student {
2. int rollNo; // instance variable
3. String name;
4.
5. void display() {
6. [Link](rollNo + " " + name);
7. }
8. }
9.
3. Static Variable (Class Variable)
• Declared using static
• Shared by all objects of the class
• Memory allocated only once
Example:
1. class School {
2. static String schoolName = "ABC School";
3. }
4.
Variable Initialization
Declaration only
1. int a;
Declaration with initialization
1. int a = 5;
Example Program Using All Variable Types
1. class Example {
2. static int count = 10; // static variable
3. int number = 5; // instance variable
4.
5. void display() {
6. int x = 2; // local variable
7. [Link](x + number + count);
8. }
9.
10. public static void main(String[] args) {
11. Example obj = new Example();
12. [Link]();
13. }
14. }
15.
JAVA OPERATORS
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-
primitive data types.
1. int a = 10, b = 5;
2. [Link](a + b);
3. [Link](a - b);
4. [Link](a * b);
5. [Link](a / b);
6. [Link](a % b);
2. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and less than.
They return boolean results after the comparison and are extensively used in looping
statements as well as conditional if-else statements.
1. int a = 10, b = 5;
2. [Link](a == b);
3. [Link](a != b);
4. [Link](a > b);
5. [Link](a < b);
6. [Link](a >= b);
7. [Link](a <= b);
3. Logical Operators
Logical Operators are used to perform "logical AND" and "logical OR" operations, similar to
AND gate and OR gate in digital electronics. They have a short-circuiting effect, meaning the
second condition is not evaluated if the first is false.
1. boolean x = true, y = false;
2. [Link](x && y);
3. [Link](x || y);
4. [Link](!x);
4. Assignment Operators
The assignment operator assigns a value from the right-hand side to a variable on the left.
Since it has right-to-left associativity, the right-hand value must be declared or constant.
1. int a = 10;
2. a += 5;
3. a -= 2;
4. a *= 2;
5. a /= 2;
5. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate a
value.
1. int a = 10;
2. [Link](++a);
3. [Link](a--);
6. Bitwise Operators
These operators perform operations at the bit level.
• Bitwise Operators manipulate individual bits using AND, OR, XOR, and NOT.
• Shift Operators move bits to the left or right, effectively multiplying or dividing by powers
of two.
1. int a = 5, b = 3;
2. [Link](a & b);
3. [Link](a | b);
4. [Link](a ^ b);
5. [Link](~a);
7. Shift Operators
1. int a = 10;
2. [Link](a << 2);
3. [Link](a >> 2);
8. Ternary Operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands and
hence the name Ternary. The general format is,
1. int a = 10, b = 20;
2. int min = (a < b) ? a : b;
3. [Link](min);
9. instanceof Operator
The instanceof operator is used for type checking. It can be used to test if an object is an
instance of a class, a subclass, or an interface. The general format,
1. String s = "Java";
2. [Link](s instanceof String);
10. Logical AND, OR using integers
1. int a = 10, b = 20, c = 30;
2. [Link](a < b && b < c);
3. [Link](a > b || b < c);
DECISION MAKING BRANCHING AND LOOPING
(REFER THE PPT CONTENT)
1. Decision Making Statements
Used to execute code based on a condition.
a) if Statement
Executes a block if the condition is true.
1. int age = 18;
2. if (age >= 18) {
3. [Link]("You can vote");
4. }
b) if-else Statement
Executes one block if true, another if false.1.
1. int marks = 50;
2. if (marks >= 35) {
3. [Link]("Pass");
4. } else {
5. [Link]("Fail");
6. }
c) if-else-if Ladder
Checks multiple conditions.
1. int marks = 75;
2. if (marks >= 90) {
3. [Link]("Grade A");
4. } else if (marks >= 75) {
5. [Link]("Grade B");
6. } else {
7. [Link]("Grade C");
8. }
d) switch Statement
Selects a block based on value of a variable.
1. int day = 3;
2. switch(day) {
3. case 1: [Link]("Monday"); break;
4. case 2: [Link]("Tuesday"); break;
5. case 3: [Link]("Wednesday"); break;
6. default: [Link]("Other day");
7. }
2. Branching Statements
Used to change the flow of loops or statements.
1. break – Exits loop/switch immediately
2. for (int i = 1; i <= 5; i++) {
3. if (i == 3) break;
4. [Link](i);
5. }
6. continue – Skips current iteration of loop
7. for (int i = 1; i <= 5; i++) {
8. if (i == 3) continue;
9. [Link](i);
10. }
11. return – Exits from method immediately
12. int square(int n) {
13. return n * n;
14. }
3. Looping Statements
Used to repeat a block of code multiple times.
a) for Loop
1. Repeats when number of iterations is known.
2. for (int i = 1; i <= 5; i++) {
3. [Link](i);
4. }
b) while Loop
Repeats while condition is true.
1. int i = 1;
2. while (i <= 5) {
3. [Link](i);
4. i++;
5. }
c) do-while Loop
Executes at least once and then checks condition.
1. int i = 1;
2. do {
3. [Link](i);
4. i++;
5. } while (i <= 5);
ARRAYS
• Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the
[Link] class. This allows you to invoke methods defined in Object (such as
toString(), equals() and hashCode()).
• Arrays have a built-in length property, which provides the number of elements in the
array
• An array is a container that holds a fixed number of values of the same data type.
It allows you to store multiple values using a single variable name.
1. Characteristics of Arrays
• Fixed size (length cannot be changed after creation)
• All elements must be of the same data type
• Stored in contiguous memory locations
• Indexed starting from 0
2. Types of Arrays
1. Single-Dimensional Array – A simple list of elements.
2. Multi-Dimensional Array – Arrays of arrays (e.g., 2D arrays).
3. Declaring and Creating Arrays
a) Single-Dimensional Array
1. Declaration
2. int[] numbers;
3. or
4. int numbers[];
5. Creating Array
6. numbers = new int[5]; // array of 5 integers
7. Initializing Array
8. numbers[0] = 10;
9. numbers[1] = 20;
10. numbers[2] = 30;
11. numbers[3] = 40;
12. numbers[4] = 50;
13. Or declare and initialize together
14. int[] numbers = {10, 20, 30, 40, 50};
15.
b) Multi-Dimensional Array
1. 2D Array Declaration
2. int[][] matrix = new int[2][3]; // 2 rows, 3 columns
3. Initialization
4. matrix[0][0] = 1;
5. matrix[0][1] = 2;
6. matrix[0][2] = 3;
7. matrix[1][0] = 4;
8. matrix[1][1] = 5;
9. matrix[1][2] = 6;
10. Or declare and initialize together
11. int[][] matrix = {
12. {1, 2, 3},
13. {4, 5, 6}
14. };
4. Accessing Array Elements
• Use index number to access elements
1. int first = numbers[0]; // 10
2. numbers[1] = 25; // update element at index 1
• Length of array:
1. int size = [Link];
5. Looping through Arrays
1. int[] arr = {10, 20, 30, 40, 50};
2. for(int i = 0; i < [Link]; i++) {
3. [Link](arr[i]);
4. }
5. Using enhanced for loop
6. for(int num : arr) {
7. [Link](num);
8. }
1. Two-Dimensional Array
2. int[][] matrix = {{1,2,3},{4,5,6}};
3. for(int i = 0; i < [Link]; i++) {
4. for(int j = 0; j < matrix[i].length; j++) {
5. [Link](matrix[i][j] + " ");
6. }
7. [Link]();
8. }
9.
7. Important Notes
• Arrays are objects in Java
• Default values for array elements:
o int → 0
o double → 0.0
o boolean → false
o Object → null
EXAMPLE PROGRAM
1. Example Program
2. public class ArrayExample {
3. public static void main(String[] args) {
4. int[] numbers = {10, 20, 30, 40, 50};
5.
6. [Link]("Array Elements:");
7. for(int i = 0; i < [Link]; i++) {
8. [Link](numbers[i]);
9. }
10.
11. // 2D Array
12. int[][] matrix = {{1,2,3},{4,5,6}};
13. [Link]("2D Array Elements:");
14. for(int i = 0; i < [Link]; i++) {
15. for(int j = 0; j < matrix[i].length; j++) {
16. [Link](matrix[i][j] + " ");
17. }
18. [Link]();
19. }
20. }
21. }
22.
23.
STRINGS IN JAVA
A String in Java is a sequence of characters.
It is used to store text and is treated as an object of the String class.
1. Creating Strings
a) Using String Literal
String str1 = "Hello";
• Stored in the String pool.
• If the same value exists, no new object is created.
b) Using new Keyword
String str2 = new String("Hello");
• Creates a new object in heap memory every time.
2. String Characteristics
• Immutable: Once created, cannot be changed.
• Can store any combination of letters, numbers, symbols.
• Supports various methods for manipulation.
3. Common String Methods
Method Description Example
length() Returns length of string "Hello".length() → 5
charAt(index) Returns character at given index "Hello".charAt(1) → 'e'
concat(String s) Concatenates two strings "Hi".concat(" Java") → "Hi Java"
equals(String s) Checks equality of strings "Hi".equals("Hi") → true
equalsIgnoreCase(s) Ignores case while comparing "hi".equalsIgnoreCase("HI") → true
toUpperCase() Converts to uppercase "hello".toUpperCase() → "HELLO"
toLowerCase() Converts to lowercase "HELLO".toLowerCase() → "hello"
substring(start, end) Extracts substring "Hello".substring(1,4) → "ell"
trim() Removes leading/trailing spaces " Java ".trim() → "Java"
replace(old, new) Replaces characters "Hello".replace('l','p') → "Heppo"
contains(s) Checks if string contains substring "Hello".contains("ll") → true
4. String Comparison
1. String str1 = "Java";
2. String str2 = "Java";
3. String str3 = new String("Java");
4.
5. // Compare values
6. [Link]([Link](str3)); // true
7.
8. // Compare references
9. [Link](str1 == str3); // false
5. String Concatenation
1. String first = "Hello";
2. String second = "World";
3. String result = first + " " + second; // "Hello World"
6. String Immutability
1. Strings cannot be changed after creation.
2. String str = "Hello";
3. [Link](" World"); // "Hello" remains unchanged
4. [Link](str); // Output: Hello
5. To modify, reassign to a new string
6. str = [Link](" World");
7. [Link](str); // Output: Hello World
7. Example Program
1. public class StringExample {
2. public static void main(String[] args) {
3. String str = "Java Programming";
4.
5. [Link]("Original String: " + str);
6. [Link]("Length: " + [Link]());
7. [Link]("Uppercase: " + [Link]());
8. [Link]("Substring: " + [Link](5, 16));
9. [Link]("Contains 'Java': " + [Link]("Java"));
10.
11. String str2 = [Link]("Java", "Python");
12. [Link]("After replace: " + str2);
13. }
14. }
15. Output:
16. Original String: Java Programming
17. Length: 16
18. Uppercase: JAVA PROGRAMMING
19. Substring: Programming
20. Contains 'Java': true
21. After replace: Python Programming