Methods in Java
A method in Java is a block of code that performs a specific task, can be reused, and is
executed when called.
1.1 Syntax of a Method
returnType methodName(parameters) {
// method body
return value; // if required
1.2 Types of Methods
1. Predefined Methods (Library methods): Already defined in Java libraries.
Example: Math.sqrt(), System.out.println()
2. User-defined Methods: Defined by the programmer to perform specific tasks.
all by Value: Passes a copy of the variable’s value.
Call by Reference: Passes the reference (address) of the variable.
class MethodExample {
static int add(int a, int b) {
return a + b;
public static void main(String[] args) {
int sum = add(5, 10);
System.out.println("Sum: " + sum);
Output: Sum: 15
Arrays in Java
An array is a collection of elements of the same data type stored in contiguous memory
locations.
1 Declaration and Initialization
int[] arr = new int[5]; // Declaration + memory allocation
arr[0] = 10; // Initialization
// OR
int[] arr = {10, 20, 30, 40, 50}; // Declaration + initialization
2 Features of Arrays
Fixed size (once created, cannot change size).
Index starts from 0.
Random access via index.
3 Traversing Arrays
class TraverseArray {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
Output:
10
20
30
40
50
Array Operations
(a) Searching:
Linear Search
for (int i=0; i<arr.length; i++){
if(arr[i] == key){
System.out.println("Found at index: " + i);
Binary Search (Sorted Array):
int index = Arrays.binarySearch(arr, key);
(b) Sorting:
Bubble Sort:
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
Built-in Sort: Arrays.sort(arr);
Strings in Java
A string is a sequence of characters enclosed in double quotes.In Java, String is a class in
the java.lang package.
String Creation:
String s1 = "Hello"; // Using string literal
String s2 = new String("Java"); // Using new keyword
Common String Methods
String str = "Java Programming";
System.out.println(str.length()); // 16
System.out.println(str.toUpperCase()); // JAVA PROGRAMMING
System.out.println(str.toLowerCase()); // java programming
System.out.println(str.substring(5)); // Programming
System.out.println(str.charAt(2)); // v
System.out.println(str.indexOf('a')); // 1
System.out.println(str.replace("Java","C++")); // C++ Programming
String Comparison
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false (different reference)
System.out.println(s1.equals(s3)); // true (content comparison)