Arrays in Java
Definition
• An array in Java is a collection of elements of the same data type, stored in contiguous
memory locations.
• It is used to store multiple values in a single variable instead of declaring separate
variables for each value.
• Arrays are objects in Java and are created dynamically.
Features of Arrays
1. Stores multiple values of the same data type.
2. Has a fixed size (cannot be changed once declared).
3. Provides random access using index (0-based).
4. Elements are stored in continuous memory locations.
Types of Arrays
1. One-Dimensional Array (1D) – Linear collection of elements.
2. Two-Dimensional Array (2D) – Collection of rows and columns (matrix).
3. Multi-Dimensional Array – Array of arrays.
[Link] Dimensional Array
A single dimensional array in Java is a linear collection of elements of the same data
type, stored in contiguous memory locations and accessed using a single index starting from 0.
Basics Operation on Arrays in Java
1. Declaring an Array
The general form of array declaration is // Method 1:
The element type determines the data type of each element that int arr[];
comprises the array. Like an array of integers, we can also create an // Method 2:
array of other primitive data types like char, float, double, etc. or user- int[] arr;
defined data types (objects of a class).
2. Initialization an Array in Java
When an array is declared, only a reference of an array is int arr[] = new int[size];
created. We use new to allocate an array of given size.
• Array Declaration is generally static, but if the size in not defined, the Array is
Dynamically sized.
• Memory for arrays is always dynamically allocated (on heap segment) in Java.
• The elements in the array allocated by new will automatically be initialized to zero (for
numeric types), false (for boolean) or null (for reference types).
// Declaring array literal
int[] arr = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
3. Change an Array Element
To change an element, assign a new value to a specific index. The index begins with 0 and
ends at (total array size)-1.
// Changing the first element to 90
arr[0] = 90;
4. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int n = [Link];
5. Accessing and Updating All Array Elements
• All the elements of array can be accessed using Java for Loop.
• Each element in the array is accessed via its index.
Example Program
class numbers
{
public static void main(String[] args)
{
int[] arr; // declares an Array of integers.
arr = new int[5]; // allocating memory for 5 integers.
arr[5] = {10,20,30,40,50}; // initialize the eements of the array
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + " : " + arr[i]);
}
}
Two Dimensional Array
A two-dimensional (2D) array in Java is an array of arrays, where data is stored in the form of
rows and columns (like a matrix).
It uses two indices – one for the row and one for the column.
Syntax (Declare, Initialize and Assigning)
// Declaring and Intializing
data_type[][] array_name = new data_type[x][y];
// Assigning Value
array_name[row_index][column_index] = value;
Example Program
import [Link].*;
class Main {
public static void main(String[] args){
// Array Intialised and Assigned
int[][] arr = { { 1, 2 }, { 3, 4 } };
// Printing the Array
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++)
[Link](arr[i][j]+" ");
[Link]();
}
}
}
Multidimensional arrays are used to store the data in rows and columns,
where each row can represent another individual array are multidimensional
array.
String in Java
Definition
• A String in Java is a sequence of characters.
• It is a class in [Link] package and is used to store and manipulate text.
• Unlike C, strings in Java are objects, not character arrays.
Syntax
String str = "Hello";
String str2 = new String("World");
Example
class StringExample {
public static void main(String args[]) {
String name = "Java";
[Link]("Length: " + [Link]());
[Link]("Uppercase: " + [Link]());
[Link]("Character at index 2: " + [Link](2));
}
}
Explanation
• length() returns the number of characters.
• toUpperCase() converts string to uppercase.
• charAt(2) gives the character at index 2.
Vector in Java
Definition
• A Vector is a dynamic array in Java that can grow or shrink in size.
• It is a class in [Link] package.
• Unlike normal arrays, Vectors can store objects of any type and automatically resize.
Syntax
Vector<Type> v = new Vector<Type>();
Example
import [Link].*;
class VectorExample
{
public static void main(String args[])
{
Vector<Integer> v = new Vector<Integer>();
[Link](10);
[Link](20);
[Link](30);
[Link]("Vector elements: " + v);
[Link]("First element: " + [Link]());
[Link]("Size of vector: " + [Link]());
}
}
Explanation
• add() inserts elements into vector.
• firstElement() returns the first element.
• size() gives current size of the vector.
Enumerated Data Type (enum) in Java
Definition
• An enum (enumeration) in Java is a special data type used to define a set of named
constants.
• It improves readability and type safety compared to using integer constants.
Syntax
enum EnumName { CONSTANT1, CONSTANT2, CONSTANT3 }
Example
class EnumExample
{
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }
public static void main(String args[])
{
Day d = [Link];
[Link]("Today is: " + d);
}
}
Explanation
• enum Day defines constants for weekdays.
• Variable d is assigned one of the constants ([Link]).
• Enums make code clearer and safer.
Inheritance
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism
in Java by which one class is allowed to inherit the features(fields and methods) of another class. In
Java, Inheritance means creating new classes based on existing ones. A class that inherits from another
class can reuse the methods and fields of that class.
• The class that inherits is called subclass (child class).
• The class from which it inherits is called superclass (parent class).
• It promotes code reusability and establishes a relationship between classes.
Types of Inheritance in Java
Java supports the following types of inheritance:
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance (through interfaces, since Java does not support multiple inheritance with
classes)
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple inheritance.
Syntax
class Parent {
// parent class members
}
class Child extends Parent {
// child class members
}
Example Program
class Parent {
void display() {
[Link]("This is the Parent class");
}
}
class Child extends Parent {
void show() {
[Link]("This is the Child class");
}
}
class SingleInheritanceExample {
public static void main(String args[]) {
Child c = new Child();
[Link](); // inherited from Parent
[Link](); // own method
}
}
Explanation
• The Child class uses extends keyword to inherit from Parent.
• The object of Child can access both parent and child methods.
[Link] Inheritance
Definition
In Multilevel Inheritance, a class is derived from another class, which is also derived from another class,
forming a chain of inheritance.
Syntax
class GrandParent
{}
class Parent extends GrandParent
{}
class Child extends Parent
{}
Example Program
class GrandParent {
void methodA() {
[Link]("This is GrandParent");
}
}
class Parent extends GrandParent {
void methodB() {
[Link]("This is Parent");
}
}
class Child extends Parent {
void methodC() {
[Link]("This is Child");
}
}
class MultilevelInheritanceExample {
public static void main(String args[]) {
Child c = new Child();
[Link](); // from GrandParent
[Link](); // from Parent
[Link](); // from Child
}
}
Explanation
• In this type, inheritance is in a step-by-step chain.
• The Child inherits from Parent, and Parent inherits from GrandParent.
[Link] Inheritance
Definition
In Hierarchical Inheritance, multiple classes inherit from the same parent class.
Syntax
class Parent
{}
class Child1 extends Parent
{}
class Child2 extends Parent
{}
Example Program
class Parent {
void methodA() {
[Link]("This is Parent class");
}
}
class Child1 extends Parent {
void methodB() {
[Link]("This is Child1 class");
}
}
class Child2 extends Parent {
void methodC() {
[Link]("This is Child2 class");
}
}
class HierarchicalInheritanceExample {
public static void main(String args[]) {
Child1 c1 = new Child1();
[Link]();
[Link]();
Child2 c2 = new Child2();
[Link]();
[Link]();
}
}
Explanation
• Both Child1 and Child2 share the properties of Parent.
• Useful when multiple classes need common features from a single parent.
4. Hybrid Inheritance
Definition
Hybrid Inheritance is a combination of two or more types of inheritance.
• Java does not support multiple inheritance with classes to avoid ambiguity (diamond
problem).
• But it supports hybrid inheritance using interfaces.
Syntax
interface A { }
class B implements A { }
class C extends B { }
Example Program
interface A {
void methodA();
}
class B {
void methodB() {
[Link]("This is class B");
}
}
class C extends B implements A {
public void methodA() {
[Link]("This is interface A");
}
}
class HybridInheritanceExample {
public static void main(String args[]) {
C obj = new C();
[Link](); // from interface
[Link](); // from class
}
}
Explanation
• C inherits from B (class) and implements A (interface).
• This demonstrates hybrid inheritance (mix of interface and class).
5. Multiple Inheritance Using Interfaces
Definition
• Multiple Inheritance is a type of inheritance where a class can inherit from two or more parent
classes.
• Java does not support multiple inheritance with classes directly, to avoid the diamond
problem (ambiguity when two parent classes have the same method).
• But Java achieves multiple inheritance using interfaces.
Syntax
interface Interface1 {
void method1();
}
interface Interface2 {
void method2();
}
class Child implements Interface1, Interface2 {
public void method1() { ... }
public void method2() { ... }
}
Example Program
interface Printable {
void print();
}
interface Showable {
void show();
}
class Demo implements Printable, Showable {
public void print() {
[Link]("Hello from Printable");
}
public void show() {
[Link]("Hello from Showable");
}
}
class MultipleInheritanceExample {
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
[Link]();
}
}
Explanation
1. Printable and Showable are two interfaces.
2. Demo class implements both interfaces.
3. The class must override all abstract methods of both interfaces.
4. This way, Java supports multiple inheritance safely without ambiguity.
Interface
Definition
• An interface in Java is a collection of abstract methods (methods without body) and
constants (final variables).
• It specifies a contract (what a class must do) but not how it is done.
• A class uses the implements keyword to provide the implementation of an interface.
• From Java 8 onwards, interfaces can also have default methods and static methods.
• An Interface in Java programming language is defined as an abstract type used to specify
the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java
interface contains static constants and abstract methods.
Syntax
interface InterfaceName {
// abstract method
void method1();
// constant
int VALUE = 100;
}
class ClassName implements InterfaceName {
public void method1() {
// implementation code
}
}
Explanation of Syntax
1. interface InterfaceName → defines an interface.
2. Inside interface:
o Methods are public and abstract by default.
o Variables are public, static, and final by default.
3. class ClassName implements InterfaceName → a class must provide body for all
abstract methods of the interface.
4. This achieves abstraction and multiple inheritance in Java.
Example Program:
import [Link].*;
// Interface Declared
interface testInterface {
// public, static and final
final int a = 10;
// public and abstract
void display();
}
// Class implementing interface
class TestClass implements testInterface {
// Implementing the capabilities of Interface
public void display(){
[Link]("Hari");
}
}
class Geeks
{
public static void main(String[] args)
{
TestClass t = new TestClass();
[Link]();
[Link](t.a);
}
}
Output:
Hari
10
Relationship Between Class and Interface
A class can extend another class and similarly, an interface can extend another interface.
However, only a class can implement an interface and the reverse (an interface implementing
a class) is not allowed.
Package in Java
Definition
• A package in Java is a collection of classes, interfaces, and sub-packages that are
grouped together.
• It helps in organizing classes and avoiding name conflicts.
• Think of a package as a folder in your computer where similar files are stored together.
• Packages are of two types:
1. Built-in Packages → Predefined by Java (e.g., [Link], [Link]).
2. User-defined Packages → Created by programmers.
Flow Diagram
[ Java API ]
/ | \
/ | \
[Link] [Link] [Link]
| | |
Collections File Database
👉 This shows how Java has built-in packages, each containing related classes.
Syntax
Defining a package
package packageName;
public class ClassName {
// code
}
Using a package
import [Link];
// OR
import packageName.*;
Explanation of Syntax
1. package packageName; → Defines a package.
2. import statement → Used to access classes from another package.
3. Packages provide modularity and prevent naming conflicts when multiple classes have
the same name.
Example Program
Step 1: Create a Package
// File: MyPackage/[Link]
package MyPackage;
public class MyClass {
public void display() {
[Link]("Hello from MyPackage!");
}
}
Step 2: Use the Package
// File: [Link]
import [Link];
class TestPackage {
public static void main(String args[]) {
MyClass obj = new MyClass();
[Link]();
}
}
Output
Hello from MyPackage!
Uses of Packages
1. Organizing Classes → Makes large projects manageable.
2. Reusability → Classes inside packages can be reused across different projects.
3. Name Conflict Avoidance → Two classes with the same name can exist in different
packages.
4. Encapsulation → Packages can have access modifiers (public, protected, default) to
control visibility.
5. Modularity → Helps divide the project into smaller modules.