FJP Unit 3
FJP Unit 3
dataType arrayName[];
Instantiating an Array
Once declared, an array must be instantiated (i.e., memory allocated for it):
Example:
numbers = new int[5];
Declaring and Instantiating in One Step:
You can also declare and instantiate an array in one line:
int[] numbers = new int[5];
Initializing an Array
After declaring and instantiating, you can initialize the array:
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
1
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
P1: Write a java program to accept n integer from user into an array and display
them one in each line.
import java.util.Scanner;
public class DisplayArray {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Ask the user for the number of elements (n)
System.out.print("Enter the number of integers you want to store: ");
int n = scanner.nextInt();
// Declare an array to store n integers
int[] numbers = new int[n];
// Accept n integers from the user
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
// Display the integers, one per line
System.out.println("You entered:");
for (int i = 0; i < n; i++) {
System.out.println(numbers[i]);
}
// Close the scanner
scanner.close();
}
}
2
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Output
Multi-Dimensional Array
Examples:
Two dimensional array:
int[][] twoD_arr = new int[10][20];
3
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
4
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
{1, 2, 3},
{8, 6, 4},
{4, 5, 6}
};
// Calculate the number of rows and columns present in the given matrix
rows = a.length;
cols = a[0].length;
// Perform the required operation to convert the given matrix into a lower triangular matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Print element if it's in the lower triangle or on the diagonal, else print 0
if (i >= j) {
System.out.print(a[i][j] + " ");
} else {
System.out.print("0 ");
}
}
System.out.println(); // Move to the next line after each row
}
}
}
}
5
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Java String
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
2) by new keyword
String s=new String("Welcome");//creates two objects and one reference variable
6
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
1 char charAt(int index) It returns char value for the particular index
String substring(int beginIndex, int It returns substring for given begin index and end
6
endIndex) index.
7
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
static String
15 It compares another string. It doesn't check case.
equalsIgnoreCase(String another)
int indexOf(String substring, int It returns the specified substring index starting
22
fromIndex) with given index.
8
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Example Code:
public class StringExample {
public static void main(String[] args) {
String greeting = "Hello, World!";
// Get length of the string
int length = greeting.length();
System.out.println("Length: " + length);
// Convert to uppercase
String upper = greeting.toUpperCase();
System.out.println("Uppercase: " + upper);
9
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Output:
Length: 13
First character: H
Uppercase: HELLO, WORLD!
Substring: World!
Replaced: Hello, Java!
10
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Output:
Joined using concat(): Hello, World!
Joined using + operator: Hello, World!
Recursive methods
A recursive method in Java is a method that calls itself in order to solve a problem. Recursion
works by breaking a larger problem into smaller sub-problems of the same type, and it continues
to call itself with smaller inputs until it reaches a base case (a condition where the recursion
stops).
Key Components of Recursion:
Base Case: The condition under which the recursive calls stop.
Recursive Case: The part of the function where it calls itself to solve a smaller part of the
problem.
Example: Factorial Calculation Using Recursion
The factorial of a number n is the product of all positive integers less than or equal to n. It can be
defined recursively as:
factorial(n) = n * factorial(n - 1) for n > 1
factorial(1) = 1 (Base Case)
Here’s how you can implement a recursive method to calculate the factorial of a number in Java:
public class RecursiveFactorial {
// Recursive method to calculate factorial
public static int factorial(int n) {
// Base case: if n is 1, return 1
if (n == 1) {
return 1;
}
// Recursive case: n * factorial of (n-1)
else {
return n * factorial(n - 1);
}
}
11
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Output:
Factorial of 5 is: 120
Wrapper class
In Java, wrapper classes are used to convert primitive data types into objects. Each primitive
data type (e.g., int, char, boolean, etc.) has a corresponding wrapper class provided by the Java
API. Wrapper classes are useful when you need an object instead of a primitive data type,
especially when working with data structures like collections that require objects (e.g., ArrayList,
HashMap).
List of Primitive Types and Their Corresponding Wrapper Classes:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
12
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
13
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
}
}
Output:
5
10
14
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
}
}
Output:
Integer Object: 100
Double Object: 3.14
Primitive int: 100
Primitive double: 3.14
Autoboxed Integer: 200
Unboxed Integer: 200
15
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
1. Type Safety: Enums ensure that a variable can only take one of the predefined constants,
preventing invalid values.
2. Predefined Constants: Enum constants are implicitly public, static, and final. They represent
fixed values and can be compared using ==.
3. Enums Can Have Methods: Unlike simple constants, enums can have fields, methods, and
constructors.
4. Used in Switch Statements: Enums can be used in switch statements to simplify code when
dealing with constant values.
16
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
case SUNDAY:
System.out.println("It's the weekend!");
break;
default:
System.out.println("Midweek day.");
break;
}
Explanation:
The enum Day defines constants for the days of the week.
In the switch statement, different actions are performed based on the day. Enums can be used in
switch statements for easier comparison.
The method Day.values() returns an array of all enum constants, which can be looped through.
Advantages of Enums:
Type safety: Enums provide compile-time type safety, reducing bugs caused by invalid values.
17
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Readability: Enums improve code readability by giving meaningful names to fixed sets of
values.
Easy comparison: Enums can be compared using == since they are constants.
Enum Limitations:
Enums are not extensible. You cannot add new constants to an enum at runtime.
All enum constants are public, static, and final, which means they cannot be changed after they are
created.
18
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Inheritance in java
Inheritance in Java is one of the core principles of Object-Oriented Programming (OOP). It
allows a new class to inherit the properties and behavior (fields and methods) of an existing
class, promoting code reusability and logical hierarchy.
Key Concepts:
Super Class (Parent Class): The class whose properties are inherited by another class. It is also called
the base class.
Sub Class (Child Class): The class that inherits the properties and methods of the superclass. It is also
called the derived class.
Extends keyword: Used to establish an inheritance relationship between two classes.
19
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Syntax:
class SuperClass {
// Fields and methods of the superclass
}
// Subclass-specific method
public void bark() {
System.out.println(name + " is barking.");
}
20
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
21
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
2. Multilevel Inheritance:
In multilevel inheritance, a class is derived from another derived class.
class A { }
class B extends A { }
class C extends B { } // Multilevel inheritance
3. Hierarchical Inheritance:
In hierarchical inheritance, multiple subclasses inherit from a single superclass.
class A { }
class B extends A { }
class C extends A { } // Hierarchical inheritance
Overriding Methods:
A subclass can override a method from its superclass to provide its own implementation. The
overridden method in the subclass must have the same signature (method name and parameters)
as the method in the superclass.
Example:
class Animal {
public void sound() {
System.out.println("Animal makes a sound.");
}
}
22
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
super Keyword:
The super keyword is used to refer to the immediate superclass object. It can be used to call
superclass methods or constructors.
super.methodName(): Calls a method from the superclass.
super(): Calls the constructor of the superclass.
23
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
Constructor in Inheritance:
When a subclass object is created, the constructor of the superclass is invoked first, followed by
the constructor of the subclass.
If the superclass has a no-argument constructor, it is called automatically. If it has a
parameterized constructor, you must explicitly call it using super().
Example of Constructor Inheritance:
class Animal {
// Parameterized constructor
public Animal(String name) {
System.out.println(name + " is an animal.");
}
}
24
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
25
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
// Subclass 1
class Dog extends Animal {
// Overriding the sound method
@Override
public void sound() {
System.out.println("Dog barks");
}
}
// Subclass 2
class Cat extends Animal {
// Overriding the sound method
@Override
public void sound() {
System.out.println("Cat meows");
}
}
26
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
}
}
Output:
Dog barks
Cat meows
Polymorphism
Polymorphism in Java is a key concept of object-oriented programming (OOP) that allows
objects of different classes to be treated as objects of a common super class. It refers to the
ability of a single interface or method to represent different underlying forms (data types or
objects). Polymorphism helps in making programs more flexible and reusable.
There are two types of polymorphism in Java:
1. Compile-time Polymorphism (Method Overloading)
Method Overloading is when multiple methods have the same name but differ in the
number or type of parameters. The correct method is determined at compile-time based
on the method signature.
Example
class MathOperation {
int add(int a, int b) {
return a + b;
}
27
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
28
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)
}
}
29
Prepared By: Prof. Shivam Agrawal