Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Introduction to Java
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Introduction
• Java is a high-level, object-oriented programming language developed
by Sun Microsystems in 1995 .
• Known for its "Write Once, Run Anywhere" capability, Java
applications can run on any device or platform that has the Java
Virtual Machine (JVM) installed.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction : Java Milestone
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction : Java Milestone
The name Java originates from a sort of espresso
bean, Java. Gosling came up with this name while
having a coffee near his office.
Java was created on the principles like Robust,
Portable, Platform Independent, High Performance,
Multithread, etc. and was called one of the Best
Products of 1995 by the TIME MAGAZINE.
Currently, Java is used in internet programming,
mobile devices, games, e-business solutions, etc.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction : Features of Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction : Features of Java
✓ Java is simple
✓ Java is object-oriented
✓ Platform Independent
✓ Java is distributed
✓ Java is Compiled and Interpreted
✓ Java is robust
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction : Features of Java
✓ Java is secure
✓ Java is architecture-neutral
✓ Java is portable
✓ Java’s performance
✓ Java is multithreaded
✓ Java is dynamic
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction : Features of Java
✓ Java is secure
✓ Java is architecture-neutral
✓ Java is portable
✓ Java’s High performance
✓ Java is multithreaded
✓ Java is dynamic and Extensible
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction of Java
Java Architecture
JVM (Java Virtual Machine): Executes Java bytecode.
JRE (Java Runtime Environment): Includes JVM and libraries
for running Java applications.
JDK (Java Development Kit): Includes JRE and tools like the
compiler for developing Java applications.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction of Java
Java in the Real World Applications:
• Web applications (using Java EE, Spring)
• Mobile applications (Android)
• Enterprise systems
• Scientific applications
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Basic Concepts of Java
Objects and Classes: Java is an object-oriented language. Objects are instances of
classes, which define a blueprint for objects.
Inheritance: Allows a new class to inherit properties and methods from an
existing class. Promotes code reusability.
Encapsulation: Bundles the data (variables) and methods that operate on the data
into a single unit or class. Access to the data is restricted through public methods.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Basic Concepts of Java
Polymorphism: Enables one interface to be used for a general class of
actions. The specific action is determined by the exact nature of the
situation.
Abstraction: Hides the complex implementation details and shows only the
essential features of the object.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction of Java
Conclusion
• Java is a versatile and powerful programming language
with broad applications.
• Understanding Java basics will enable you to develop
applications ranging from simple programs to complex
enterprise-level systems.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction of Java
Quiz for Today
1. Who developed Java, and when was it released?
2. What are the main features of Java
3. What was the main goal behind the creation of Java?
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Introduction to Java
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Introduction to Java
Why Java Continues to be a Top Choice for Developers ?
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Quiz for Today
1. Which feature of Java allows the same code to run on
multiple platforms without modification?
A. Robust
B. Object-oriented
C. Platform Independent
D. Multithreaded
2. What makes Java a "robust" programming language?
A. It supports pointers
B. It allows direct memory access
C. It has strong memory management and exception handling
D. It runs only on Windows
3. Which feature of Java helps in executing multiple tasks
simultaneously?
A. Distributed
B. Secure
C. Multithreaded
Complied By : Dr. Annu Sharma- Department of Computer Applications
D. Architecture Neutral
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
JVM and JRE Working
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
JVM and JRE Working
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
JVM and JRE Working
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
JVM and JRE Working
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
JVM and JRE Working
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
JVM and JRE Working
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
JVM and JRE Working
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
JVM and JRE Working
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Quiz for Today
1. What is Java bytecode?
A. The source code written by the programmer
B. The machine code generated by the compiler
C. The intermediate code generated by the Java compiler
D. The graphical output of a Java program
2. Which component of Java executes the bytecode?
A. Java Development Kit (JDK)
B. Java Runtime Environment (JRE)
C. Java Virtual Machine (JVM)
D. Java Compiler (javac)
3. What is the file extension of a compiled Java
bytecode file?
A. .java
B. .txt
C. .exe
D. .class Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Building Blocks of Java
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Architecture& JDK
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Installation
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Installation
• Download Java (Installation guide)
• Install Java JDK 24.0.2 (Current latest version)
• Set Environment variables – javac – (sys. Var / env var.) (jdk/bin)
• ‘javac’ and ‘java’
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Coding convention
• Class names / Interface - Camel case starting with a UPPER CASE
• Method names / variable names – Camel case starting with “lower” case
• Constants – All UPER CASE letters with under-score as separator
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Program structure
import [Link].*; OR
import [Link];
import [Link];
class Test {
public static void main(String[] args) {
[Link](“ Welcome to Java World”);
} } Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Java Compiler
javac:
➢ Checks for Syntax errors
➢ Converts .java file to .class intermediate file (byte code)
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Java Compiler
Java Enterprise Application Development
Java Compiler
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Java Compiler
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Execution of Java Program
• Execute .class files (without extension)- java
• ‘java’ - JVM
✓ loads the class file specified
✓ Calls main() method for execution
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
JAVA Myths
• Class name and file name should be same
• One program cannot have multiple classes – compiler error
• Program with multiple classes causes error while saving
• Class can have multiple public classes
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
The statement "Class name and file name should be same" is not a
myth, but it’s only partially true —
If your Java class is declared as public, then:
public class MyClass {
// code here
}
File name must be: [Link]
Otherwise, the compiler will throw an error:
error: class MyClass is public, should be declared in a file named [Link]
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
When class and file name can be different
If the class is not declared public, then:
class MyClass {
// code here
}
You can save this in any file name, like:
•[Link]
•[Link]
•[Link]
It will compile as long as there’s no public class in the file.
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Introduction TO JAVA
Multiple classes in one file?
Yes! You can have:
class A {
// class A
}
class B {
// class B
}
Saved in a file like [Link] — no problem.
But only one class in a file can be public, and its name
must match the file.
Complied By : Dr. Annu Sharma- Department of Computer Applications
Java Enterprise Application Development
Quiz for Today
[Link] component provides the tools to develop Java programs?
A. JRE
B. JVM
C. JDK
D. JIT
2. Which component is responsible for converting bytecode into machine code?
A. JDK
B. JVM
C. JRE
D. JIT
7. Which of the following is included in the JDK but not in the JRE?
A. JVM
B. Compiler (javac)
C. Java libraries
D. Java runtime
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Data Types
User Input in Java
Complied By : Dr. Annu Sharma Department of Computer Applications
BUILDING BLOCKS OF JAVA
Data Types in java
Java’s Primitive Types:
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Data Types in java
Java’s Build in Data Types
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Data Types in java
Java Literals
Literals:
Literals in Java are a sequence of characters (digits, letters, and other
characters) that represent constant values to be stored in variables.
Types of literals in java with example as shown here.
Important points:
• also commonly called constants.
• Java literals can be any of the primitive data types.
• Character constants are enclosed in single quotes.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Handling User Input / Output:
➢Java I/O (Input and Output) is used to process the
input and produce the output.
➢ uses the concept of stream to make I/O operation
fast.
➢ The [Link] package contains all the classes required
for input and output operations
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Input characters from the Keyword:
➢ To read a character from the keyboard we will use
[Link]().
➢ [Link] is the complement to [Link]
➢ It is the input object attached to the keyboard.
➢ The read() method waits until the user presses a key and
then returns the result.
➢ The character is returned as an integer, so it must be
cast into a char to assign it to a char variable.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Reading string:
String can be read using following classes
1. InputStreamReader
2. BufferedReader
3. Scanner
automatically import the
[Link] package
[Link] package
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Reading string:
String can be read using following classes
1. InputStreamReader -automatically import the
[Link] package
2. BufferedReader
3. Scanner --------------[Link] package
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java: Buffer Reader Example
import [Link];
import [Link]; try {
import [Link]; [Link]("Enter a string: ");
String input = [Link]();
public class BufferedReaderExample { [Link]("You entered: " +
public static void main(String[] args) { input);
BufferedReader reader = new } catch (IOException e) {
BufferedReader(new [Link]("An error occurred
InputStreamReader([Link])); while reading input.");
}
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
User Input in Java: Scanner Example
import [Link];
public class ScannerExample { // Display the inputs back to the user
public static void main(String[] args) { [Link]("\nHere is the
information you entered:");
Scanner scanner = new Scanner([Link]); [Link]("Name: " + name);
[Link]("Enter your name:"); [Link]("Age: " + age);
String name = [Link](); // Reads full line [Link]("Salary: " + salary);
[Link]("Enter your age:"); [Link]("Initial: " + initial);
int age = [Link](); // Reads an integer
[Link]("Enter your salary:"); // Close the scanner to free resources
double salary = [Link](); [Link]();
}
[Link]("Enter a single character:"); }
char initial = [Link]().charAt(0); // Reads a
single character
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Quiz for Today
1. Which class is commonly used in Java to take input from the user?
A. System
B. InputReader
C. Scanner
D. ConsoleReader
2. Which package must be imported to use the Scanner class?
A. [Link]
B. [Link]
C. [Link]
D. [Link]
3. Which of the following is a correct way to read an integer using Scanner?
A. nextInt();
B. [Link]();
C. [Link]();
D. [Link]();
6. What kind of literal is 3.14 in Java?
A. Integer literal
B. Character literal
C. Double literal Complied By : [Link] Sharma - Department of Computer Applications
D. Float literal
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
• Conditional statements: if, if-else, switch
• Iterative statements : for, while, do-while
• Transfer statements : break, continue, go to, return, try
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Selection or Conditional or Decision Statements:
Decision making structures have one or more conditions to be evaluated or tested, if
it is true the statements get executed and optionally, other statements to be executed
if the condition is determined to be false.
Types of Conditional statements
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Types of Conditional statements
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Types of Conditional statements
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Iteration Statements:A loop statement allows us to execute a statement or
group of statements multiple times. statements
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Iteration Statements:A loop statement allows us to execute a statement or
group of statements multiple times. statements
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Iteration Statements: A loop statement allows us to execute a statement or
group of statements multiple times. statements
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Iteration Statements: For - Each loop
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Iteration Statements: For - Each loop
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Iteration Statements: For - Each loop
public class LoopExample { // Using for-each loop
int sumEach = 0;
public static void main(String[] args) { for (int num : numbers) {
sumEach += num;
// Array of integers }
int[] numbers = {10, 20, 30, 40, 50}; [Link]("Sum using for-each loop: " +
sumEach);
// Using traditional for loop }
int sum = 0; }
for (int i = 0; i < [Link]; i++) {
sum += numbers[i];
}
[Link]("Sum using for loop: " + sum);
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Hands on Practice loop
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Iteration Statements:A loop statement allows us to execute a statement or
group of statements multiple times. statements
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
Hands on Practice loop
Write a Java program that takes an array of strings representing fruit names. The program should
iterate through the array using a for-each loop and categorize each fruit into one of three categories
using branching (if-else or switch):
•Category A: Fruits that start with letters A-M (case insensitive)
•Category B: Fruits that start with letters N-Z (case insensitive)
•Category C: Fruits that start with a vowel (a, e, i, o, u) — this category overrides A or B
For each fruit:
•Print the fruit name and its category.
•Keep a count of how many fruits fall into each category.
•At the end, print the total count for each category.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
[Link] of the Day:
What is the output of the following code?
int sum = 0;
for (int i = 1; i <= 5; i++)
{
if (i % 2 == 0) {
sum += i;
}
} [Link](sum);
A) 15
B) 6
C) 10
D) 0
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Branching Statements & Conditions
char[] letters = {'A', 'B', 'C', 'D'};
int score = 0;
for (char ch : letters) {
switch (ch) {
case 'A':
case 'B':
score += 5;
break;
case 'C':
score += 10;
break;
default:
score += 0;
}
}
[Link](score);
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Java Variables and Operators
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Java Tokens
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Tokens
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Language Elements
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Basics
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Variables
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Variables
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Basics
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Variables
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Local Variables
class JavaClass {
variables; (local, instance, static)-memory allocation??
stack, heap, metaspace(native-heap)
methods ; (instance, static)
constructors;
instance blocks;
static blocks;
} Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Variables
Stored in stack memory
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Local Variables
Example of Local Variable
public class Main {
public static void main(String[] args) {
// Declare a local variable
int localVar = 10;
// Display the value of the local variable
[Link]("The value of the local variable is: " +
localVar);
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Instance Variable
➢ Stored in heap memory
➢ Belongs to object (instance)
➢ Automatically initialized to default values
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Instance Variables
Instance Variable Example
public class InstanceExample {
String name = ”Annu"; // instance variable
public static void main(String[] args) {
InstanceExample obj = new InstanceExample();
[Link]("Instance variable name: " + [Link]);
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Local and Instance Variables
Example of Local and Instance Variable
public class Person {
// Instance variable
String name = ”Annu";
public static void main(String[] args) {
// Create an object of the Person class
Person p = new Person();
// Local variable
String message = "Hello";
// Accessing instance variable using object
[Link](message + ", " + [Link] + "!");
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Static Variables
Static Variables
➢ Static variables are declared using the static keyword.
➢ They belong to the class, not the instance.
➢ only one copy exists, shared among all objects.
➢ Stored in method area (part of JVM memory)
➢ Loaded when class is loaded
➢ Can be accessed without object
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Static variable
Example of Static Variable
public class StaticExample {
static int counter = 0; // static variable
public static void main(String[] args) {
[Link]++;
[Link]("Static variable counter: " +
[Link]);
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Variable
Memory Allocation
Variable Type Memory Location Lifetime Accessed via
During method
Local Stack Method/block only
execution
Until object is garbage
Instance Heap Object
collected
Static Method Area Until class is unloaded Class or object
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
JAVA Variables
Observations :
Instance / static variables need not be assigned – default values are assigned
Memory allocation / de-allocation for different variables –
• local variable memory is released when it loses its scope
• Instance variable memory is released when the object is destroyed
• Static memory is released when the class is destroyed
Accessing local / instance / static variables
Local variables need to be initialised – but before using. (If not using??)
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Unary Operators
• Bitwise and Shift Operators
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Operators
Arithmetic Operators
Symbol Meaning Example
+ Add two values 2 + 3 //5
- Subtract two values 2 - 3 //-1
* Multiply two values 6 * 3 //18
/ Divide two values 9 / 2 //4.5
∼/ Integer division of two values 9 ~/ 2 //4
Remainder (modulo) of an int
% 5 % 2 //1
division
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Arithmetic Operators
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Relational Operators
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Logical Operators
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Bitwise Operators
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Operators
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Unary Operators
• Bitwise and Shift Operators
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Operators Program
public class AllOperatorsDemo { [Link]("\n===== Logical Operators =====");
boolean x = true, y = false;
public static void main(String[] args) { [Link]("x && y: " + (x && y));
[Link]("===== Arithmetic Operators "); [Link]("x || y: " + (x || y));
int a = 10, b = 3; [Link]("!x: " + (!x));
[Link]("a + b = " + (a + b));
[Link]("a - b = " + (a - b)); [Link]("\n= Assignment Operators =");
[Link]("a * b = " + (a * b)); int num = 5;
[Link]("a / b = " + (a / b)); [Link]("num = " + num);
[Link]("a % b = " + (a % b)); num += 3;
[Link]("num += 3: " + num);
[Link]("\n===== Relational Operators="); num *= 2;
[Link]("a == b: " + (a == b)); [Link]("num *= 2: " + num);
[Link]("a != b: " + (a != b)); num -= 4;
[Link]("a > b: " + (a > b)); [Link]("num -= 4: " + num);
[Link]("a < b: " + (a < b)); num /= 2;
[Link]("a >= b: " + (a >= b)); [Link]("num /= 2: " + num);
[Link]("a <= b: " + (a <= b)); num %= 3;
Complied By : [Link] Sharma - Department of Computer Applications
[Link]("num %= 3: " + num);
Java Enterprise Application Development
Java Java Operators
[Link]("\n===== Unary Operators =");
int p = 5;
[Link]("p: " + p); [Link]("\n=== Ternary Operator =====");
[Link]("++p: " + (++p)); int max = (a > b) ? a : b;
[Link]("p++: " + (p++)); [Link]("Max of a and b: " + max);
[Link]("--p: " + (--p));
[Link]("p--: " + (p--)); [Link]("\n ==instanceof Operator ===");
[Link]("Final p: " + p); String str = "Hello";
[Link]("str instanceof String: " + (str
[Link]("\n===== Bitwise Operators ="); instanceof String));
int bitA = 5; // 0101 }
int bitB = 3; // 0011 }
[Link]("bitA & bitB: " + (bitA & bitB));
[Link]("bitA | bitB: " + (bitA | bitB));
[Link]("bitA ^ bitB: " + (bitA ^ bitB));
[Link]("~bitA: " + (~bitA));
[Link]("bitA << 1: " + (bitA << 1)); // Left
[Link]("bitA >> 1: " + (bitA >> 1)); // Right
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Quiz of the day
1. Which of these is not a valid Java variable name?
A) _count
B) $value
C) 2ndValue
D) firstName
2. What is the result of true || false && false in Java?
A) true
B) false
C) Compilation error
D) Runtime error
3. What type of variable is shared across all instances of a class?
A) Local variable
B) Instance variable
C) Final variable
D) Static variable
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Java Arrays
➢ An array is a data structure used to store multiple values
of the same type in a single variable.
➢ Arrays are fixed in size once declared.
➢ Example:
int[] numbers = new int[5];
➢ Efficient way to store and manage collections of data.
➢ Helps in avoiding multiple variable declarations.
➢ Useful in loops and data processing.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Indexed collection of fixed number of homogeneous
elements.
Arrays Declaration:
int [ ] x;
int [ ]x;
int x[ ];
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Indexed collection of fixed number of homogeneous
elements.
Declaration (1-D):
int [ ] x;
int [ ]x;
int x[ ];
int[10] x;
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Declaration (2-D):
int [ ] [ ] x;
int [ ] [ ]x;
int x[ ] [ ];
int[ ] [ ] x;
int[ ] x [ ];
int [ ] x [ ];
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Declaring and Initializing Arrays
// Declaration
int[] marks;
// Initialization
marks = new int[5];
// Declaration + Initialization
int[] marks = {90, 80, 70, 85, 95};
Accessing Array Elements
•Array indices start from 0.
•Example:
[Link](marks[2]); // prints 70
Looping Through Arrays
for (int i = 0; i < [Link]; i++) { [Link](marks[i]); }
•Use for-each loop for cleaner syntax:
for (int mark : marks) { [Link](mark); }
Java Enterprise Application Development
Java Arrays
Example :1
Java Enterprise Application Development
Java Arrays
Java Enterprise Application Development
Java Arrays Quiz
Every array in java is an object.
int [ ] a; -- What is the size?
int [ ] a = new int[5];
int [ ] a = new int[0]; ??
int [ ] a = new int[-3]; ??
int[ ] a = new int[‘b’]; ??
Demonstration to identify class name.
Java Enterprise Application Development
Java Arrays
Demonstration:
1. Program to find the largest of numbers in a
given array.
2. Program to find TRACE of a given square
matrix.
Java Enterprise Application Development
Java Arrays
Class Assignment :
Find the class name for 1-D and 2-D arrays of all other
primitive data types.
public class Main {
public static void main(String[] args) {
int[] intArray = new int[10];
String[] stringArray = new String[10];
// Get class name of the arrays
[Link]("Class name of intArray: " + [Link]().getName());
[Link]("Class name of stringArray: " + [Link]().getName());
}
}
Java Enterprise Application Development
Java Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Traditional multi-dimensional Arrays
Java’s Array of Arrays for multi-dimensional Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Example 2D Array
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Using Array Length Member
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays Practice Program
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays Practice Program
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Arrays
Arrays Quiz:
• What will be the default values stored in an array? Why?
• How do you apply Array of Arrays concept to a 3-D array?
• What will be the output of:
int [ ] [ ] x = new int [2][3];
Sop(x);
Sop(x[0]);
Sop(x[0][0]);
Complied By : [Link] Sharma - Department of Computer Applications
JEAD
Arrays
Array Instantiation:
1-D Array:
int [] x = { 5, 10, 15, 20, 25 };
2-D Array :
int[ ] [ ] x = { { 5, 2}, { 10, 20, 30 } };
Quiz:
What is the dimension of the given array:
{ { {10,20,30}, { {5 , 6}, { 60, 70, 80} } }
Java Enterprise Application Development
Java Arrays
Quiz:
1. Which of the following correctly declares an array in Java?
A) int arr[] = new int(5);
B) int arr[] = int[5];
C) int[] arr = new int[5];
D) array arr = new array[5];
2. What is the dimension of the given array:
{ { {10,20,30}, { {5 , 6}, { 60, 70, 80} } }
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Java Methods and Strings
Dr. Annu Sharma
Associate Professor
Java Enterprise Application Development
Java Methods
Methods
A method contains the statement that define its action.
➢ Each method has a name
➢ It is the same name used to call the method
➢ General form
Return-type name(parameter-list)
{
//body of method
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Methods
Methods
re-type method_name(parameter-list)
{
//body of method
}
➢ Here, return_type is nothing but the value to be returned to an calling
method.
➢ method_name is an name of method that we are going to call through
any method.
➢ Parameter –list are the different parameters that we are going to pass to
a method
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Methods
Methods
Return type of method
1. Method can return any type of value.
2. Method can return any Primitive data type.
3. Method can return Object of Class Type.
4. Method sometimes may not return value.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Methods
Methods
Method Name
1. Method name must be valid identifier.
2. All Variable naming rules are applicable for writing Method Name.
Parameter List
1. Method can accept any number of parameters.
2. Method can accept any data type as parameter.
3. Method can accept Object as Parameter
4. Method can accept no Parameter.
5. Parameters are separated by Comma.
6. Parameter must have Data Type
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Methods
Returning from a method
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Methods
Methods
Using Parameters
➢ It is possible to pass one or more values to a method when the method is
called.
➢ A value passed to a method is called an argument.
➢ Inside the method, the variable that receives the argument is called a
parameter.
➢ Parameters are declared inside the parentheses that follow the method’s name.
➢ The parameter declaration syntax is the same as that used for variables
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Methods
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Methods
Methods: object as Parameter
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Methods
// Method accepting multiple parameters
public class MethodExamples {
public void printMultiple(int a, double b, String c) {
// Method accepting no parameters
[Link]("Int: " + a + ", Double: " + b + ",
public void sayHello() {
String: " + c);
[Link]("Hello, no parameters!");
}
}
public static void main(String[] args) {
// Method accepting a single data type (int)
MethodExamples obj = new MethodExamples();
public void printData(int num) {
[Link]("Integer: " + num);
[Link](); // No parameters
}
[Link](10); // Single int
[Link](new [Link]()); // Object as
// Method accepting Object as parameter
parameter
public void printObject(Object obj) {
[Link](1, 2.5, "Test"); // Multiple
[Link]("Object: " + [Link]());
parameters
}
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Java Strings
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Immutable: Once created, the value of a string cannot be changed.
Any modification creates a new string object, which helps ensure data
integrity and security.
String Class: Strings are instances of the String class in Java, which
provides numerous methods for string manipulation, such as length(),
charAt(), substring(), replace(), and more.
Concatenation: You can concatenate strings using the + operator
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Constructing Strings
Java maintains special memory called: String literal pool
Is a pool of unique Strings: avoid duplicate
• Using
➢ o String literal
➢ o new keyword
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Constructing Strings
String literal
• Strings are maintained in String literal Pool of a Heap. ( String
constant pool)
• String literal Pool is a pool of unique Strings, It avoids
duplicate String objects in
heap memory.
• String str =”Hello”;
• Whenever compiler encounters a string literal, it creates a
String object with given
string value.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Constructing Strings
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Java Strings
Constructing Strings
Using new keyword
• String str = new String( );
• JVM doesn't perform String pool check if you create object using new operator.
• Always creates new string object.
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Java Strings
The String Constructors
Different forms of Constructors.
1. String ( )
a. Creates object with no characters
b. example: String str = new String( );
2. String (char charArr[ ]) or
3. String (char charArr[ ], int startindex, int numchars)
c. Creates string using char Array
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Java Strings
The String Constructors Example
public class StringExample {
public static void main(String[] args) {
char charArr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String str1 = new String(charArr);
[Link](str1); // Output: abcdef
String str2 = new String(charArr, 2, 3);
[Link](str2); // Output: cde
}
}
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Java Strings
The String
4
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Java Strings
The Strings
Java supports three especially useful string features within the syntax of
the language.
• They are:
a. String literal
b. String concatenation
c. Overriding toString( )
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Java Strings
[Link] literal
• A string literal is created by specifying a quoted string. For each string literal in your
program, Java automatically constructs a String object.
Example: String str = “MCA in PES”;
b. String concatenation:
• In java, string concatenation forms a new string that is the combination of multiple
strings.
• There are two ways to concatenate string in java:
1. Using operator: +(string concatention) operator
2. Using method : concat( )
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Java Strings
Example1: Example2:
public class TestStringConcatenation2 {
public class TestStringConcatenation1 { public static void main(String[] args)
public static void main(String[] args) { {
String s = "Sachin" + " Tendulkar"; String s1 = "Sachin ";
[Link](s); // Output: Sachin String s2 = "Tendulkar";
Tendulkar // Concatenating using the concat()
} method
} String s3 = [Link](s2);
[Link](s3);
}
Complied By : [Link] Sharma - Department of Computer Applications }
Java Enterprise Application Development
Java Strings
[Link] toString( ):
➢ If you want to represent any object as a string, toString() method comes
into existence.
➢ The toString() method returns the string that describes the object.
➢ By overriding the toString() method of the Object class, we can return
values of the object, so we don't need to write much code.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Example: // Main method
public class StringStudent { public static void main(String[] args) {
int rollno; // Creating a Student object
String name; StringStudent s = new StringStudent(101,
"Anil");
// Constructor to initialize student details
StringStudent(int rollno, String name) { // Printing the Student object (calls toString()
[Link] = rollno; method implicitly)
[Link] = name; [Link](s); // Output: 101 Anil
} }
// Overriding the toString() method }
@Override
public String toString() {
return rollno + " " + name;
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
The Length( ) Method
➢ The method length( ) returns the length of the string.
➢ A string’s length is the number of characters that it contains.
General form
int length( )
Example:
String str =”PESMCA”
[Link]([Link]( ) ); // displays 6
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Demonstrate String functions:
charAt(), substring(), toUpperCase(), toLowerCase(),
equals(), equalsIgnoreCase(), replace(), split(), contains() etc.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Strings
Obtaining the characters within a string
• String class provides three ways in which
character can be obtained from a string.
a) charAt( )
b) getChars( )
c) toCharArray( )
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Obtaining the characters within a string
• String class provides three ways in which character
can be obtained from a string.
a) charAt( )
b) getChars( )
c) toCharArray( )
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
char [ ]charArr = “PES”.toCharArray() ;
for( char ch: charArr)
[Link](charArr);
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Different methods used for string comparison are
1. equals() and equalsIgnoreCase()
2. regionMatches()
3. startsWith() and endsWith()
4. equals() VS ==
5. compareTo()
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Complied By : [Link] Sharma - Department o
Computer Applications
Java Enterprise Application Development
Java String Operations
regionMatches( )
• compares a specific region inside a string with another
specific region in another string.
• It has two overloaded forms:
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
regionMatches( )
Parameter List
Length
The length of the substring being compared is passed in
numChars.
IgnoreCase
if ignoreCase is true, the case of the characters is ignored.
Otherwise,
case is significant.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
equlas( ) vs ==
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
compareTo( )
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
using indexOf( ) and lastIndexOf( )
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
using indexOf( ) and lastIndexOf( )
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Changing the case of characters within a string
Returns a copy of this string converted to lowercase
or uppercase.
• If no conversions are necessary, these methods
return the original string.
• General form:
String toLowerCase( )
String toUpperCase( )
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Changing the case of characters within a string: Example
class StringUpperCaseDemo {
public static void main(String[] args) {
String name = "Pes";
[Link]("Name in Upper Case: " +
[Link]() );
[Link]("Name in Lower Case: " +
[Link]() );
[Link]("Original name: " + name);
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Obtaining a modified String
Different methods for searching a string
a) substring()
b) concat()
c) replace()
d) trim()
e) valueOf()
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Java String Operations
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
replace( )
• Syntax
public String replace(char oldChar, char newChar)
• It returns a string derived from this string by replacing every occurrence of oldChar with
newChar.
• Example:
import [Link].*;
public class Test{
public static void main(String args[]){
String Str = new String("Welcome to PES");
[Link]("Return Value :" );
[Link]([Link]('o', 'T'));
[Link]("Return Value :" );
[Link]([Link]('E', 'D'));
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Example
public class Test{
public static void main(String args[]){
String Str = " Welcome to [Link]";
[Link]("Return Value :" );
[Link]([Link]( ) );
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java String Operations
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Experiential Learning
Banana Problem
Program -1
Digital Clock: Display current time live in the console.
Program -2
Find Palindromic Words: Accept a sentence and list all palindrome words.
Orange Problem
• Password Strength Checker: Accept a password and check if it meets rules
(length, digits, special chars).
• Simple Calendar Generator: Accept month and year, print a calendar
layout.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Experiential Learning
Jackfruit Problem.
Word Guess Game (Anagram Challenge)
Category: Strings, Command-line, Logic
Accept a word through command line and present it to the user with
jumbled letters.
Allow the user 5 chances to guess the correct word.
Display success/failure and the number of attempts used.
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Java Classes And Objects
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Java Classes And Objects
Java Classes and Objects
What are Classes?
• Blueprint or template for creating objects.
• Defines properties (attributes) and behaviors (methods).
What are Objects?
• Instances of a class.
• Real-world entities created using a class.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Class Concept
Objects and Classes: Java is an object-oriented language.
Objects are instances of classes, which define a blueprint for
objects.
Inheritance: Allows a new class to inherit properties and methods
from an existing class. Promotes code reusability.
Encapsulation: Bundles the data (variables) and methods that
operate on the data into a single unit or class. Access to the data
is restricted through public methods.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Class Concept
Polymorphism: Enables one interface to be used for a general
class of actions. The specific action is determined by the exact
nature of the situation.
Abstraction: Hides the complex implementation details and
shows only the essential features of the object.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Java Classes And Objects
Java Classes
In object-oriented programming, a class is a blueprint for creating objects. A class
defines the properties and methods that an object will have. For example, a class
called Dog might have properties like breed, color and methods like bark, run.
Declaring Class In Java
You can declare a class in java using the class keyword followed by class name and
braces {}. It’s a good habit to write class name in PascalCase. For example,
Employee, Student, QuizBrain, etc.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Class Concept
Syntax
class ClassName {
// properties or fields
// methods or functions
}
In the above syntax:
• The class keyword is used for defining the class.
• ClassName is the name of the class.
• Body of the class consists of properties and functions.
• Properties are used to store the data. It is also known as fields or attributes.
• Functions are used to perform the operations. It is also known as methods.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Java Classes And Objects
Java Class
import [Link].*; OR
import [Link];
import [Link];
class Test {
public static void main(String[] args) {
[Link](“Welcome to Java
World”);
} } Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Classes And Objects
Java Objects
• Java is object-oriented programming, and everything is treated as an
object in java.
• An object is a variable or instance of the class used to access the
class's properties.
• Objects have two features - State and Behavior.
• Programming objects are theoretically similar to the real-life objects;
they also have state and behavior.
• An object is created from a template which is known as class.
• The fields of the classes are stored as object states, whereas the
method represents an object's behavior.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Classes And Objects
Java Objects
• Class names / Interface - Camel case starting with a UPPER CASE
• Method names / variable names – Camel case starting with “lower” case
• Constants – All UPER CASE letters with under-score as separator
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Classes And Objects
Class – Logical component
Object – Physical component
One class – multiple objects
Keywords:
Class – ‘class’
Objects – ‘new’
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Java Classes And Objects
Java Objects
Creating Class Objects in Java
After creating the class, we can create an instance or object of that class. The new keyword is used to declare class
followed by the class name. general syntax of creating object
Syntax for creating object
Class name object_name = new class_name(<constructor_arguments>);
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Class & object Concept
Syntax to create an object:
ClassName objectName = new ClassName();
Example:
Car myCar = new Car();
[Link] = "Red";
[Link] = "Toyota";
[Link]();
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Functions in Java
Understanding Methods in Java Programming
Dr. Annu Sharma
Department of Computer Applications
Java Technologies
Java Functions and methods
Java Functions
➢ Functions in Java are called methods.
➢ A function is a block of code that performs a specific task.
➢ It Improves code reusability and modularity.
Structure of a Java Method
returnType methodName(parameters) { // method body }
➢ returnType: Data type returned (or void)
➢ methodName: Name of the method
➢ parameters: Input values (optional)
➢ method body: Code to execute Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Functions and methods
Java Functions
Example of a Java Method
public int add(int a, int b) { return a + b; }
•Method name: add
•Parameters: int a, int b
•Return type: int
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Functions and methods
Types of Methods in Java
Predefined Methods (e.g., [Link]())
User-defined Methods (created by the programmer)
Static Methods
Instance Methods
Feature Static Method Instance Method
Called using Class name Object of the class
Access to this No Yes
Memory Single copy shared Separate per object
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Functions and methods
Method syntax and signature:
Permission static(op) return_type fun_name(parameter list)
throws Exception_type
{
statements
return (data ??)
}
Significance of method signature
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Types of Methods in Java Example
public class MethodTypeExample {
public static void main(String[] args) {
// Static method - belongs to the class // Calling static method - no object needed
static void staticMethod() { [Link]();
[Link]("This is a static method.");
} // Creating object to call instance method
MethodTypeExample obj = new
// Instance method - belongs to an object MethodTypeExample();
void instanceMethod() { [Link]();
[Link]("This is an instance }
method."); }
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Types of Methods in Java Example
Demonstration:
• Calling a method without parameters
• Calling a method with parameters
• Calling a method with ‘objects’ as parameters
• Calling a method which returns an ‘object’
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Types of Methods in Java Example
class Person1 { // Method with parameters
String name; void greet(String greeting) {
[Link](greeting + ", " + name + "!");
// Constructor }
// Method that accepts an object as parameter
Person1(String name) {
void compareNames(Person1 other) {
[Link] = name;
} if ([Link]([Link])) {
// Method to display name (no parameters) [Link]("Same names: " +
name);
void displayName() {
} else {
[Link]("Name: " + name); [Link]("Different names: " +
name + " vs " + [Link]);
} } Complied By : [Link] Sharma - Department of Computer Applications
}
Java Technologies
Types of Methods in Java Example
// 1. Calling method without parameters
// Method that returns an object [Link]();
Person1 clonePerson() { // 2. Calling method with parameters
return new Person1([Link] + "clone"); [Link]("Hello");
}
} // 3. Calling method with object as
parameter
public class MethodExample2 {
[Link](p2);
public static void main(String[] args) {
// 4. Calling method that returns an object
// Creating Person1 objects
Person1 p3 = [Link]();
Person1 p1 = new Person1("Annu"); [Link]();
}
Person1 p2 = new Person1("Babita"); }
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Class Objects & Constructors in Java
Dr. Annu Sharma
Department of Computer Applications
Java Enterprise Application Development
Class Objects in Java
Assessing Instance Variable and FunctionFeatures Of OOP
• After creating an object, we can access the fields and methods
of the class.
• The class property name is separated by the (.) operator with
the instance name.
syntax
[Link] or [Link]()
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Class Objects in Java
Assessing Instance Variable and FunctionFeatures Of OOP
Example:
[Link] = "Abhay";
[Link] = 4;
[Link] = 10;
[Link](); - Function Call in Java
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Class Objects in Java
Benefit of Objects
• Modularity: The source code of an object can be maintained individually and
can hide from the other object's source code.
• Data - hiding: Using oops programming, the details of the internal
functionality of code are hidden from the others.
• Reusability - We don't need to write the same code again and again. We can
use the object of class multiple times in our program.
• Pluggability and debugging easy - If any object is creating a problem in our
program, and then we can replace it in our program and plug the new object
as its replacement. The oops code can be easy to debug.
Complied By : Annu Sharma - Deptment of Computer Applications
Java Technologies
Class Objects in Java
Points to Remember
• The class is declared using the class keyword.
• The class is a blueprint for creating objects.
• The class body consists of properties and methods.
• The properties are also known as fields, attributes, or data
members.
• The methods are also known as behaviors, or member functions.
Assignment
Create a class Book with three properties: name, author, and price. Also, create
a method called display, which prints out the values of the three properties.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Constructors in Java
Java Constructors
• A constructor is a special function of the class that is responsible for
initializing the variables of the class.
• Java defines a constructor with the same name as that of the class.
• The constructor is used to initialize an object when it is created.
• A constructor is a function and hence can be parameterized.
• Constructors cannot have a return type.
• If you don’t declare a constructor, a default no-argument constructor
is provided for you.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Constructors in Java
Java Constructors Example
Syntax
Class Student{
class ClassName { Student(){
ClassName() { }
} }
}
We must remember the following two rules while creating a constructor.
• The constructor name should be same as the class name.
• The constructor doesn't have explicit return type.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Java Constructors
Types of Constructor
There are three types of constructors in Java
➢ Default Constructor or no-arg Constructor
➢ Parameter Constructor
➢ Constructor Overloading
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Constructors in Java
Default Constructor or no-arg Constructor
➢ A Constructor which has no parameter is called default constructor or no-arg
constructor.
➢ It is automatically created (with no argument) by compiler if we don't declare in the
class.
➢ The compiler ignores the default constructor if we create a constructor with argument
or no argument.
Syntax:
class ClassName {
ClassName() {
// constructor body
}
Complied By : Annu Sharma - Deprtment of Computer Applications
}
Java Enterprise Application Development
Constructors in Java
Default Constructor or no-arg Constructor Example
void main() {
// Call constructor automatically when we creates an object
Student std = new Student();
}
class Student{
// Declaring a construstor
Student()
{
[Link]("The example of the default constructor");
}
}
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Constructors in Java
Parameterized Constructor
• We can also pass the parameters to a constructor that type of constructor
is called parameterized constructor.
• It is used to initialize instance variables.
• Sometimes, we need a constructor which accepts single or multiple
parameters.
• The parameterized constructors are mainly used to initialize instance
variable with own values.
Syntax:
class ClassName {
ClassName(parameter_list) {
// constructor body } By : Annu Sharma - Deprtment of Computer Applications
Complied
Java Enterprise Application Development
Constructors in Java
Parameterized Constructor Example
void main() {
// Creating an object
Student std = new Student("Shashank",26);
}
class Student{
// Declaring a parameterized constructor
Student(String str, int age){
[Link](”The name: " + name);
[Link](”The age: " + age);
}
}
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Constructors in Java
Overloading Constructor :
The constructor is an overloaded constructor that takes parameter.
• We can also pass the parameters to a constructor .
• It demonstrates constructor overloading by defining multiple
constructors with different signatures.
• Sometimes, we need a multiple constructor which accepts single or
multiple parameters. .
• Constructor overloading is Creating multiple constructors with different
parameter lists.
• It Allows flexibility in object initialization.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Java Constructors Example
class ConstructorExample {
// 1. Default Constructor (No parameters)
ConstructorExample() { public static void main(String[] args) {
[Link]("Default constructor called"); // Calling the default constructor
} ConstructorExample obj1 = new
ConstructorExample();
// 2. Parameterized Constructor (With parameters)
ConstructorExample(int x, String name) { // Calling the parameterized constructor
[Link]("Parameterized constructor ConstructorExample obj2 = new
called"); ConstructorExample(10, ”Chethna");
[Link]("x: " + x + ", name: " + name);
} // Calling the overloaded constructor
ConstructorExample obj3 = new
// 3. Constructor Overloading (Multiple constructors) ConstructorExample("Hello, World!");
ConstructorExample(String message) { }
[Link]("Constructor with String }
parameter: " + message); Complied By : Annu Sharma - Deprtment of Computer Applications
}
Java Enterprise Application Development
Constructors in Java
Constructor Chaining
➢ Calling one constructor from another within the
same class.
➢ this() is used to call a constructor from another
constructor in the same class.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Constructors in Java
Constructor Chaining Example
class Student { // Constructor with one parameter (calls
String name; another constructor)
int age; Student(String name) {
this(name, 18); // Constructor chaining
// Constructor with two parameters }
Student(String name, int age) {
[Link] = name; void display() {
[Link] = age; [Link]("Name: " + name + ",
} Age: " + age);
}
}
public static void main(String[] args) {
Student s1 = new Student("Dave");
[Link]();
}
Complied By : Annu Sharma - Deprtment}of Computer Applications
Java Enterprise Application Development
Constructors in Java
Points to Remember
➢ Constructors are crucial for object initialization in Java.
➢ Parameterized constructors provide flexibility by
allowing the initialization of objects with specific values.
➢ Constructor overloading and constructor chaining
enhance flexibility and code clarity.
Complied By : Annu Sharma - Deprtment of Computer Applications
Java Enterprise Application Development
Java Classes And Objects. Experential Learning
1. a) Write a program to disprove that a Java class name and file-name need not be same.
b) Write a program to verify if a java file can hold multiple classes and execute.
2. Write a Java program to calculate the parking fee in a mall:
•First 2 hours: Rs. 20/hour
•Next 3 hours (3–5): Rs. 30/hour
•Beyond 5 hours: Rs. 50/hour
•Flat entry fee: Rs. 10
3. Write a Java program to simulate a basic shopping cart system where:
•Each product has a name, quantity, and price.
•A constructor initializes the product.
•A method calculates the total cost for the product (quantity × price).
•Another method displays product details.
HINT:
Use constructors to set values when creating an object.
Use methods to separate logic (like cost calculation and display).
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Inheritance in Java
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object.
➢ It is an important part of OOPs (Object Oriented programming system).
➢ 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.
➢ you can add new methods and fields in your current class also.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Why Do We Need Java Inheritance?
➢ Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
➢ Method Overriding: Method Overriding is achievable only through Inheritance. It is
one of the ways by which Java achieves Run Time Polymorphism.
➢ Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Important Terminologies Used in Java Inheritance
➢ Class: Class is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. It is just a template or blueprint or prototype from which objects are created.
➢ Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base
class or a parent class).
➢ Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.
.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
The syntax of Java Inheritance
class Subclass-name extends Superclass-
name
{
//methods and fields
}
The extends keyword indicates that you are
making a new class that derives from an
existing class. The meaning of "extends" is
to increase the functionality.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Example Inheritance
class Employee{
float salary=40000;
class Programmer extends Employee{
int bonus=10000;
}
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
} Complied By : Annu Sharma - Department of Computer Applications
}
Java Enterprise Application Development
Inheritance in Java
Types of Inheritance in java
On the basis of class, there can be three types of
inheritance in java:
➢ Single
➢ multilevel
➢ hierarchical.
In java programming, multiple and hybrid
inheritance is supported through interface only.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Types of Inheritance in java
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Types of Inheritance in java
Single Inheritance Example
When a class inherits another class, it is
known as a single inheritance. For
Example the example, Dog class inherits
the Animal class, so there is the single
inheritance.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Single Inheritance Example
class Animal{
void eat(){
[Link]("eating...");}
}
class Dog extends Animal{
void bark(){
[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Multilevel Inheritance Example
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Multilevel Inheritance Example
class Animal{
void eat(){ class TestInheritance2{
[Link]("eating...");} public static void main(String args[]){
} BabyDog d=new BabyDog();
class Dog extends Animal{
void bark(){ [Link]();
[Link]("barking...");} [Link]();
} [Link]();
class BabyDog extends Dog{ }}
void weep(){
[Link]("weeping...");}
}
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Hierarchical Inheritance Example
class Animal{ class TestInheritance3{
void eat(){[Link]("eating...");} public static void main(String args[]){
} Cat c=new Cat();
class Dog extends Animal{ [Link]();
void bark() [Link]();
{ //[Link]();//[Link]
[Link]("barking...");} }}
}
class Cat extends Animal{
void meow()
{
[Link]("meowing...");}
}
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Types of Inheritance in java
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Why multiple inheritance is not supported in java
➢ To reduce the complexity and simplify the language, multiple inheritance is
not supported in java.
➢ Consider a scenario where A, B, and C are three classes. The C class inherits
A and B classes. If A and B classes have the same method and you call it
from child class object, there will be ambiguity to call the method of A or B
class.
➢ Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Why multiple inheritance is not supported in java
1. class C extends A,B{ //suppose if it were
1. class A{
2.
2. void msg()
3. public static void main(String args[]){
3. {
4. C obj=new C();
4. [Link]("Hello MCA");}
5. [Link]();//Now which msg() method would be
5. } invoked?
6. class B{
6. }
7. void msg()
7. }
8. {
This will show compile-time errors .
9. [Link]("Welcome MCA");}
10. }
11. class C extends A,B{ //suppose if it were
12.
13.
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java
Inheritance Program in java.
Q- Write a java program for vehicle management system by building a simple
class structure where:
➢ Vehicle is the base class
➢ Car inherits from Vehicle (Single Inheritance)
➢ ElectricCar inherits from Car (Multilevel
Inheritance)
➢ Bike also inherits from Vehicle (Hierarchical
Inheritance)
Complied By : Annu Sharma - Department of Computer Applications
Java Enterprise Application Development
Inheritance in Java Quiz of the day
1. Which keyword is used to inherit a class in Java?
A. inherits 1.B
B. extends 2.C
C. implements 3.C
D. super
2. Which of the following is NOT a type of inheritance supported in Java?
A. Single inheritance
B. Multilevel inheritance
C. Multiple inheritance with classes
D. Hierarchical inheritance
3. What does the super keyword refer to in Java?
A. It calls the child class constructor
B. It refers to the current object
C. It refers to the parent class object
D. It creates an object
Complied By : Annu Sharma - Department of Computer Applications
THANK YOU
Dr. Annu Sharma
Associate Professor
Department of Computer Science
Java Technologies
(UQ23CA252A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Technologies
Java Interfaces
Complied By : Vinita Nair - Department of Computer
Applications
Java Technologies
JJava Interfaces
Interface Fundamentals :
An Interface defines a set of variables and methods that
will be implemented by a class.
It is not a class but similar to abstract classes, except
that no method can include a body.
An interface contains the behaviour that class must
implement.
An interface is a collection of abstract methods and
final variables.
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Interfaces
Interface Fundamentals :
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
JJava Interfaces
Creating Interface
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
JJava Interfaces
Interface Example
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Interfaces
Interface Example
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
JJava Interfaces
Interface Example
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
JJava Interfaces
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Interfaces Example
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
JJava Interfaces
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Interfaces
interface Shape{ class Square implements Shape {
void getArea( ); double side;
} Square (double side) {
class Rectangle implements Shape{ [Link] = side;
double height, width; }
Rectangle (double height, double width) public void getArea() {
// must be public
{
[Link] ("Area of Square= " +
[Link] = height; (side*side));
[Link] = width; }
} }
public void getArea() { // must be class InterfaceDemo2 {
public public static void main(String [] a){
[Link] ("Area of Rectangle= Shape sh;
"+(height*width)); sh = new Rectangle(20.00, 40.00);
[Link]();
}
sh = new Square(15.5);
} [Link]();
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Technologies
Java Interfaces
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Polymorphism, Method Overloading &
Method Overriding
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Introduction to Polymorphism
➢ Polymorphism is the ability of an object to take on multiple forms.
➢ It allows a single interface to be used for different types.
➢ In Java, polymorphism is achieved through method overloading and
method overriding.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Introduction to Polymorphism
➢ The word polymorphism is a combination of two words
i.e. ploy and morphs.
➢ The word poly means many and morphs means different forms.
➢ In short, a mechanism by which we can perform a single action in
different ways.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Types of Polymorphism:
[Link]-time (Static) Polymorphism
2. Runtime (Dynamic) Polymorphism
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Compile-time (Static) Polymorphism
Method overloading and operator overloading (not
supported in Java) allow compile-time polymorphism.
Method Overloading:
Occurs when multiple methods in the same class share the
same name but have different parameters.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Compile Time Polymorphism
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overriding
Runtime (Dynamic) Polymorphism
Achieved using method overriding.
The method call is resolved at runtime.
Method Overriding:
Occurs when a subclass provides a specific implementation of a
method defined in its parent class.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overriding
Properties of Dynamic Polymorphism
➢ It decides which method is to execute at runtime.
➢ It can be achieved through dynamic binding.
➢ It happens between different classes.
➢ It is required where a subclass object is assigned to a super-
class object for dynamic polymorphism.
➢ Inheritance involved in dynamic polymorphism.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overriding
Properties of Dynamic Polymorphism
➢ It provides a specific implementation to a method that is
already present in the parent class.
➢ it is used to achieve run-time polymorphism.
➢ it is not possible to override the static method.
➢ Hence, we cannot override the main() method also because
it is a static method.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overriding
Method Overiding
Used in achieving dynamic method dispatch.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overiding
Method Overiding
In the Program , we have assigned the child class object to the
parent class reference. So, in order to determine which method
would be called, the type of the object would be decided by the
JVM at run-time. It is the type of object that determines which
version of the method would be called (not the type of
reference).
Used in achieving dynamic method dispatch.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overiding
[Link]
class Fruits {
public void color() {
// Main class
[Link]("Parent class method is
public class DynamicPolymorphismExample {
invoked.");
public static void main(String args[]) {
}
// Assigning a child class object to a parent
}
class reference
// Child class
Fruits fruits = new Mango();
class Mango extends Fruits {
@Override
// Invoking the method
public void color() {
[Link]();
[Link]("The child class method is
}
invoked.");
}
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overiding
➢ Method overriding is one of the ways in which Java supports
Runtime Polymorphism.
➢ Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile
time.
➢ When an overridden method is called through a superclass
reference, Java determines which version(superclass/subclasses)
of that method is to be executed based upon the type of the
object being referred to at the time the call occurs. Thus, this
determination is made at run time.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Static vs Dynamic binding
➢ Static binding is done during compile-time while dynamic
binding is done during run-time.
➢ private, final and static methods and variables uses static
binding and bonded by compiler while overridden methods are
bonded during runtime based upon type of runtime object.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism
Differences Between Method Overloading and Overriding
Complied By : [Link] Sharma - Department of
Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Advantages of Polymorphism
➢ Enhances code reusability.
➢ Improves scalability and flexibility.
➢ Reduces code complexity.
➢ Makes code maintenance easier.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
RECAP
➢ Polymorphism allows a single interface to be used with different types.
➢ Compile-time polymorphism is achieved through method overloading.
➢ Runtime polymorphism is achieved through method overriding.
➢ Helps in achieving loose coupling and code reusability.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
class Calculator {
// Method to add two integers
public int add(int a, int b) { public class Metoverload{
return a + b; public static void main(String[] args) {
} Calculator calc = new Calculator();
// Overloaded method to add three integers [Link]([Link](5, 10));
public int add(int a, int b, int c) {
return a + b + c; [Link]([Link](5, 10, 15));
}
[Link]([Link](5.5, 10.5));
// Overloaded method to add two doubles }
public double add(double a, double b) { }
return a + b;
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Dynamic Method Dispatch
Dynamic Method Dispatch (also called runtime
polymorphism) is a mechanism in Java where the
method that gets called is determined at runtime,
based on the actual object (not the reference type).
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Dynamic Method Dispatch
Dynamic Method Dispatch is the process through which a call to an
overridden method is resolved at runtime rather than compile-time.
It allows Java to support runtime polymorphism — a key feature of
object-oriented programming.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Dynamic Method Dispatch
class Cat extends Animal {
class Animal {
void sound() {
void sound() {
[Link]("Meow");
[Link]("Some generic animal
}
sound");
}
}
}
public class TestPolymorphism {
public static void main(String[] args) {
class Dog extends Animal {
Animal a; // reference of superclass
void sound() {
[Link]("Bark");
a = new Dog(); // object of subclass
}
[Link](); // prints: Bark
}
a = new Cat(); // object of another subclass
class Cat extends Animal {
[Link](); // prints: Meow
void sound() {
}
[Link]("Meow");
}
} Complied By : [Link] Sharma - Department of Computer Applications
}
Java Enterprise Application Development
Polymorphism & Method Overloading
Experential Learning
1. Create A superclass Payment with a method pay() and Subclasses
CreditCardPayment and UPIPayment override pay() to provide specific
implementations.
2. Using the concept of Method Overloading create a calculator with
basic operations.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Polymorphism & Method Overloading
Experential Learning
Problem Statement: Employee Payment System
Create an abstract class called Employee with the following:
•Fields: name (String), employeeId (int)
•Constructor to initialize these fields
•Abstract method: calculateSalary()
•Concrete method: displayDetails() that prints name and employeeId
Then, create two subclasses:
•FullTimeEmployee – has a monthlySalary field and overrides
•calculateSalary() to return it.
•PartTimeEmployee – has hoursWorked and hourlyRate, and overrides
•calculateSalary() to return hoursWorked * hourlyRate.
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science
Java Enterprise Application
Development
(UQ24CA751A)
Dr. Annu Sharma
Associate Professor
Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Complied By : Dr. Annu Sharma Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Converting Primitives to Objects and Vice Versa
➢ Java is object-oriented, but primitives (int, char, etc.)
are not objects.
➢ Wrapper classes convert primitives into objects.
➢ Used in:
➢ Collections (like ArrayList)
➢ Serialization
➢ Multithreading (when objects are required)
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Why Use Wrapper Classes?
•Need objects for Collections API
→ ArrayList<int> → ArrayList<Integer>
•Helpful for:
• Parsing strings to numbers ([Link]())
• Utility methods ([Link](), [Link]())
➢ If string does not contain a valid numeric value, then a NumberFormatException is
thrown.
➢ All of the type wrappers override toString( ), which returns the value contained within
the wrapper in proper format.
➢ toString( ) is called whenever wrapper object is concatenated with string.
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Boxing and UnBoxing
Autoboxing: Java automatically converts a primitive → object
•Example:
int a = 5;
Integer obj = a; // Autoboxing
➢ UnBoxing:
Java converts an object → primitive
•Example:
Integer obj = 10;
int a = obj; // Unboxing
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
import [Link];
public class WrapperDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](10); // Autoboxing
[Link](20);
int sum = 0;
for (Integer i : list) {
sum += i; // Unboxing
}
[Link]("Sum: " + sum);
}
}
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Common Methods in Wrapper Classes
[Link]("123");
[Link]("45.6");
[Link]('5’);
[Link]("true");
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Differences Between Primitives and Wrappers
Feature Primitive Wrapper Class
Memory usage Low Higher
Nullable No Yes
Use in Collections No Yes
Default values 0, false null
Complied By : [Link] Sharma - Department of Computer Applications
Java Enterprise Application Development
Wrapper Classes & Autoboxing in Java
Quiz Time!
[Link] is the wrapper class for char?
[Link] is the output of:
Integer x = 100;
int y = x;
[Link](y);
[Link] you store int directly in ArrayList?
Complied By : [Link] Sharma - Department of Computer Applications
THANK YOU
[Link] Sharma
Associate Professor
Department of Computer Science