0% found this document useful (0 votes)
15 views29 pages

Java Unit - 1

The document provides an overview of advanced Java programming, covering core concepts such as the Java Virtual Machine (JVM), data types, variables, and control statements. It details the history and evolution of Java, its features including platform independence and security, as well as the structure of Java programs. Additionally, it explains the types of data and operators in Java, along with examples of expressions and control statements.

Uploaded by

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

Java Unit - 1

The document provides an overview of advanced Java programming, covering core concepts such as the Java Virtual Machine (JVM), data types, variables, and control statements. It details the history and evolution of Java, its features including platform independence and security, as well as the structure of Java programs. Additionally, it explains the types of data and operators in Java, along with examples of expressions and control statements.

Uploaded by

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

lOMoARcPSD|49915069

Unit 1 AJP - advanced java programming

Master of Computer Applications (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Kamalapraba (kamalapraba25@[Link])
lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Unit 1

Core Java Fundamentals: Java Virtual Machine, data types, variables, keywords, operators,
expressions, control statements, classes, objects, constructors, access control, method
overloading, static members, Arrays, Strings, Inheritance: types, constructors in inheritance,
method overriding, use of super, abstract classes – interfaces, dynamic method dispatch.
Packages and exception handling.

History of Java:

The history of java starts from Green Team. Java team members (also known as Green
Team), initiated a revolutionary task to develop a language for digital devices such as set-top
boxes, televisions etc. For the green team members, it was an advance concept at that time.
But, it was suited for internet programming. Later, Java technology as incorporated by
Netscape. Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc. There are given the major points that describes the history of java. 1) James
Gosling, Mike Sheridan, and Patrick Naught on initiated the Java language project in June
1991. The small team of sun engineers called Green Team. 2) Originally designed for small,
embedded systems in electronic appliances like set- top boxes. 3) Firstly, it was called "Green
talk" by James Gosling and file extension [Link]. 4) After that, it was called Oak and was
developed as a part of the Green project.

Java Version History

There are many java versions that has been released. Current stable release of Java is Java SE
8. 1. JDK Alpha and Beta (1995) 2. JDK 1.0 (23rd Jan, 1996) 3. JDK 1.1 (19th Feb, 1997) 4.
J2SE 1.2 (8th Dec, 1998) 5. J2SE 1.3 (8th May, 2000) 6. J2SE 1.4 (6th Feb, 2002) 7. J2SE
5.0 (30th Sep,2004) 8. Java SE 6 (11th Dec,2006) 9. Java SE 7 (28th July, 2011) [Link] SE
8 (18th March,2014)

Features of Java

There is given many features of java. They are also known as java buzzwords. The Java
Features given below are simple and easy to understand.

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

 Java has removed many complicated and rarely-used features, for


example, explicit pointers, operator overloading, etc.
 There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform independent

Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.

Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
 No explicit pointer

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Java Programs run inside a virtual machine sandbox


Java language provides these securities by default. Some security can also be provided
by an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust:
Robust simply means strong. Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security problems.
 There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
 There are exception handling and the type checking mechanism in Java. All
these points make Java robust.

Architecture-neutral:
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit


architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4
bytes of memory for both 32 and 64-bit architectures in Java.

Portable: Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.

High-performance:
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed:
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes us
able to access files by calling the methods from any machine on the internet.
Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.
Dynamic:
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).

3 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

1.1 Java Virtual Machine (JVM)

Definition: JVM is an abstract computing machine that enables Java bytecode to be executed
on any platform without modification.
Role:
o Converts Java bytecode into machine code.
o Provides platform independence.

o Manages memory through Garbage Collection.

o Ensures security and performance optimization.

Architecture:

 Class Loader – loads classes.


 Bytecode Verifier – checks code for illegal code.
 Interpreter – executes instructions.
 Just-In-Time Compiler (JIT) – optimizes performance by compiling
bytecode to native code.
 Garbage Collector – automatically frees memory used by objects that are no
longer referenced.

Key Features of JVM

 Platform Independence – “Write once, run anywhere.”


 Memory Management – Automatic garbage collection.

 Security – Bytecode verification and sandboxing.

 Performance Optimization – JIT compilation and efficient runtime execution.

 Multithreading Support – Multiple threads executed via separate stacks.

4 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

JVM is a engine that provides runtime environment to drive the Java Code or applications. It
converts Java bytecode into machines language. JVM is a part of JRE(Java Run
Environment). It stands for Java Virtual Machine

1. First, Java code is compiled into bytecode. This bytecode gets interpreted
on different machines
2. Between host system and Java source, bytecode is an intermediary language.
3. JVM is responsible for allocating memory space.

Java Program Structure:

Section Description

Documentation You can write a comment in this section. Comments are beneficial for the
Section programmer because they help them understand the code. These are
optional.

Three types of comment line representation:


• Single line (//)
• Multi line (/* */)
• Documentation Comments (/** */ )

Import This line indicates that if you want to use a class of another package, then
statements you can do this by importing it directly into your program.
Example:
import [Link].*;

Interface Interfaces are like a class that includes a group of method declarations.
statement It's an optional section and can be used when programmers want to
implement multiple inheritances within a program.

5 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Class A Java program may contain several class definitions. Classes are the
Definition main and essential elements of any Java program.

Main Method Every Java stand-alone program requires the main method as the starting
Class point of the program. This is an essential part of a Java program. There
may be many classes in a Java program, and only one class defines the
main method. Methods contain data type declaration and executable
statements

1.2 Data Types in Java

Data types represent the different values to be stored in the variable. In java, there are two
types of data types:

 Primitive datatypes
 Non-primitive datatypes

Primitive Data Types:

A primitive data type in Java is a basic, built-in data type that stores simple values directly,
rather than objects or more complex structures. These are predefined by the language and are
used to represent raw data efficiently in memory.

Key Characteristics:

 Not objects – They store values directly.


 Fixed size and format – The size of each data type is predefined.

 Efficient in memory and speed – Operations on primitive types are faster.

 Default values – Each has a default value if not explicitly initialized.

Description
Data Type Size
Byte 8 bits Stores small integers
short 16 bits Stores larger integers
int 32 bits Default integer type
long 64 bits Stores very large integers
float 32 bits Stores floating-point numbers
double 64 bits Stores high precision floating-point numbers
char 16 bits Stores single characters
boolean 1 bit Stores true or false

Non-primitive Data Types:

6 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Non-primitive data types (also called reference types) in Java are types that refer to
objects rather than storing the actual data directly. These are more complex structures and can
hold multiple values, methods, and behaviours.(Class, Array & Interface)

Key Characteristics of Non-Primitive Data Types:

 They store references – The variable holds the memory address where the object is
stored.
 Can be used to create objects – These types are built from classes and interfaces.

 More memory overhead – They have extra data like methods and metadata.

 Can be null – A reference can point to no object.

Example: Add Two Numbers using class

Class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
[Link](c);
}}
Output:20

Example: print elements in the array

public class ArrayExample {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
[Link]("Elements of the array are:");
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);

} }}

Example: Interface

interface Printable {
void print();
}
class Document implements Printable {
public void print() {
[Link]("Printing the document");
}}
public class SimpleInterface {
public static void main(String[] args) {
7 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Printable doc = new Document();


[Link]();
}
}

1.3 Variables

Variable is a name of memory location. There are three types of variables in java

 Local Variables: Declared inside methods, constructors, or blocks.


 Instance Variables:Variable is a name of memory location. There are three types of
variables in java

 Static Variables: A variable that is declared as static is called static variable. It


cannot be local.

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
} }//end of class

1.4 Keywords
 Reserved words with special meaning. Examples: class, public, static, void, if, else,
for, while, return, this, super, new.

1.5 Operators

Operators in Java are special symbols or keywords that are used to perform operations on
variables and values. They help manipulate data by performing arithmetic, comparisons,
logical operations, and more.

Types of operators:

 Arithmetic: +, -, *, /, %
 Relational: ==, !=, >, <, >=, <=
 Logical: &&, ||, !
 Assignment: =, +=, -=, *=, /=
 Unary: ++, --, -, +
 Bitwise: &, |, ^, ~, <<, >>

Example:

int a = 10;

int b = 5;

8 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

int sum = a + b; // '+' is an arithmetic operator that adds two numbers

1.6 Expressions

Expressions are essential building blocks of any Java program, usually created to produce a
new value, although sometimes an expression simply assigns a value to a variable.
Expressions are built using values, variables, operators and method calls. (Combinations of
operators and operands).

Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:

• Those that produce a value, i.e. the result of (1 + 1)

• Those that assign a variable, for example (v =10)

• Those that have no result but might have a "side effect" because an expression can include a
wide range of elements such as method invocations or increment operators that modify the
state (i.e. memory) of a program.

Example:

int a = 10;

int b = 20;

int c = a + b * 2;

1.7 Control Statements

Control statements in Java are used to manage the flow of execution based on conditions or
loops. They decide which part of the code should be executed and how many times.

 Decision-making:
o if, if-else, if-else if-else, switch

 Looping:

o for, while, do-while

 Branching:

o break, continue, return

Examples for decision making statement

9 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

If statement

int number = 10;

if (number > 5) {

[Link]("Number is greater than 5");

If-else statement

int number = 3;

if (number > 5) {

[Link]("Greater than 5");

} else {

[Link]("5 or less");

Switch statement

int day = 3;

switch(day) {

case 1:

[Link]("Monday");

break;

case 3:

[Link]("Wednesday");

break;

default:

[Link]("Another day");

Looping Statement

10 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

For loop

for (int i = 1; i <= 3; i++) {

[Link]("Count: " + i);

While loop

int i = 1;

while (i <= 3) {

[Link]("Count: " + i);

i++;

Do-while loop

int i = 1;

do {

[Link]("Count: " + i);

i++;

} while (i <= 3);

Branching statements:

Break

for (int i = 1; i <= 5; i++) {

if (i == 3) break;

[Link](i);

continue

for (int i = 1; i <= 5; i++) {

if (i == 3) continue;

11 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

[Link](i);

Return

public static void printMessage() {

[Link]("Hello!");

return;

1.8 Classes and Objects

Classes

 A Class is a collection of data members and member functions. Data


members are used to store information; member functions are used to
perform operations on data.
 A class is a group of objects which have common properties.
 It is a template or blueprint from which objects are created.

A class in Java can contains:

12 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Syntax to declare a class:


class ClassName
{

Fileds or Data
members; Methods or
member functions;
}

Field declarations Syntax:

Class classname
{

Datatype
variablename
1; Datatype
variablename2
;
.

Method declaration Syntax:

Returntype methodname(ArgumentsList)
{

Method body;
}

Object:

An entity that has state and behaviour is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical.
An object has three characteristics:
 State : Represents the data (value) of an object.
 Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used internally
by the JVM to identify each object uniquely.

13 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Syntax to declare a object:

Classname objectname=new Classname( );

Example:

class Car {

String color;

int speed;

class Test {

public static void main(String[] args) {

Car myCar = new Car();

[Link] = "Red";

[Link] = 100;

1.9 Constructors

A constructor in Java is a special method that is automatically called when an object is


created. It is used to initialize objects and set initial values for its fields (properties).

Key Points about Constructors

 Same name as the class


 No return type, not even void

14 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

 Called automatically when an object is created

 Can be overloaded (multiple constructors with different parameters)

 If no constructor is defined, Java provides a default constructor

Example:

class Car {
String model;
Car(String model) {
[Link] = model;
}
void display() {
[Link]("Car model: " + model);
}
}

public class SimpleConstructor {


public static void main(String[] args) {
Car car1 = new Car("Toyota");
[Link]();
}
}

1.10 Access Control

Access control can be used for the following purpose:


Encapsulation – Keeps data safe and secure
Modularity – Controls how classes and methods interact
Code maintenance – Helps manage large programs
Restricts unwanted access – Protects sensitive information

Access Modifiers:

o private: Accessible only within the class.


o default: Accessible within the package.

o protected: Accessible within the package and subclasses.

o public: Accessible everywhere.

Example:

class AccessExample {
private int privateVar = 1;
int defaultVar = 2; // default access
protected int protectedVar = 3;
public int publicVar = 4;

15 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

public void display( ) {


[Link]("Private: " + privateVar);
[Link]("Default: " + defaultVar);
[Link]("Protected: " + protectedVar);
[Link]("Public: " + publicVar);
}
}

public class AccessControl {


public static void main(String[] args) {
AccessExample obj = new AccessExample();
[Link]();
}
}

1.11. Method Overloading

If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.(Defining multiple methods with the same
name but different parameters).

Example:

class MathOperations {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

1.12. Static Members

A static member in Java is a field (variable) or method that belongs to the class rather than
any particular instance (object) of the class. This means all objects of the class share the same
static members.

Static Members can be

16 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

✔ Declared using the static keyword


✔ Belongs to the class, not objects
✔ Can be accessed without creating an object
✔ Useful for constants, counters, utility methods
✔ Memory is allocated only once

Example:

class Counter {
static int count = 0; // static variable
Counter() {
count++;
}
static void showCount() {
[Link]("Count is: " + count);
}
}

public class StaticMemberExample {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
[Link]();
}}
Output:
Count is :3

1. 13. Arrays

An array in Java is a container that holds a fixed number of values of the same type. It
allows you to store multiple values in a single variable and access them using an index.

✔ Stores multiple values of the same type


✔ Elements are accessed by index (starting from 0)
✔ Can be of any data type – primitives or objects
✔ Helps in efficient data management

Declaration

int[] numbers;

Initialization

numbers = new int[5]; // Array of size 5

17 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Example

public class ArrayExample {


public static void main(String[] args) {
// Declare and initialize array
int[] numbers = {10, 20, 30, 40, 50};

// Access and print elements


[Link]("First element: " + numbers[0]);
[Link]("Third element: " + numbers[2]);

// Loop through the array


[Link]("All elements:");
for(int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}
}
}

Output:
First element: 10
Third element: 30
All elements:
10
20
30
40
50

1.14 Strings
In Java, a String is an object that represents a sequence of characters. The String class,
defined in the [Link] package, provides constructors and methods to create, manipulate,
and inspect sequences of characters. Strings are immutable, meaning once a String object is
created, its value cannot be changed.

Example:

public class StringExample {


public static void main(String[] args) {
String greeting = "Hello, Java!";

[Link]("String: " + greeting);


[Link]("Length: " + [Link]());
[Link]("First character: " + [Link](0));
[Link]("Uppercase: " + [Link]());
[Link]("Substring (7 to 11): " + [Link](7, 11));
String name = "Java";
if([Link]("Java")) {

18 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

[Link]("Strings are equal");


} else {
[Link]("Strings are not equal");
}
}
}

1.15 Inheritance

Inheritance is the process by which one class acquires the properties (data members) and
behaviors (methods) of another class. The class that inherits is called the subclass or derived
class, and the class from which it inherits is called the superclass or base class.

Types:

1. Single Inheritance
2. Multilevel Inheritance

3. Hierarchical Inheritance

Single Inheritance
In this type, a class inherits the properties and behaviors of one parent class.

Class A → Class B
B inherits from A

Example:

class Animal {

void eat() {

[Link]("Eating...");

class Dog extends Animal {

void bark() {

[Link]("Barking...");

19 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

Multilevel Inheritance
In this type, a class is derived from a child class, and this chain continues further. The
properties are passed from one class to the next.

Class A → Class B → Class C


C inherits from B, which inherits from A

Example:

class Animal {

void eat() {

[Link]("Eating...");

}}

class Mammal extends Animal {

void walk() {

[Link]("Walking...");

}}

class Dog extends Mammal {

void bark() {

[Link]("Barking...");

}}

3. Hierarchical Inheritance
In this type, multiple classes inherit from a single parent class. This allows different classes to
share the common properties of the base class.

Example:
Class A → Class B

class Animal {

void eat() {

[Link]("This animal eats food.");

20 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

class Dog extends Animal {

void bark() {

[Link]("The dog barks.");

class Cat extends Animal {

void meow() {

[Link]("The cat meows.");

1.16 Constructors in Inheritance

When a class inherits from a parent class, the constructor of the parent class is not inherited
by the child class, but it is automatically invoked when an object of the child class is created.
This ensures that the parent’s attributes are properly initialized before the child class adds its
own attributes or behaviors.

 Constructors are not inherited-Even though methods and variables are inherited,
constructors are not inherited.

 Parent constructor is called first-When a child class object is created, the constructor of
the parent class is invoked before the constructor of the child class.

 Use of super()-The child class can explicitly call the parent class’s constructor using the
super() keyword. If super() is not called explicitly, Java automatically inserts a call to the
no-argument constructor of the parent class.

 Parameter Passing-If the parent class constructor requires arguments, the child class
must explicitly call it using super(arguments).

Example:

class Animal {

Animal() {

[Link]("Animal constructor called");

21 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

class Dog extends Animal {

Dog() {

super(); // calls Animal's constructor

[Link]("Dog constructor called");

public class TestConstructorInheritance {

public static void main(String[] args) {

Dog d = new Dog();

Output:

Animal constructor called

Dog constructor called

1.17 Method Overriding

Method overriding is the process in which a subclass provides its own implementation of a
method that is already defined in its parent class. The method in the subclass must have the
same name, return type, and parameters as the method in the parent class. Overriding is used
to provide specific behavior to the subclass while still keeping the method’s general structure.

Example:

// Parent class
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

22 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

// Child class
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}

// Main class
public class TestOverriding {
public static void main(String[] args) {
Animal a = new Animal();
[Link](); // Calls parent class method

Dog d = new Dog();


[Link](); // Calls overridden method in child class
}
}
Output:

Animal makes a sound


Dog barks

1.18 Use of super()

The super() keyword is used to invoke the constructor of the parent class from the child
class. It ensures that the parent class is properly initialized before the child class’s constructor
executes its own code. The call to super() must be the first statement in the child class’s
constructor.

Uses of super():

1. To invoke the parent class’s constructor-This is done to initialize inherited


properties before adding new ones in the child class.
2. It must be the first statement in the constructor-Java requires that super() appears
before any other statement in the constructor.

3. It can pass parameters to the parent’s constructor-If the parent class constructor
requires arguments, super(arguments) is used to pass them.

4. Automatic call if not written-If you don’t explicitly call super(), Java
automatically inserts a call to the parent’s no-argument constructor.

Example:

// Parent class
class Animal {
Animal() {

23 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

[Link]("Animal constructor called");


}
Animal(String name) {
[Link]("Animal name is: " + name);
}
}
// Child class
class Dog extends Animal {
Dog() {
super(); // Calls Animal's no-argument constructor
[Link]("Dog constructor called");
}
Dog(String name) {
super(name); // Calls Animal's parameterized constructor
[Link]("Dog constructor called");
}
}

// Main class
public class TestSuper {
public static void main(String[] args) {
Dog dog1 = new Dog();
[Link]("-----");
Dog dog2 = new Dog("Tommy");
}
}

Output:

Animal constructor called


Dog constructor called
-----
Animal name is: Tommy
Dog constructor called

1.19 Abstract Classes and Interfaces

An abstract class is a class that cannot be instantiated and is designed to be extended by


other classes. It can contain both abstract methods (without implementation) and concrete
methods (with implementation). Abstract classes are used to define common behaviors for a
group of related classes while leaving certain methods to be implemented by the subclasses.

1. Declared with abstract keyword.


2. Can have both abstract and non-abstract methods.

3. Cannot create objects of an abstract class.

4. Provides a partial implementation that subclasses can reuse.

Example
24 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

abstract class Animal {


abstract void sound(); // abstract method
void eat() { // concrete method
[Link]("This animal eats food.");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class TestAbstract {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}

Output:

Dog barks
This animal eats food.

Interfaces

An interface is a collection of abstract methods that specify a behavior or capability that a


class must implement. Interfaces provide full abstraction, as all methods are implicitly
abstract and public. Interfaces help achieve multiple inheritance and separate the definition of
functionality from implementation. Or An interface is like a contract that a class agrees to
follow by providing specific behaviors (methods)

Key Points:

1. All methods are abstract and public by


2. Variables are static and final by default.

3. A class can implement multiple interfaces.

4. Interfaces are used to define a contract for what a class should do.

Example

interface Printable {
void print();
}
interface Showable {
void show();

25 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

}
class Demo implements Printable, Showable {
public void print() {
[Link]("Printing...");
}
public void show() {
[Link]("Showing...");
}
}
public class TestInterface {
public static void main(String[] args) {
Demo d = new Demo();
[Link]();
[Link]();
}
}
Output:
Printing...
Showing...

1.20 Dynamic Method Dispatch

Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at


runtime rather than at compile time. It is used to achieve runtime polymorphism, where the
reference type and the object type may be different, and the method that gets executed
depends on the actual object being referred to at runtime

Example:

class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


void sound() {
[Link]("Cat meows");
}
}
public class TestDynamicDispatch {
public static void main(String[] args) {
Animal a; // Parent class reference

26 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

a = new Dog(); // Dog object assigned to Animal reference


[Link](); // Calls Dog’s sound()

a = new Cat(); // Cat object assigned to Animal reference


[Link](); // Calls Cat’s sound()
}
}
Output:
Dog barks
Cat meows

1.21 Packages

A package is a collection of related classes and interfaces grouped together under a common
name. Packages are used to organize classes, avoid name conflicts, and control access. By
using packages, programmers can manage large software projects by grouping similar
functionality into separate modules.

Creating Packages:

 The package keyword is used at the beginning of a source file to declare its package.
 Classes and interfaces within the same package can access each other’s default and
protected members.

Importing Packages:

 The import keyword is used to access classes from other packages.


 import [Link].*; imports all classes in the [Link] package.

Example:

Create a package

// File: mypack/[Link]
package mypack;
public class Hello {
public void display() {
[Link]("Hello from mypack!");
}
}

Use the Package

// File: [Link]
import [Link];

public class TestPackage {


public static void main(String[] args) {
Hello h = new Hello();
[Link]();
27 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])


lOMoARcPSD|49915069

MC25106 Advanced Java Programming

}
}
Output:
Hello from mypack!

1.22. Exception Handling

Exception handling is a mechanism in Java to handle runtime errors, so that the normal flow
of the application is maintained. An exception is an abnormal condition that occurs during the
execution of a program, such as division by zero, invalid input, or file not found. Java
provides built-in classes and keywords to catch, handle, and throw exceptions to prevent
abrupt termination of the program.

 Exception – An abnormal event that disrupts the normal flow of the program.
 try block – Contains code that might throw an exception.
 catch block – Handles the exception and defines how to respond to it.
 finally block – Contains code that will be executed whether or not an exception
occurs.
 throw – Used to explicitly throw an exception.
 throws – Declares exceptions that a method might throw to be handled by the caller.

Example

public class SimpleTryCatchFinally {


public static void main(String[] args) {
int a = 10;
int b = 0;
int result;
try {
result = a / b; // This will cause ArithmeticException
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero.");
} finally {
[Link]("This block is always executed.");
}
[Link]("Program continues after exception handling.");
}
}

Output:

Error: Cannot divide by zero.


This block is always executed.
Program continues after exception handling.

28 Department of MCA

Downloaded by Kamalapraba (kamalapraba25@[Link])

You might also like