Java Programming
Arrays, Class & Objects, Methods, Overloading and Overriding
1. Arrays
6.1 One-Dimensional Arrays
Concept:
A one-dimensional array is a collection of elements of the same data type stored in a single row of contiguous
memory locations, accessed using an index starting from 0.
Syntax:
dataType[] arrayName = new dataType[size];
dataType[] arrayName = {value1, value2, ...};
Example:
public class ArrayDemo {
public static void main(String[] args) {
int[] marks = {80, 90, 70};
[Link](marks[0]);
[Link](marks[1]);
}
}
Output:
80
90
Explanation:
'marks' is an array storing three values. marks[0] accesses the first element (80) and marks[1] accesses the
second (90), since indexing starts at 0.
6.2 Two-Dimensional Arrays
Concept:
A two-dimensional array stores data in a table-like structure of rows and columns, useful for representing grids
or matrices.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
Example:
public class TwoDArrayDemo {
public static void main(String[] args) {
int[][] matrix = {{1, 2}, {3, 4}};
[Link](matrix[0][1]);
[Link](matrix[1][0]);
}
}
Output:
2
3
Explanation:
matrix[0][1] accesses the element in row 0, column 1 (value 2), and matrix[1][0] accesses row 1, column 0 (value
3).
6.3 Array Initialization
Concept:
Arrays can be initialized either at the time of declaration with fixed values, or later by assigning values to
individual index positions.
Syntax:
int[] arr = new int[3];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
Example:
public class ArrayInitDemo {
public static void main(String[] args) {
int[] arr = new int[3];
arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
[Link](arr[2]);
}
}
Output:
15
Explanation:
The array is first created with a size of 3, and then each index is assigned a value individually. arr[2] holds 15.
6.4 Passing Arrays to Methods
Concept:
An array can be passed as an argument to a method, allowing the method to access or modify its elements
directly.
Syntax:
static returnType methodName(dataType[] arr) {
// use arr
}
Example:
public class ArrayMethodDemo {
static void printArray(int[] arr) {
for (int val : arr) {
[Link](val);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
printArray(numbers);
}
}
Output:
1
2
3
Explanation:
The array 'numbers' is passed to the printArray() method, which loops through and prints each element.
6.5 Array Programs (Sum, Average, Largest, Smallest, Search)
Concept:
Arrays are commonly used to perform operations like calculating the sum, average, finding the largest/smallest
value, or searching for an element by looping through all the elements.
Syntax:
for (int i = 0; i < [Link]; i++) {
// process arr[i]
}
Example:
public class ArrayOperationsDemo {
public static void main(String[] args) {
int[] arr = {12, 45, 3, 67, 21};
int sum = 0, max = arr[0], min = arr[0];
for (int i = 0; i < [Link]; i++) {
sum += arr[i];
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
[Link]("Sum: " + sum);
[Link]("Average: " + (sum / [Link]));
[Link]("Largest: " + max);
[Link]("Smallest: " + min);
}
}
Output:
Sum: 148
Average: 29
Largest: 67
Smallest: 3
Explanation:
The loop goes through every element once: adding each value to 'sum', and updating 'max'/'min' whenever a
larger or smaller value is found. Average is sum divided by the number of elements.
2. Class and Objects
8.1 Class
Concept:
A class is a blueprint or template that defines the properties (fields) and behaviors (methods) that its objects will
have. It does not occupy memory on its own until an object is created.
Syntax:
class ClassName {
// fields
// methods
}
Example:
class Student {
String name;
int age;
}
public class ClassDemo {
public static void main(String[] args) {
[Link]("Student class defined");
}
}
Output:
Student class defined
Explanation:
'Student' is a class with two fields (name and age). No object has been created yet, so these fields don't hold any
real values.
8.2 Object
Concept:
An object is an instance of a class, created using the 'new' keyword. It has its own copy of the fields defined by
the class and can use the class's methods.
Syntax:
ClassName objectName = new ClassName();
Example:
class Student {
String name = "Anu";
}
public class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student();
[Link]([Link]);
}
}
Output:
Anu
Explanation:
's1' is an object of the Student class, created using 'new'. It can access the field 'name' defined in the class using
the dot (.) operator.
8.3 Creating Objects
Concept:
Objects are created by using the 'new' keyword followed by a call to the class's constructor, which allocates
memory and initializes the object.
Syntax:
ClassName objectName = new ClassName(arguments);
Example:
class Book {
String title = "Java Basics";
}
public class CreateObjectDemo {
public static void main(String[] args) {
Book b1 = new Book();
[Link]([Link]);
}
}
Output:
Java Basics
Explanation:
'new Book()' creates a new object 'b1' in memory, and '[Link]' accesses its field to print the book's title.
3. Methods
7.1 Defining Methods
Concept:
A method is a named block of code that performs a specific task and can be executed (called) whenever needed,
helping to organize and reuse code.
Syntax:
returnType methodName(parameters) {
// method body
}
Example:
public class MethodDefDemo {
static void greet() {
[Link]("Hello from a method!");
}
public static void main(String[] args) {
greet();
}
}
Output:
Hello from a method!
Explanation:
'greet' is a method with no return value (void) and no parameters. It is defined once and then called from
main().
7.2 Method Calling
Concept:
Calling a method means executing the code inside it by writing its name followed by parentheses, optionally
passing values it needs.
Syntax:
methodName(arguments);
Example:
public class MethodCallDemo {
static void showMessage() {
[Link]("Method called successfully");
}
public static void main(String[] args) {
showMessage();
}
}
Output:
Method called successfully
Explanation:
Writing 'showMessage();' inside main() transfers control to the method, executes its code, and then returns back
to main().
7.3 Parameters and Arguments
Concept:
Parameters are variables listed in a method's definition to receive input values, while arguments are the actual
values passed to the method when it is called.
Syntax:
static void methodName(dataType parameter) {
// use parameter
}
methodName(argument);
Example:
public class ParameterDemo {
static void greet(String name) {
[Link]("Hello, " + name);
}
public static void main(String[] args) {
greet("Priya");
}
}
Output:
Hello, Priya
Explanation:
'name' is the parameter defined in the method, and "Priya" is the argument passed when the method is called.
7.4 Return Type
Concept:
The return type of a method specifies the data type of the value it sends back to the caller using the 'return'
keyword. If a method returns nothing, its return type is 'void'.
Syntax:
returnType methodName(parameters) {
return value;
}
Example:
public class ReturnDemo {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
int result = square(5);
[Link]("Square: " + result);
}
}
Output:
Square: 25
Explanation:
The method 'square' takes a number, calculates its square, and returns the result (int), which is then stored in
'result' and printed.
7.6 Scope of Variables
Concept:
The scope of a variable defines the region of the program where it can be accessed. Local variables (declared
inside a method) are only accessible within that method, while instance/class variables have wider scope.
Syntax:
void method() {
int localVar = 10; // accessible only inside this method
}
Example:
public class ScopeDemo {
static void display() {
int localVar = 25;
[Link]("Local variable: " + localVar);
}
public static void main(String[] args) {
display();
}
}
Output:
Local variable: 25
Explanation:
'localVar' is declared inside the display() method, so it only exists and is only accessible while that method is
executing.
7.7 Recursion (Basic)
Concept:
Recursion is a technique where a method calls itself to solve a smaller instance of the same problem, continuing
until it reaches a base case that stops the recursive calls.
Syntax:
returnType methodName(parameters) {
if (baseCondition) {
return baseValue;
}
return methodName(smallerInput);
}
Example:
public class RecursionDemo {
static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
[Link]("Factorial of 4: " + factorial(4));
}
}
Output:
Factorial of 4: 24
Explanation:
factorial(4) calls factorial(3), which calls factorial(2), and so on until factorial(0) returns 1 (the base case). The
results are then multiplied together: 4×3×2×1 = 24.
4. Method Overloading
7.5 Method Overloading
Concept:
Method overloading allows multiple methods in the same class to have the same name but different parameter
lists (different number or types of parameters).
Syntax:
returnType methodName(int a) { ... }
returnType methodName(int a, int b) { ... }
Example:
public class OverloadDemo {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
[Link](add(2, 3));
[Link](add(2.5, 3.5));
}
}
Output:
5
6.0
Explanation:
Java chooses the correct 'add' method to run based on the argument types: integers call the int version, and
decimals call the double version.
5. Method Overriding
9.2 Method Overriding
Concept:
Method overriding occurs when a subclass provides its own implementation of a method that is already defined
in its superclass, replacing the parent's version when called on the subclass object.
Syntax:
class Parent {
void display() { ... }
}
class Child extends Parent {
@Override
void display() { ... }
}
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
public class OverrideDemo {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output:
Dog barks
Explanation:
'Dog' redefines the sound() method with its own behavior. When called on a Dog object, the overridden (child)
version runs instead of the parent's version.