CoCubes MTech Level – Coding (Java) Exam Ready Notes
Topics Covered
1. Loops & Conditions
2. Arrays & Strings
3. Functions & Recursion
4. Sorting & Searching
5. Data Structures Basics
1️⃣Loops & Conditions
Example 1: Print first 5 natural numbers
for(int i=1; i<=5; i++){
[Link](i + " ");
}
// Output: 1 2 3 4 5
Example 2: Check if number is even or odd
int n = 9;
if(n % 2 == 0){
[Link]("Even");
}else{
[Link]("Odd");
}
// Output: Odd
2️⃣Arrays & Strings
Example 1: Reverse an array
int[] arr = {1,2,3,4};
for(int i=[Link]-1; i>=0; i--){
[Link](arr[i] + " ");
}
// Output: 4 3 2 1
Example 2: Check palindrome string
String s = "level";
String rev = new StringBuilder(s).reverse().toString();
if([Link](rev)) [Link]("Palindrome");
else [Link]("Not Palindrome");
// Output: Palindrome
3️⃣Functions & Recursion
Example 1: Factorial using recursion
int factorial(int n){
if(n==0) return 1;
return n * factorial(n-1);
}
[Link](factorial(5)); // Output: 120
Example 2: Sum of array elements using function
int sum(int[] arr){
int s=0;
for(int n:arr) s+=n;
return s;
}
[Link](sum(new int[]{1,2,3})); // Output: 6
4️⃣Sorting & Searching
Example 1: Bubble Sort
int[] arr={5,2,8,1};
for(int i=0;i<[Link]-1;i++){
for(int j=0;j<[Link]-i-1;j++){
if(arr[j]>arr[j+1]){
int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp;
}
}
}
// Sorted array: 1 2 5 8
Example 2: Linear Search
int[] arr={1,3,5,7};
int key=5;
for(int i=0;i<[Link];i++){
if(arr[i]==key){
[Link]("Found at index: "+i);
}
}
// Output: Found at index: 2
5️⃣Data Structures Basics
Example 1: Stack using Java
Stack<Integer> st = new Stack<>();
[Link](10);
[Link](20);
[Link]([Link]()); // Output: 20
Example 2: Queue using LinkedList
Queue<Integer> q = new LinkedList<>();
[Link](10);
[Link](20);
[Link]([Link]()); // Output: 10
End of Coding (Java) Section