0% found this document useful (0 votes)
48 views212 pages

BSCS 7th Java 3

Java provides security through various features like sandboxing with the JVM, lack of pointers, bytecode verification, security APIs, and exception handling. It also allows portability through platform independence, standardized APIs, and garbage collection. A basic "Hello World" Java program demonstrates creating a class with a main method that prints output to the console.

Uploaded by

m.saadbaloch4892
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views212 pages

BSCS 7th Java 3

Java provides security through various features like sandboxing with the JVM, lack of pointers, bytecode verification, security APIs, and exception handling. It also allows portability through platform independence, standardized APIs, and garbage collection. A basic "Hello World" Java program demonstrates creating a class with a main method that prints output to the console.

Uploaded by

m.saadbaloch4892
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 212

BSCS-7th

Advance OOP(Java)
Week – 1

Introduction of Java
Security In Java Programs
• Java is the most popular object-oriented
programming language. It provides a variety of
salient features that are preferred by the
developers. It is the reason that a billion of
devices runs on Java. In this section, we are
going to discuss why Java is secure.
Java is secure due to the following reasons:
• Java programs run inside a virtual machine which is
known as a sandbox.
• Java does not support explicit pointer.
• Byte-code verifier checks the code fragments for illegal
code that can violate access right to object.
• It provides java.security package implements explicit
security.
• It provides library level safety.
• Run-time security check takes place when we load new
code.
• Java provides some other features that make Java
more secure.
Java provides some other features that
make Java more secure.
• JVM
• Security API's
• Security Manager
• Auto Memory Management
• No Concept of Pointers
• Compile-time Checking
• Cryptographic Security
• Java Sandbox
• Exception Handling
• ClassLoader
JVM
• JVM plays a vital role to provide security. It
verifies the byte-code. The JVM provides
guarantees that there is no unsafe operation
going to execute. It also helps to diminish the
possibilities of the programmers who suffer
from memory safety flaws.
Security API's

• Java class libraries provide several API that


leads to security. These APIs contain
cryptographic algorithms and authentication
protocols that lead to secure communication.
Byte Code

• Every time when a user compiles the Java


program, the Java compiler creates a class file
with Bytecode, which are tested by the JVM at
the time of program execution for viruses and
other malicious files.
Security Manager

• The security manager is responsible for


checking the permissions and properties of
the classes. It monitors the system resources
accessed by the authorized classes. It also
controls socket connections.
No Concept of Pointers
• Java does not provide support for pointers
concept. It is the main security features of
Java. The use of pointers may lead to
unauthorized read or write operations.
Therefore, the user cannot point to any
memory locations.
Memory Management
• Java automatically manages memory which is
known as garbage collection. The JVM
manages memory itself. Hence, there are
limited chances of fault in memory
management.
Compile-time checking
• Compile-time checking also makes the Java
secure. Consider a scenario in which an
unauthorized method is trying to access the
private variable, in this case, the JVM gives the
compile-time error. It prevents the system
from the crash.
Cryptographic Security
• Java provides a class named
java.secrurity.SourceCode that also provides
security. If we get code from other sources, we
should check from where the code is coming.
The class maintains the source information
and provides guarantees to keep a digital
signature and cryptographic security.
Java Sandbox
• Java Sandbox is a major component of security
consideration. It is a restricted area where
applets are run. Java does not provide system
resources without check if an applet is to be
run.
Exception Handling – Code Level Security

• The exception handling feature adds more


security in Java. The feature reports the error
to the programmer during the runtime. The
code will not run until the programmer will
not rectify it.
Java ClassLoader

• There are a number of class loaders present in


JVM. It provides and maintains namespaces
for specific classes. The advantage of the
ClassLoader is that the untrusted classes
would not behave like a trusted one.
Portability

• A program is said to be portable if it can be made


to run on many different kinds of computers.
• Portability is good because the programmer can
concentrate all effort on just a single version of
the program.
• While a program in a high-level language can be
compiled for different kinds of computers, the
resulting machine language program can run on
only one kind of computer.
Portability
• Java is portable because it facilitates you to
carry the Java bytecode to any platform. It
doesn't require any implementation.
• Portability in Java refers to the ability of Java
programs to run on different platforms
without modification.
Portability
• Java achieves portability through the following
mechanisms:
• 1. Platform-Independence.
• 2. Write Once, Run Anywhere (WORA)
• 3. Standardized APIs
• 4. Class Libraries
• 5. Garbage Collection
Portability: Platform-Independence
• Java programs are compiled into an
intermediate form called bytecode. This
bytecode is not specific to any particular
hardware or operating system.
• Java Virtual Machine (JVM) is responsible for
interpreting and executing the bytecode. Each
platform has its own JVM implementation,
which allows Java programs to run on various
platforms without modification.
Portability: Write Once, Run Anywhere
(WORA)
• The famous Java slogan, "Write Once, Run
Anywhere," emphasizes the idea that you can
write your code on one platform and run it on
any other platform with a compatible JVM.
• Developers can write Java code on one
operating system and distribute the compiled
bytecode to users on different platforms.
Portability: Standardized APIs
• Java provides a set of standardized APIs
(Application Programming Interfaces) for
common tasks such as file I/O, networking,
and user interface development.
• These APIs ensure that Java programs can
interact with the underlying system in a
consistent manner, regardless of the specific
operating system.
Portability: Class Libraries
• Java comes with a rich set of class libraries
that provide pre-built functionality for various
tasks.
• These libraries abstract the underlying
platform-specific details, making it easier for
developers to create portable applications.
Portability: Garbage Collection
• Java's automatic garbage collection helps manage
memory efficiently.
• Developers don't need to deal with memory
allocation and deallocation explicitly, reducing
the chances of platform-specific memory issues.
• If a developer perform allocation and
deallocation explicitly in a persistent manner
then it will be more good for Garbage collection.
Portability: Security Model
• Java's security model adds another layer of
portability by providing a secure execution
environment.
• Applets, for example, can be downloaded and
executed securely on different platforms.
Portability: Bytecode Verification
• Before executing bytecode, the JVM performs
bytecode verification to ensure that it adheres
to the Java language specifications.
• This verification process contributes to the
stability and security of Java applications
across platforms.
Hello world program In Java
• The "Hello, World!" program is a simple and
traditional way to demonstrate the basic
syntax of a programming language.
Hello world program In Java
• Here's a simple "Hello, World!" program in
Java.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Hello world program In Java: Explanation
• public class HelloWorld: This declares a class named HelloWorld. In Java,
every application must contain at least one class.

• public static void main(String[] args): This is the main method, which is
the entry point of a Java program. When you run a Java application, the
Java Virtual Machine (JVM) starts by executing the main method. It takes
an array of strings (args) as parameters, although we are not using them
in this simple example.

• System.out.println("Hello, World!");: This line prints the string "Hello,


World!" to the console. The System.out.println method is used to display
output in the console. The println method adds a newline character after
printing the message, so the next output appears on a new line.
Requirement for Java Hello World Example

• For executing any Java program, the following


software or application must be properly
installed.
1. Install the JDK if you don't have installed it,
download the JDK and install it.
2. Set path of the jdk/bin directory. (http://
www.javatpoint.com/how-to-set-path-in-java)
3. Create the Java program
4. Compile and run the Java program
To run this program
• Write the code in a text editor and save it with the
name HelloWorld.java.
• Open a command prompt or terminal window.
• Navigate to the directory where you saved
HelloWorld.java.
• Compile the program by typing javac
HelloWorld.java and pressing Enter.
• Run the compiled program using java HelloWorld.
You should see the output "Hello, World!" displayed
on the console.
C++ vs Java

• There are many differences and similarities


between the C++ programming language and
Java
Comparison C++ Java
Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for system programming. Java is mainly used for application programming. It is
widely used in Windows-based, web-based,
enterprise, and mobile applications.
C++ vs Java
Design Goal C++ was designed for systems and applications prog Java was designed and created as an interpreter for
ramming. It was an extension of the C programming printing systems but later extended as a support
language.
network computing. It was designed to be easy to use
and accessible to a broader audience.

Goto C++ supports the goto statement. Java doesn't support the goto statement.

Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance through class.
It can be achieved by using interfaces in java.
Inheritance

Operator C++ supports operator overloading. Java doesn't support operator overloading.
Overloading
Pointers C++ supports pointers. You can write a pointer progr Java supports pointer internally. However, you can't
am in C++. write the pointer program in java. It means java has
restricted pointer support in java.
C++ vs Java
Compiler and C++ uses compiler only. C++ is compiled and run using Java uses both compiler and interpreter. Java source code
Interpreter the compiler which converts source code into is converted into bytecode at compilation time. The
machine code so, C++ is platform dependent. interpreter executes this bytecode at runtime and
produces output. Java is interpreted that is why it is
platform-independent.

Call by Value and Call C++ supports both call by value and call by reference. Java supports call by value only. There is no call by
by reference reference in java.

Structure and Union C++ supports structures and unions. Java doesn't support structures and unions.

Thread Support C++ doesn't have built-in support for threads. It relies Java has built-in thread support.
on third-party libraries for thread support.

Documentation C++ doesn't support documentation comments. Java supports documentation comment (/** ... */) to
Comment create documentation for java source code.

Virtual Keyword C++ supports virtual keyword so that we can decide Java has no virtual keyword. We can override all non-static
whether or not to override a function. methods by default. In other words, non-static methods
are virtual by default.
C++ vs Java
unsigned right shift C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator that
>>> fills zero at the top for the negative numbers. For
positive numbers, it works same like >> operator.

Inheritance Tree C++ always creates a new inheritance tree. Java always uses a single inheritance tree because all class
es are the child of the Object class in Java. The Object clas
s is the root of the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with hardware.

Object-oriented C++ is an object-oriented language. However, in Java is also an object-oriented language. However, everyt
the C language, a single root hierarchy is not hing (except fundamental types) is an object in Java. It is a
single root hierarchy as everything gets derived from
possible. java.lang.Object.
Week – 2, 3 & 4

Java building blocks


Built in data types
• Built-in data types are types that are built-in
to a language implementation.
• There are two main categories of data types:
a. Primitive data types
b. Non-Primitive / Reference data types.
Primitive Data Types
• Primitive data types are the most basic data
types in Java. They are predefined by the
language and are not composed of other data
types.
• Java has eight primitive data types:
• Integer Types:
• byte: 8-bit signed integer
• short: 16-bit signed integer
Primitive Data Types
• int: 32-bit signed integer
• long: 64-bit signed integer
• Floating-Point Types:
• float: 32-bit floating-point
• double: 64-bit floating-point
• Character Type:
• char: 16-bit Unicode character
Primitive Data Types
• Boolean Type:
• boolean: Represents true or false values
Non-Primitive / Reference Data Types
• These are user-defined.
• They used to store references (memory addresses) to
objects.
• They include:
• Class Types:
– Custom user-defined data types created using classes.
• Interface Types:
– Similar to classes but represent a set of abstract methods.
• Array Types:
– Ordered collections of elements of the same or different types.
Non-Primitive / Reference Data Types
• Enumeration Types:
– A special data type used to define collections of
constants.
• Other Reference Types:
– Various other types like String, which is a
sequence of characters, and other classes
provided by Java libraries.
Literals

• In Java, a literal represents a fixed value that can


be assigned to a variable.
• Literals are compile-time constants, and their
values cannot be changed during program
execution.
• Java supports various types of literals for
different data types, including integers, floating-
point numbers, characters, booleans, and strings.
• Here are some examples of literals in Java:
Literals
• Integer Literals:
– Decimal: `int decimal = 42;`
– Octal (prefix with 0): `int octal = 052;`
– Hexadecimal (prefix with 0x or 0X):`int hex = 0x2A;`
– Binary (Java 7 and later, prefix with 0b or 0B):
`int binary = 0b101010;`
• Floating-Point Literals:
– `double myDouble = 3.14;`
– `float myFloat = 2.71828f;` // Note the 'f' suffix for float
literals
Literals
• Character Literals:
– Single character: `char myChar = 'A';`
– Unicode character:
`char unicodeChar = '\u0041'; `// Unicode for
'A'
• Boolean Literals:
– `boolean myBoolean = true;`
• String Literals:
– `String myString = "Hello, World!";`
Literals
• Null Literal:
– `Object myObject = null;`
• Escape Sequences in Strings:
– `String escapeSequence = "This is a newline:\
nSecond line\tTabbed text";`
Naming Conventions

• Naming conventions are important for writing


clean and readable code.
• Naming Conventions are not enforced by the
Java compiler but are widely adopted by the
Java community.
• They help make your code more understandable
to others and follow a consistent style.
Here are some common naming conventions in
Java:
Naming Conventions
• Packages:
– Package names are usually in lowercase letters. For example:
com.example.myproject.
• Classes:
– Class names should start with an uppercase letter and follow
CamelCase. For example: MyClass, EmployeeDetails.
• Interfaces:
– Interface names should also start with an uppercase letter and
follow CamelCase. For example: MyInterface, Drawable.
• Methods:
– Method names should start with a lowercase letter and follow
CamelCase. For example: calculateTotal(), getEmployeeDetails().
Naming Conventions
• Variables:
– Variable names should start with a lowercase letter and follow
CamelCase. For example: myVariable, totalAmount.
• Constants:
– Constant names should be in uppercase letters with underscores
separating words. For example: MAX_SIZE, PI_VALUE.
• Enums:
– Enum names should be in uppercase letters, and enum constants should
be in uppercase letters with underscores. For example:

enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Naming Conventions
• Packages, Classes, and Methods for Beans (JavaBeans):
• Follow the conventions for classes and methods. Additionally, include getter
and setter methods with appropriate names. For example:

public class Person {


private String name;
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}
}
Naming Conventions
• Booleans:
– Use names that sound like a yes/no question for boolean variables or
methods. For example: isAvailable(), hasPermission.
• Acronyms and Abbreviations:
– Acronyms and abbreviations should be in uppercase or lowercase
consistently. For example: URL, xmlParser, HTTPConnection.
• Class Members:
– Class member (field) names should be descriptive and follow
camelCase. Avoid using single-letter names unless for a temporary
variable (e.g., in a loop).
• Indentation and Spacing:
– Use consistent indentation (usually four spaces) and add spaces
around operators to improve code readability.
Control Structures

• Control structures in Java are constructs that allow


you to control the flow of execution in a program.
• These control structures allow you to create flexible
and dynamic programs by controlling the order and
conditions under which different parts of your code
are executed.
• Java provides several types of control structures,
including conditional statements and loops.
Here's an overview of the main control structures in
Java:
Control Structures
• Conditional Statements:
• if Statement: An if statement is a selection statement that allows more than one possible flow
of control.
• Example:
if (condition) {
// code to be executed if the condition is true
}
if-else Statement: The if/else statement executes a block of code if a specified condition is true. If
the condition is false, another block of code can be executed.
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Control Structures
• if-else if-else Statement: The if...else statement executes a
statement if a specified condition is truthy. If the condition is falsy,
another statement in the optional else clause will be executed.
• Example:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if none of the conditions are true
}
Control Structures
• switch Statement: A switch statement is a control statement that executes a set of
logic based on the result of a comparison between a controlling expression and the
labels specified in the switch block.
• Example:
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
// ... additional cases
default:
// code to be executed if none of the cases match
}
Control Structures
• Loops:
• for Loop: For loop is a programming language conditional iterative statement
which is used to check for certain conditions and then repeatedly execute a
block of code as long as those conditions are met.
• Example:
for (initialization; condition; update) {
// code to be repeated as long as the condition is true
}
• while Loop: The while loop checks the condition/expression before the block
is executed, the control structure is often also known as a pre-test loop.
• Example:
• while (condition) {
• // code to be repeated as long as the condition is true
• }
Control Structures
• do-while Loop: In a do-while loop, it executes the
body of the loop and then validates the condition or
test expression. It is also called an entry-controlled
loop. It is also called an exit-controlled loop.
• Example:
do {
// code to be executed at least once, then repeated
as long as the condition is true
} while (condition);
Control Structures
• Transfer Statements:
• break Statement:
• Used to exit a loop or switch statement.
• Example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exit the loop when i is 5
}
// other code
}
Control Structures
• continue Statement:
• Skips the rest of the loop's code and continues with the
next iteration.
Example:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
// code to be executed for odd numbers
}
Control Structures
• return Statement:
• Exits a method and optionally returns a value.
• Example:
public int add(int a, int b) {
return a + b; // exit the method and return
the sum of a and b
}
Week – 5 & 6

Arrays & Strings


Arrays
• In Java, an array is a data structure that allows you to
store multiple values of the same type under a single
variable name , instead of declaring separate
variables for each value.
• Arrays provide a way to work with collections of data
efficiently.
• Array is a group of like-typed variables referred to by
a common name.
• Arrays in Java work differently than they do in C/C++.
Here are the key aspects of arrays in Java:
Arrays: Important points about Java
arrays.
• In Java, all arrays are dynamically allocated.
• Arrays may be stored in contiguous memory [consecutive
memory locations].
• Since arrays are objects in Java, we can find their length using
the object property length. This is different from C/C++, where
we find length using sizeof.
• A Java array variable can also be declared like other variables
with [] after the data type.
• The variables in the array are ordered, and each has an index
beginning with 0.
• Java array can also be used as a static field, a local variable, or a
method parameter.
Arrays: Declaration and Initialization
• Declaration: To declare an array, you specify
the type of its elements and the array's name,
followed by square brackets ([]).
• For example:
int[] myArray;
// Declaration of an integer array
Arrays: Declaration and Initialization
• Initialization: Arrays can be initialized at the time of
declaration or later. Initialization involves specifying
the size of the array and providing values for its
elements.
• For example:
int[] myArray = new int[5];
// Initialization with a size of 5
• OR
int[] myArray = {1, 2, 3, 4, 5};
// Initialization with values
Arrays: Accessing Array Elements

• Array elements are accessed using their index.


The index starts from 0 for the first element.
• For example:
• int[] myArray = {10, 20, 30, 40, 50};
• int firstElement = myArray[0];
// Accessing the first element (10)
• int thirdElement = myArray[2];
// Accessing the third element (30)
Arrays: Array Length

• The length of an array (i.e., the number of


elements it can hold) can be obtained using
the length property.
• For example:
int[] myArray = {10, 20, 30, 40, 50};
int arrayLength = myArray.length;
// Length of the array (5)
Arrays: Iterating Through an Array

• You can use loops to iterate through the


elements of an array.
• For example, using a for loop:
int[] myArray = {10, 20, 30, 40, 50};
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
One dimensional & multidimensional array

• In Java, arrays can be categorized into one-dimensional arrays


and multidimensional arrays, each serving different purposes.
• the choice between one-dimensional and multidimensional
arrays depends on the nature of the data you are working
with and the requirements of your program.
One-Dimensional Array:
• A one-dimensional array is a simple linear array where
elements are stored in a single line. It is declared and
initialized as follows:
// Declaration and initialization of a one-dimensional array
int[] myArray = {1, 2, 3, 4, 5};
One dimensional & multidimensional array

• Accessing elements in a one-dimensional array is done using


their index:
int firstElement = myArray[0];
// Accessing the first element
int thirdElement = myArray[2];
// Accessing the third element

• Iterating through a one-dimensional array is often done using


loops, such as a for loop:
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
One dimensional & multidimensional array

• Multidimensional Array:
• A multidimensional array is an array of arrays.
• Multidimensional arrays are useful for representing tables, matrices,
and other complex data structures.
• The most common type is a two-dimensional array, but you can have
three-dimensional arrays and beyond. Here's an example of a two-
dimensional array:
// Declaration and initialization of a two-dimensional array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
One dimensional & multidimensional array

• Accessing elements in a two-dimensional array involves using


two indices:
int elementAtRow2Column3 = matrix[1][2];
// Accessing element at row 1, column 2
Iterating through a two-dimensional array requires nested loops:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
In the above example, matrix.length gives the number of rows, and
matrix[i].length gives the number of columns in the ith row.
One dimensional & multidimensional array

• Three-Dimensional Array:
• The concept extends to three-dimensional arrays
and beyond. Here's an example of a three-
dimensional array:
// Declaration and initialization of a three-dimensional array
int[][][] threeDArray = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}},
{{9, 10}, {11, 12}}
};
One dimensional & multidimensional array

• Accessing elements in a three-dimensional


array involves using three indices:
int elementAtCoordinates = threeDArray[1][0][1];
// Accessing element at depth 1, row 0, column 1
• Iterating through a three-dimensional array
requires nested loops for each dimension.
Sorting & searching

• In Java, sorting and searching are common operations


performed on arrays and collections. Java provides
built-in methods and algorithms to facilitate these
operations.
• Sorting:
• Arrays:
• Arrays.sort() Method:
– The Arrays class in Java provides a sort() method for sorting
arrays of primitive types or objects. For example:
int[] myArray = {5, 2, 8, 1, 3};
Arrays.sort(myArray);
Sorting & searching

• Comparable Interface:
• For custom objects, you can implement the Comparable interface and
override the compareTo() method to define the sorting order.
• For example:
public class MyClass implements Comparable<MyClass> {
// ...

@Override
public int compareTo(MyClass other) {
// Compare logic goes here
}
}
– Then, you can use Arrays.sort() or Collections.sort() for arrays or lists of
custom objects.
Sorting & searching

• Lists:
• Collections.sort() Method:
– The Collections class provides a sort() method for sorting
lists. For example:
List<Integer> myList = Arrays.asList(5, 2, 8, 1, 3);
Collections.sort(myList);
• Comparator Interface:
• For custom objects, you can implement the
Comparator interface and pass it as an argument to
Collections.sort() for custom sorting logic.
Sorting & searching

• Searching:
• Arrays:
• Arrays.binarySearch() Method:
– The Arrays class provides a binarySearch() method
for searching in sorted arrays. The array must be
sorted before using this method.
int[] myArray = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(myArray, 3);
Sorting & searching

• Lists:
• Collections.binarySearch() Method:
– Similar to Arrays.binarySearch(), the Collections class
provides a binarySearch() method for searching in
sorted lists.
• Lists:
• Collections.binarySearch() Method:
– Similar to Arrays.binarySearch(), the Collections class
provides a binarySearch() method for searching in
sorted lists.
Sorting & Searching

• Custom Searching:
• Implementing Your Search Logic:
– If the data is not sorted or you need a custom
search logic, you can iterate through the array or
list and implement your own search algorithm.
Sorting & Searching

• Example:
• Here's a simple example combining sorting and searching:

mport java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortingAndSearchingExample {


public static void main(String[] args) {
// Sorting arrays
int[] myArray = {5, 2, 8, 1, 3};
Arrays.sort(myArray);

// Searching in arrays
int indexInArray = Arrays.binarySearch(myArray, 3);

// Sorting lists
List<Integer> myList = Arrays.asList(5, 2, 8, 1, 3);
Collections.sort(myList);

// Searching in lists
int indexInList = Collections.binarySearch(myList, 3);

// Print results
System.out.println("Sorted Array: " + Arrays.toString(myArray));
System.out.println("Index of 3 in the sorted array: " + indexInArray);

System.out.println("Sorted List: " + myList);


System.out.println("Index of 3 in the sorted list: " + indexInList);
}
}
Strings
• In Java, strings are objects that represent sequences of
characters. The String class in Java is part of the java.lang
package and provides numerous methods for working
with strings.
• strings in Java are versatile and come with a variety of
methods for manipulation and analysis.
• Understanding their immutability and choosing the
appropriate class for your use case is important for
efficient string handling in Java.
• Here are some key aspects of working with strings in
Java:
Strings : Declaring and Initializing Strings:

• String Literal:
Strings can be created using string literals,
enclosed in double quotes.
String greeting = "Hello, World!";
• String Object:
You can create a string object using the new
keyword.
String dynamicString = new String("Dynamic
String");
Strings : Common Operations with Strings:

• Concatenation:
Strings can be concatenated using the + operator.
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
• Length:
The length() method returns the number of characters
in a string.
String text = "Java Programming";
int length = text.length(); // length is 17
Strings : Common Operations with Strings

• Accessing Characters:
Individual characters in a string can be accessed
using the charAt() method.
char firstChar = text.charAt(0); // firstChar is 'J'
• Substring:
The substring() method extracts a portion of a
string.
String substring = text.substring(5, 14);
// "Programmi"
Strings : Common Operations with Strings

• Concatenating Strings:
The concat() method can be used to concatenate two strings.
String result = firstName.concat(" ").concat(lastName);
• Comparing Strings:
String comparison can be done using equals() or
equalsIgnoreCase() methods.
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // false
boolean isIgnoreCaseEqual = str1.equalsIgnoreCase(str2);
// true
Strings : Common Operations with Strings

• Converting Case:
Strings can be converted to uppercase or lowercase.
String uppercase = text.toUpperCase();
String lowercase = text.toLowerCase();
• String Immutability:
Strings in Java are immutable, meaning their values cannot be changed
after they are created. Operations on strings create new strings rather
than modifying existing ones. For example:
String original = "Hello";
String modified = original.concat(", World!"); // Creates a new string

System.out.println(original); // Output: Hello


System.out.println(modified); // Output: Hello, World!
Strings : Common Operations with Strings

• String Pool:
Java maintains a string pool, a special area in
memory where string literals are stored.
Strings declared using string literals that have
the same content will reference the same object
in the pool.
This can lead to more efficient memory usage.
Strings : Common Operations with Strings

• StringBuilder and StringBuffer:


If you need mutable strings and want to perform
many modifications, you can use StringBuilder (not
thread-safe) or StringBuffer (thread-safe). These
classes provide methods for modifying strings
efficiently.
StringBuilder stringBuilder = new StringBuilder("Hello");
stringBuilder.append(", World!");

String result = stringBuilder.toString(); // "Hello, World!"


Command line Arguments

• In Java, command-line arguments allow you to pass


information to a Java program when it is run from the
command line.
• Command-line arguments are specific to the way a Java
program is run from the command line and are not the same as
method parameters or function arguments in the program
itself.
• These arguments are passed as strings separated by spaces
after the class name.
• Accessing Command-Line Arguments:
Command-line arguments are passed to the main method of
the Java program as an array of strings.
Command line Arguments

public class CommandLineArgumentsExample {


public static void main(String[] args) {
// 'args' is an array containing the command-line arguments
// args[0] is the first argument, args[1] is the second, and so on
System.out.println("Number of command-line arguments: " +
args.length);

// Accessing and printing each argument


for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
Command line Arguments

• Running a Java Program with Command-Line


Arguments:
• Assuming you have compiled your Java
program
(CommandLineArgumentsExample.java), you
can run it with command-line arguments as
follows:
java CommandLineArgumentsExample arg1 arg2 arg3
Command line Arguments

java CommandLineArgumentsExample arg1 arg2 arg3


• In this example, arg1, arg2, and arg3 are the command-
line arguments.
Example Output:
• If you run the program with the command java
CommandLineArgumentsExample one two three, you
should see the following output:
Number of command-line arguments: 3
Argument 0: one
Argument 1: two
Argument 2: three
Command line Arguments

• Notes:
• The args array is of type String[], so all command-line
arguments are initially treated as strings. If you need to use
them as other types, you must perform type conversion.
• If your command-line arguments contain spaces or special
characters, you may need to enclose them in quotes.
• The length of the args array can be used to determine the
number of command-line arguments provided.
• Command-line arguments are useful for configuring a
program, providing input data, or setting other parameters
when the program starts.
Week – 7 & 8

Introducing OOP
Introducing OOP

• Java is an object-oriented programming (OOP) language, which


means it follows the principles of object-oriented
programming.
• Object-oriented programming is a programming paradigm that
revolves around the concept of "objects," which can
encapsulate data and behavior.
• These are the fundamental principles of object-oriented
programming in Java.
• By applying these concepts, developers can create modular,
reusable, and maintainable code.
• Here are some key concepts and features of Java's object-
oriented programming:
Introducing OOP

Classes and Objects:


• A class is a blueprint or template for creating
objects. It defines the properties (attributes)
and behaviors (methods) that objects of the
class will have.
• An object is an instance of a class. It
represents a real-world entity and can interact
with other objects.
OOP: Classes and Objects
// Example of a simple class
public class Car {
// Attributes
String model;
int year;

// Method
public void start() {
System.out.println("Car started");
}
}

// Creating an object of the Car class


Car myCar = new Car();
OOP: Encapsulation
Encapsulation:
• Encapsulation is the bundling of data
(attributes) and methods that operate on that
data within a single unit (class).
• It helps in data hiding and abstraction.
OOP: Encapsulation
public class Person {
private String name; // Encapsulated attribute

// Getter and setter methods


public String getName() {
return name;
}

public void setName(String newName) {


this.name = newName;
}
}
OOP: Inheritance
Inheritance:
• Inheritance allows a class (subclass or derived
class) to inherit properties and behaviors from
another class (superclass or base class).
• It promotes code reuse.
OOP: Inheritance
// Example of inheritance
public class Student extends Person {
private int studentId;

// Additional methods and attributes for


Student
}
OOP: Polymorphism
Polymorphism:
• Polymorphism allows objects to be treated as
instances of their parent class rather than
their actual class.
• This can be achieved through method
overloading & overriding.
OOP: Polymorphism
// Example of polymorphism
public class Animal {
public void makeSound() {
System.out.println("Some generic sound");
}
}

public class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Woof!");
}
}
OOP: Abstraction
Abstraction:
• Abstraction involves simplifying complex
systems by modeling classes based on the
essential properties and behaviors they share.
• Abstract classes and interfaces support
abstraction.
OOP: Abstraction
// Example of abstraction using an interface
public interface Shape {
double calculateArea();
}

public class Circle implements Shape {


private double radius;

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
OOP: Class modifiers
• In Java, class modifiers are keywords that provide
additional information about the nature of a class.
• These modifiers provide a way to control the
visibility, inheritance, and behavior of classes in
Java, contributing to the overall design and
encapsulation of the code.
• These modifiers are used to control the visibility,
access, and behavior of classes.
• Here are some of the class modifiers in Java
OOP: Access Modifiers
Access Modifiers:
• Public (public): The class is accessible from
any other class.
• Default (no modifier): The class is only
accessible within the same package.
OOP: Access Modifiers
// Public class
public class PublicClass {
// class members
}

// Default (package-private) class


class DefaultClass {
// class members
}
OOP: Final
Final (final):
• A final class cannot be subclassed. No other
class can extend a final class.
public final class FinalClass {
// class members
}
OOP: Abstract
Abstract (abstract):
• An abstract class cannot be instantiated on its
own. It is meant to be subclassed, and it may
contain abstract methods that must be
implemented by its subclasses.
public abstract class AbstractClass {
// abstract methods or other members
}
OOP: Strictfp
Strictfp (strictfp):
• Ensures that the floating-point calculations
inside the class adhere to the IEEE 754
standard.
public strictfp class StrictfpClass {
// class members
}
OOP: Static
Static (static):
• A static class is associated with the class itself
rather than instances of the class. It cannot be
instantiated, and its members are shared
among all instances of the class.
public class StaticClass {
// static members
}
OOP: Final and Abstract
Final and Abstract:
• A class can be both final and abstract. In such
cases, the class cannot be subclassed, but it
may contain abstract methods that must be
implemented by its subclasses.
public final abstract class FinalAbstractClass {
// abstract methods or other members
}
OOP: Class members
• In Java, class members are the fields (variables) and
methods (functions) that belong to a class.
• These class members collectively define the
structure and behavior of a Java class, enabling
developers to create modular and organized code.
• Fields represent the state, methods define behavior,
constructors initialize objects, and nested classes
provide additional organization and encapsulation.
• Here are the main types of class members in Java:
Class Members: Fields
Fields (Variables):
• Fields are variables that represent the state or
attributes of an object.
• They can be of different data types such as int,
double, String, custom objects, etc.
• Fields can have different access modifiers
(public, private, protected, or default).
Class Members: Fields
public class MyClass {
// Instance variable (belongs to an instance of the class)
private int myNumber;

// Static variable (shared among all instances of the class)


public static String className = "MyClass";

// Constant (final and static)


public static final double PI = 3.14159;
}
Class Members: Methods
Methods:
• Methods define the behavior or actions that
objects of a class can perform.
• They consist of a method signature (name,
return type, and parameters) and a method
body.
• Methods can also have different access
modifiers.
Class Members: Methods
public class Calculator {
// Instance method
public int add(int a, int b) {
return a + b;
}

// Static method
public static double squareRoot(double num) {
return Math.sqrt(num);
}

// Getter method
public int getMyNumber() {
return myNumber;
}

// Setter method
public void setMyNumber(int newNumber) {
this.myNumber = newNumber;
}
}
Class Members: Constructors
Constructors:
• Constructors are special methods used for
initializing objects when they are created.
• They have the same name as the class and do
not have a return type.
• Constructors are called automatically when an
object is instantiated.
Class Members: Constructors
public class Person {
private String name;
private int age;

// Default constructor
public Person() {
// Initialization code
}

// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Class Members: Nested Classes
Nested Classes:
• Java allows classes to be defined inside other
classes. These are known as nested classes.
• Nested classes can be static or non-static.
Class Members: Nested Classes
public class OuterClass {
private int outerField;

// Nested class (static)


public static class NestedStaticClass {
// Static nested class members
}

// Nested class (non-static or inner class)


public class InnerClass {
// Inner class members
}
}
OOP: Constructor & finalizer

• In Java, constructors and finalizers serve different purposes


in the lifecycle of an object.
• Constructors are used for object initialization, ensuring
proper setup, while finalizers are invoked by the garbage
collector to perform cleanup operations before an object is
reclaimed.
• It's important to note that finalizers should be used with
caution, and alternative resource management strategies
are often preferred in modern Java programming.
OOP: Constructors
Constructors:
• Purpose:
– Constructors are special methods used for initializing
objects when they are created.
– They ensure that an object is properly initialized before it is
used.
• Syntax:
– Constructors have the same name as the class and do not
have a return type.
– They can be overloaded, meaning a class can have multiple
constructors with different parameter lists.
OOP: Constructors
public class MyClass {
// Default constructor
public MyClass() {
// Initialization code
}

// Parameterized constructor
public MyClass(int initialValue) {
// Initialization code with a parameter
}
}
OOP: Constructors
Invocation:
• Constructors are called automatically when an
object is created using the new keyword.
MyClass obj1 = new MyClass();
// Calls the default constructor
MyClass obj2 = new MyClass(42);
// Calls the parameterized constructor
OOP: Constructors
Types:
• There are two main types of constructors: default (no-argument) constructors
and parameterized constructors.
public class MyClass {
// Default constructor
public MyClass() {
// Initialization code
}

// Parameterized constructor
public MyClass(int initialValue) {
// Initialization code with a parameter
}
}
OOP: Finalizer
Finalizer:
• Purpose:
– A finalizer, also known as a destructor, is a method that gets
called by the garbage collector before an object is reclaimed
(destroyed) by the memory management system.
– It allows the object to perform cleanup operations before it is
removed from memory.
• Syntax:
– In Java, the finalizer is declared using the finalize() method.
However, explicit finalization is often discouraged, and other
resource management techniques (like using try-with-
resources for closing resources) are preferred.
OOP: Finalizer
public class MyClass {
// Finalizer
@Override
protected void finalize() throws Throwable {
// Cleanup code
super.finalize();
}
}
OOP: Finalizer
Invocation:
• The finalizer is automatically called by the
garbage collector when it decides to reclaim
the memory occupied by an object
MyClass obj = new MyClass();
obj = null;
// Object becomes eligible for garbage collection
// The garbage collector calls obj's finalize() method
before reclaiming its memory
Week – 9

Exception Handling
Introduction
• Exception handling is a crucial aspect of Java
programming that enables developers to manage
errors and unexpected situations effectively.
• In Java, exceptions are events that occur during the
execution of a program and disrupt its normal flow.
• These exceptions may arise due to various reasons,
such as invalid input, network issues, file not found,
etc.
• To deal with these exceptions, Java provides a robust
exception handling mechanism.
Introduction
• Exception handling in Java helps in writing
more robust and fault-tolerant code by
providing a structured way to deal with
unexpected situations.
• It promotes good programming practices and
improves the overall reliability of Java
applications.
• Unlike errors, exceptions are meant to be
caught and handled by the program.
• Exception handling in Java involves using try,
catch, and finally blocks to handle exceptional
situations.
• The try block contains the code that may throw
an exception.
• The catch block handles the exception if it occurs,
• and the finally block (optional) contains code that
will be executed regardless of whether an
exception occurs or not.
Example
try {
// code that may cause an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code that will be executed no matter what
}
Types of Exceptions
• Checked Exceptions: These are exceptions
that the compiler forces you to handle
explicitly. Examples include IOException,
FileNotFoundException, SQLException, etc.
• Unchecked Exceptions (Runtime Exceptions):
These exceptions occur at runtime and do not
require explicit handling. Examples include
ArithmeticException, NullPointerException,
etc.
Example
public class DivideByZeroExample {
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;

try {
int result = numerator / denominator;
// This will throw an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Types of Errors
• In Java, errors are a type of throwable that represent
serious and typically irrecoverable problems.
• Errors are not meant to be caught or handled by regular
application code; instead, they indicate issues that often
require intervention at a system or environment level.
• These errors are typically not handled by application
code but are important for developers to be aware of, as
they often require adjustments to the application or the
execution environment.
• Here are some common types of errors in Java:
StackOverflowError
• This error occurs when the call stack exceeds its limit due to deep or
infinite recursion.
• Example:

public class StackOverflowExample {


public static void main(String[] args) {
recursiveMethod(); // This will eventually lead to a StackOverflowError
}

private static void recursiveMethod() {


recursiveMethod();
}
}
OutOfMemoryError
• Indicates that the Java Virtual Machine (JVM) has run out of
memory.
• Example:
public class OutOfMemoryExample {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
while (true) {
list.add(new Object()); // This will eventually lead to an
OutOfMemoryError
}
}
}
NoClassDefFoundError
• This error occurs when the Java Virtual Machine (JVM) cannot find the
definition of a class at runtime, even though it was available at compile time.
• Example:

public class NoClassDefFoundErrorExample {


public static void main(String[] args) {
try {
// Attempting to create an instance of a class that doesn't exist
Class.forName("NonExistentClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
AbstractMethodError
• Occurs when an abstract method is not implemented by a
concrete subclass.
• Example:
public abstract class AbstractMethodErrorExample {
public abstract void abstractMethod();
}

public class ConcreteClass extends AbstractMethodErrorExample {


// Missing implementation for abstractMethod, will result in
AbstractMethodError
}
UnsupportedClassVersionError
• This error occurs when a class file has a version number
that is not supported by the Java Runtime Environment
(JRE).
• Example:
// Compile this code with a higher version of Java, and try to run it
with a lower version
public class UnsupportedClassVersionErrorExample {
public static void main(String[] args) {
System.out.println("Unsupported Class Version Error
Example");
}
}
Error Handling Technique
• Error handling in Java involves techniques to
gracefully manage exceptions and errors that may
occur during the execution of a program.
• Effective error handling is essential for writing
robust and reliable Java applications.
• It ensures that the application can gracefully handle
unexpected situations and provides a mechanism
for recovery or appropriate response.
• Here are some key error handling techniques in
Java:
try-catch Blocks
• Use try blocks to enclose the code that might
throw exceptions.
• Use catch blocks to handle specific exceptions that
may occur within the corresponding try block.
try {
// code that may throw exceptions
} catch (ExceptionType e) {
// handle the exception
}
Multiple Catch Blocks
• Use multiple catch blocks to handle different
types of exceptions.
try {
// code that may throw exceptions
} catch (IOException e) {
// handle IOException
} catch (SQLException e) {
// handle SQLException
}
finally Block
• The finally block contains code that is guaranteed
to be executed, whether an exception occurs or
not. It is often used for cleanup operations.
try {
// code that may throw exceptions
} catch (ExceptionType e) {
// handle the exception
} finally {
// cleanup code
}
Throwing Exceptions
• Use the throw statement to throw exceptions
explicitly when a certain condition is met.
if (someCondition) {
throw new SomeException("Error message");
}
Custom Exceptions
• Create custom exception classes by extending
the Exception class or one of its subclasses.
This is useful for handling application-specific
errors.
public class CustomException extends Exception {
// constructor and additional methods
}
Checked vs. Unchecked Exceptions
• Handle checked exceptions using try-catch blocks
or declare them in the method signature using
throws.
• Unchecked exceptions (runtime exceptions) do not
require explicit handling but should be handled if
possible to ensure a more robust program.
public void someMethod() throws SomeCheckedException
{
// code that may throw SomeCheckedException
}
Logging
• Use logging frameworks like Java's built-in
java.util.logging or third-party libraries (e.g.,
Log4j, SLF4J) to log exception information. This
aids in debugging and monitoring.
catch (ExceptionType e) {
// log the exception
logger.error("An error occurred: ", e);
// handle the exception
}
Graceful Degradation
• Implement strategies for graceful degradation
when errors occur, allowing the program to
continue functioning or provide a meaningful
response to the user.
try {
// code that may throw exceptions
} catch (ExceptionType e) {
// handle the exception
// provide a graceful response to the user
}
Week – 10

Inheritance
Introduction
• Inheritance is a fundamental concept in object-oriented programming (OOP)
that allows one class to inherit the properties and behaviors of another class.
• Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
• The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes.
• When you inherit from an existing class, you can reuse methods and fields of
the parent class.
• Moreover, you can add new methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
• Inheritance in Java allows you to create a hierarchy of classes, where a
subclass can inherit and extend the functionality of a superclass.
• It promotes code reuse and helps in organizing and structuring your code in
a more modular way.
Terms used in Inheritance

Base Class (Superclass/Parent Class):


• The class whose properties and behaviors are inherited by
another class is called the base class, superclass, or parent class.
• It serves as a blueprint for the derived class.

public class Animal {


String name;
public void eat() {
System.out.println(name + " is eating.");
}
}
Terms used in Inheritance

Derived Class (Subclass/Child Class):


• The class that inherits the properties and behaviors from
another class is called the derived class, subclass, or child class.
• It can have additional attributes and methods or override the
methods of the base class.

public class Dog extends Animal {


public void bark() {
System.out.println(name + " is barking.");
}
}
Terms used in Inheritance

Keyword extends:
• In Java, the extends keyword is used to
indicate that a class is inheriting from another
class.
public class Dog extends Animal {
// ...
}
Terms used in Inheritance

Access Modifiers:
• The access modifiers (public, protected, private, or
package-private) in the base class determine the visibility
of its members (fields and methods) in the derived class.

public class Animal {


protected String name;

// ...
}
Terms used in Inheritance

Method Overriding:
• A derived class can provide a specific implementation for a
method that is already defined in its base class. This is known
as method overriding.

public class Dog extends Animal {


@Override
public void eat() {
System.out.println(name + " is eating dog food.");
}
}
Terms used in Inheritance

Constructor in Inherited Class:


• The constructor of the base class is not inherited by the
derived class, but it is called implicitly when an object of the
derived class is created.

public class Dog extends Animal {


public Dog(String dogName) {
name = dogName;
}
// ...
}
Terms used in Inheritance

Multiple Inheritance:
• Java supports single inheritance for classes,
meaning a class can inherit from only one
superclass. However, a class can implement
multiple interfaces.
public class MyClass extends AnotherClass {
// ...
}
Need of Inheritance

• Inheritance is a fundamental concept in Java and other


object-oriented programming (OOP) languages, serving
several purposes that contribute to code organization,
reusability, and extensibility.
• Here are some key reasons why inheritance is essential
in Java:
• Code Reusability:
– Inheritance allows a class to reuse the code of another
class. The properties and behaviors of a base class can be
inherited by a derived class, promoting code reusability and
reducing redundancy.
Need of Inheritance

• Method Overriding:
– Derived classes can provide specific implementations for
methods defined in their base classes. This is known as
method overriding. It allows customization of behavior
in derived classes while maintaining a common interface
defined in the base class.
• Polymorphism:
– Inheritance is closely related to polymorphism, where
objects of a derived class can be treated as objects of
their base class. This enables a more generalized and
flexible code structure.
Need of Inheritance

• Organizing Code:
– Inheritance helps in organizing and structuring code by
establishing a hierarchy of classes. This hierarchy
reflects relationships and commonalities among
different types of objects in a system.
• Extensibility:
– New classes can be created by extending existing
classes. This promotes extensibility, allowing developers
to add new features or modify existing behavior without
modifying the original code. This is particularly useful in
maintaining and evolving large codebases.
Need of Inheritance

• Encapsulation:
– Inheritance supports encapsulation by allowing the
definition of private members in a base class. These
members are accessible within the class hierarchy, but they
are not directly accessible from outside the hierarchy,
enhancing data hiding and protection.
• Base Class as a Blueprint:
– The base class serves as a blueprint for derived classes,
providing a common structure and behavior. Changes made
to the base class automatically propagate to all derived
classes, ensuring consistency throughout the codebase.
Need of Inheritance

• Reducing Redundancy:
– Common functionality shared among multiple classes
can be centralized in a base class, reducing redundancy
and making the code easier to maintain. Changes made
in the base class automatically affect all derived classes.
• Facilitating Design Patterns:
– Inheritance is a key aspect of various design patterns,
such as the Template Method Pattern and the Factory
Method Pattern. These patterns leverage inheritance to
define and structure relationships between classes.
Need of Inheritance

Code Understanding:
• Inheritance can enhance the understandability
of code by representing real-world
relationships between objects. It provides a
way to model and represent commonalities
and differences in a system.
Super class and Base class in java

• In Java, the terms "superclass" and "base


class" are often used interchangeably,
referring to the class from which another class
inherits properties and behaviors. Let's clarify
these terms.
• Whether you use "superclass" or "base class"
depends on the convention or terminology
used in a particular context or development
team.
Super class and Base class in java

Superclass:
• The term "superclass" is more commonly used in
the context of Java. It refers to the class that is being
extended or inherited by another class.
• The superclass provides a blueprint for the subclass,
and the subclass inherits the attributes and
methods defined in the superclass.
• In Java, the extends keyword is used to indicate that
a class is inheriting from another class (the
superclass).
Super class and Base class in java

public class Animal {


// Superclass
// ...
}

public class Dog extends Animal {


// Subclass
// ...
}
Super class and Base class in java

Base Class:
• The term "base class" is more general and can
be used in the context of object-oriented
programming in general, not just limited to
Java.
• It also refers to the class that is inherited by
another class, providing a foundation for the
derived class.
Super class and Base class in java

// Base class
public class Animal {
// ...
}

// Derived class inheriting from the base class


public class Dog extends Animal {
// ...
}
Sequence of constructors call in hierarchy

• While implementing inheritance in a Java


program, every class has its own constructor.
Therefore the execution of the constructors
starts after the object initialization.
• It follows a certain sequence according to the
class hierarchy.
• There can be different orders of execution
depending on the type of inheritance.
Order of execution of constructor in Single inheritance

• In single level inheritance, the constructor of the base class is executed first.
• In the below code, after creating an instance
of ChildClass the ParentClass constructor is invoked first and then
the ChildClass.

/* Parent Class */
class ParentClass
{
/* Constructor */
ParentClass()
{
System.out.println("ParentClass constructor executed.");
}
}
Order of execution of constructor in Single inheritance

/* Child Class */
class ChildClass extends ParentClass
{
/* Constructor */
ChildClass()
{
System.out.println("ChildClass constructor executed.");
}
}
public class OrderofExecution1
{
/* Driver Code */
public static void main(String ar[])
{
/* Create instance of ChildClass */
System.out.println("Order of constructor execution...");
new ChildClass();
}
}
Order of execution of constructor in Multilevel inheritance

• In multilevel inheritance, all the upper class


constructors are executed when an instance of
bottom most child class is created.
• In the below code, an instance
of Student class is created and it invokes the
constructors of College,
Department and Student accordingly.
Order of execution of constructor in Multilevel inheritance

class College
{
/* Constructor */
College()
{
System.out.println("College constructor executed");
}
}
class Department extends College
{
/* Constructor */
Department()
{
System.out.println("Department constructor executed");
}
}
Order of execution of constructor in Multilevel inheritance

class Student extends Department


{
/* Constructor */
Student()
{
System.out.println("Student constructor executed");
}
}
public class OrderofExecution2
{
/* Driver Code */
public static void main(String ar[])
{
/* Create instance of Student class */
System.out.println("Order of constructor execution in Multilevel inheritance...");
new Student();
}
}
Calling same class constructor using this keyword

• Here, inheritance is not implemented. But


there can be multiple constructors of a single
class and those constructors can be accessed
using this keyword.
• In the below code, the parameterized
constructor is called first even when the
default constructor is called while object
creation. It happens because this keyword is
used as the first line of the default constructor.
Calling same class constructor using this keyword

public class OrderofExecution3


{
/* Default constructor */
OrderofExecution3()
{
this("CallParam");
System.out.println("Default constructor executed.");
}
/* Parameterized constructor */
OrderofExecution3(String str)
{
System.out.println("Parameterized constructor executed.");
}
/* Driver Code */
public static void main(String ar[])
{
/* Create instance of the class */
System.out.println("Order of constructor execution...");
OrderofExecution3 obj = new OrderofExecution3();
}
}
Final keyword
• In Java, the final keyword is used to denote that a
variable, method, or class cannot be further modified or
extended.
• It serves different purposes depending on where it is
applied.
• The final keyword in Java is a modifier that can be
applied to variables, methods, and classes.
• It provides a way to create constants, prevent method
overriding, restrict class inheritance, and enforce
immutability in method parameters.
Final Variable
• When applied to a variable, the final keyword indicates that the variable's
value cannot be changed after it has been assigned a value. It essentially
makes the variable a constant.
• The variable must be assigned a value either at the time of declaration or
within the constructor of the class.

public class Example {


final int constantValue = 10;

public void modifyValue() {


// Error: Cannot assign a value to a final variable.
// constantValue = 20;
}
}
Final Method
• When applied to a method, the final keyword indicates that the method
cannot be overridden by subclasses. Subclasses are not allowed to
provide a different implementation for a final method.

public class BaseClass {


public final void finalMethod() {
// Method implementation
}
}
public class SubClass extends BaseClass {
// Error: Cannot override the final method from BaseClass.
// public void finalMethod() { }
}
Final Class
• When applied to a class, the final keyword indicates that the class cannot be
sub-classed.
• It prevents the creation of any further subclasses.
• Final classes are often used when the design intent is to create an immutable
class.
• Or when it is deemed that further inheritance could compromise the integrity
of the class.

public final class FinalClass {


// Class implementation
}

// Error: Cannot inherit from final class.


// public class SubClass extends FinalClass { }
Final Parameters
• When applied to method parameters, the final keyword
indicates that the parameter cannot be modified within the
method.
• It helps in enforcing that the parameter remains constant
throughout the method execution.

public void processValue(final int value) {


// Error: Cannot assign a value to a final parameter.
// value = 10;
// Method implementation
}
Overriding and Overloading
• Overriding and Overloading are two concepts
related to methods in the context of inheritance.
• Method Overriding is about providing a new
implementation for a method in a subclass.
• While Method Overloading is about having multiple
methods with the same name but different
parameter lists in the same class.
• Both concepts contribute to the flexibility and
expressiveness of Java's object-oriented
programming model.
Method Overriding
Definition:
• Method overriding occurs when a subclass provides a specific
implementation for a method that is already defined in its
superclass.
Key Points:
• The method in the subclass must have the same signature (name,
return type, and parameters) as the method in the superclass.
• The @Override annotation is optional but recommended for
clarity. It helps the compiler catch errors if the method signature
in the subclass does not match any method in the superclass.
• The overridden method in the subclass should provide a specific
implementation that is related to the subclass's context.
Method Overriding
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
In this example, the Dog class overrides the makeSound method from the
Animal class.
Method Overloading

Definition:
• Method overloading occurs when a class has two or
more methods with the same name but different
parameters (number, type, or order).
Key Points:
• The methods must have the same name but different
parameter lists.
• Return types may or may not be the same.
• Overloading allows a class to provide multiple methods
with similar functionality but different ways of
accepting and processing inputs.
Method Overloading

class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}
In this example, the Calculator class has two add methods, one
for adding integers and another for adding doubles.
Interfaces
• In Java, an interface is a collection of abstract methods (methods
without a body) and constant declarations.
• Interfaces provide a way to achieve abstraction in Java, allowing
you to define a contract that classes must follow without
specifying how they should implement it.
• A class that implements an interface must provide concrete
implementations for all the methods declared in that interface.
• Interfaces play a crucial role in Java's support for multiple
inheritance, abstraction, and defining contracts between
different parts of a program.
• They are widely used in Java libraries and frameworks to define
common behavior that can be implemented by various classes.
• Here are the key features and concepts related to interfaces in
Java.
Interfaces: Declaration
• We declare an interface using the interface keyword.

public interface MyInterface {


// Abstract methods (implicitly public and abstract)
void myMethod();

// Constant declarations (implicitly public, static, and


final)
int MY_CONSTANT = 42;
}
Interfaces: Implementing an Interface
• A class implements an interface using the implements
keyword.
• The class must provide concrete implementations for
all the abstract methods declared in the interface.
public class MyClass implements MyInterface {
@Override
public void myMethod() {
// Implementation of the method
}
}
Interfaces: Multiple Interface
Implementation
• A class can implement multiple interfaces, separated by commas.
• If multiple interfaces have methods with the same signature, the class must
provide a concrete implementation for each.

public class MyOtherClass implements MyInterface, AnotherInterface {


@Override
public void myMethod() {
// Implementation of the method
}

@Override
public void anotherMethod() {
// Implementation of another method from AnotherInterface
}
}
Interfaces: Default Methods
• Starting from Java 8, interfaces can have default methods,
which provide a default implementation for a method.
• Default methods are declared using the default keyword.

public interface MyInterface {


void myMethod();

default void defaultMethod() {


// Default implementation
}
}
Interfaces: Static Methods
• Starting from Java 8, interfaces can have static methods.
• Static methods are declared using the static keyword.

public interface MyInterface {


void myMethod();

static void staticMethod() {


// Static method implementation
}
}
Interfaces: Functional Interfaces
• A functional interface is an interface that has only
one abstract method (SAM - Single Abstract Method).
• Functional interfaces can be used with lambda
expressions, providing a concise way to implement
them.

@FunctionalInterface
public interface MyFunctionalInterface {
void myMethod();
}
Interfaces: Marker Interfaces
• Some interfaces, known as marker interfaces,
have no methods at all. They serve as a tag to
indicate something about the implementing
class.
• Examples include Serializable, Cloneable, and
MarkerInterface.
public interface MarkerInterface {
// Marker interfaces have no methods
}
Week – 11,12,13

AWT& Border layout &


Event
Week – 14

Applet
Week – 15

Threads
Week – 16

Data base programming


Introduction
• In Java, you can interact with databases using
the Java Database Connectivity (JDBC) API.
JDBC provides a standard interface for
connecting to relational databases and
executing SQL queries.
• Below is a basic guide on how to perform
database programming in Java using JDBC:
1. Download and Install a JDBC Driver
• JDBC drivers are specific to the database you
are using.
• Download the JDBC driver for your database
and add it to your project's classpath.
2. Import JDBC Packages
• Import the necessary JDBC packages in your
Java program.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
3. Establish a Database Connection
• Use the DriverManager.getConnection method to establish a connection to
your database.

String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";


String username = "your_username";
String password = "your_password";

try {
Connection connection = DriverManager.getConnection(jdbcUrl, username,
password);
// Perform database operations here
} catch (SQLException e) {
e.printStackTrace();
}
4. Execute SQL Queries
• Create a Statement object to execute SQL queries.

Statement statement = connection.createStatement();


String sqlQuery = "SELECT * FROM your_table";
ResultSet resultSet = statement.executeQuery(sqlQuery);

// Process the result set


while (resultSet.next()) {
// Access data from the result set
}
5. Update or Insert Data
• Use the executeUpdate method for SQL queries
that modify the database (INSERT, UPDATE,
DELETE).

String insertQuery = "INSERT INTO your_table


(column1, column2) VALUES ('value1', 'value2')";
int rowsAffected =
statement.executeUpdate(insertQuery);
6. Close Resources
• Close the ResultSet, Statement, and
Connection objects when you are done with
them.

resultSet.close();
statement.close();
connection.close();
Complete Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseExample {

public static void main(String[] args) {


String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";

try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);


Statement statement = connection.createStatement()) {

String sqlQuery = "SELECT * FROM your_table";


ResultSet resultSet = statement.executeQuery(sqlQuery);

while (resultSet.next()) {
// Process data from the result set
}

} catch (SQLException e) {
e.printStackTrace();
}
}
}
THE END

You might also like