BSCS 7th Java 3
BSCS 7th Java 3
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
• 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.
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.
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
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:
• 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
• 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
• 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;
// 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);
• 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
• 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
• 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
// Method
public void start() {
System.out.println("Car started");
}
}
@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
}
// 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;
// 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:
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
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.
// ...
}
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.
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
• 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
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
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 {
// ...
}
• 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
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
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;
}
@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.
@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
Applet
Week – 15
Threads
Week – 16
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.
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;
while (resultSet.next()) {
// Process data from the result set
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
THE END