0% found this document useful (0 votes)
8 views62 pages

Java Programming Basics and Examples

Uploaded by

ddddddgdvdg
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views62 pages

Java Programming Basics and Examples

Uploaded by

ddddddgdvdg
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Vikas Learning center.

HSR Layout Sector 7 Bangalore 560102


Ph +91 86181 54620

Table of Contents
Programming - Basics .............................................................................................................................. 3
Program for methods – Example calculator ......................................................................................... 3
Program for methods – Example Factorial ........................................................................................... 3
Program for impure methods – Example Array manipulation ............................................................... 5
Program for impure methods – Example 2D Array – Matrix addition ................................................... 6
Program for printing patterns in Java ................................................................................................... 8
Programming – Sorting and searching ..................................................................................................... 9
Program for Linear search.................................................................................................................... 9
Program for Binary search ................................................................................................................. 10
Program for Bubble sort .................................................................................................................... 14
Program for Selection sort ................................................................................................................. 18
Programming – Classes and objects ....................................................................................................... 21
Program for Classes and objects demonstration - Constructors ......................................................... 21
Program for Classes and objects Copy Constructors ........................................................................... 22
Program for Classes and objects Constructors ................................................................................... 23
Program for Classes and objects Constructors – This keyword in java ................................................ 24
Program for Classes and objects Static methods ................................................................................ 26
Autoboxing ............................................................................................................................................ 26
Unit IV Mathematical Library methods – import [Link].* .................................................................... 28
Chapter 4 String handling – import [Link].* ........................................................................................ 29
Chapter 5 User defined methods ........................................................................................................... 33
Example of user defined method ....................................................................................................... 33
Chapter 6 Classes and objects................................................................................................................ 34
Chapter 7 Constructors.......................................................................................................................... 36
Chapter 8 Encapsulation and inheritance ............................................................................................... 38
Computer application Section A Sample question paper ........................................................................ 40
Answer Keys Computer application Section A Test your knowledge ....................................................... 41
Computer application Section A test your knowledge 2 ......................................................................... 43
Computer application Section A test your knowledge 2A – Class 9......................................................... 45
Program to count the number of -ve numbers in an integer array and in a double array using methods
.......................................................................................................................................................... 56

1
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

List of Tables
Table 1 Unit IV Mathematical methods in java ....................................................................................... 28
Table 2 Chapter 4 String functions methods in java ................................................................................ 29
Table 3 Chapter 4 String buffer functions methods in java ...................................................................... 31
Table 4 Chapter 5 User defined methods - Simple .................................................................................. 33
Table 5 User defined method over loading ............................................................................................. 33
Table 6 Chapter 5 User defined method Impure function – Arrays – Call by reference ............................ 33
Table 7 Chapter 6 Example of a class with public private and protected ................................................. 34
Table 8 Chapter 7 Example of default constructor / Non parameterized ................................................. 36
Table 9 Chapter 7 Example of parameterized constructor ...................................................................... 36
Table 10 Chapter 7 Example of Copy constructor .................................................................................. 37
Table 11 Chapter 8 Encapsulation .......................................................................................................... 38
Table 12 Chapter 8 Inheritance – Leave this if its tough ......................................................................... 39

2
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Programming- Basics
Program for methods – Example calculator
Date 18-Nov-2023 Calculator using methods
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import [Link].*;
class Calculator {
//Method to add two integers which returns an integer
public static int add(int x, int y )
{
return(x+y);
}
//Method to sub two integers which returns an integer
public static int sub(int x, int y )
{
return(x-y);
}
//Method to Multiply two integers which returns an integer
public static int mul(int x, int y )
{
return(x*y);
}
//Method to Divide two integers which returns an integer
public static int div(int x, int y )
{
return(x/y);
}

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
int a, b;
int result ;
[Link]("Enter a ");
a = [Link]();
[Link]("Enter b ");
b = [Link]();
result = add(a,b);

[Link]("A = " +a + "B = " + b + " Result = a+b= " + result);


result = sub(a,b);
[Link]("A = " +a + "B = " + b + " Result = a - b = " + result);
result = mul(a,b);
[Link]("A = " +a + "B = " + b + " Result = a * b = " + result);
result = div(a,b);
[Link]("A = " +a + "B = " + b + " Result = a / b = " + result);
[Link]("Hello, World!");
}
}

Program for methods – Example Factorial

3
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

import [Link].*;
class Factorial {

public static int fact_forloop(int x)


{
int result = 1;
for(int i = 1; i <= x ;i++)
{
result *= i;
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number ;
int result ;
[Link]("Enter a number to find its factorial ");
number = [Link]();
result = fact_forloop(number);
[Link]("Factorial of " + number + " is = " + result);
}
}

4
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Program for impure methods – Example Array manipulation


19-11-2023 : Impure Methods : Creating an instance of a class and using the methods in that class.
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
class Array_Class{
public static void ModifyArray(int x[])
{
for(int i = 0 ; i < [Link]; i++)
{
x[i] = i +10 ;
}
}
public static void print_array(int x[])
{
for(int i = 0 ; i < [Link]; i++)
{
[Link]("a[" + i + "] = " + x[i]);
}
}
public static void main(String[] args) {
int a[] = new int[10];
[Link]("========= Array Initialized from the main program ========");
for(int i = 0 ; i < [Link]; i++)
{
a[i] = i;
[Link]("a[" + i + "] = " + a[i]);
}
[Link]("========= Array Modified by the main program ========\n");
ModifyArray(a);
[Link]("========= Print ModifiedArray ========");
print_array(a);
[Link]("Hello, World!");
}
}
// Online Java Compiler
// Use this editor to write, compile and run your Java code online

class Array_Class {
public void ModifyArray(int x[])
{
for(int i = 0 ; i < [Link]; i++)
{
x[i] = i +10 ;
}
}
public void print_array(int x[])
{
for(int i = 0 ; i < [Link]; i++)
{
[Link]("a[" + i + "] = " + x[i]);
}

}
public static void main(String[] args) {
Array_Class ar = new Array_Class();

5
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

int a[] = new int[10];


[Link]("========= Array Initialized from the main program ========");
for(int i = 0 ; i < [Link]; i++)
{
a[i] = i;
[Link]("a[" + i + "] = " + a[i]);
}
[Link]("========= Array Modified by the main program ========\n");
[Link](a);
[Link]("========= Print ModifiedArray ========");
ar.print_array(a);
[Link]("Hello, World!");

}
}

Program for impure methods – Example 2D Array – Matrix addition


Matrix addition :
Example Only matrix of the same dimensions can be added.
1 2 1 2 1+1 2+2 2 4
Example 𝑎 = [ ] 𝑏=[ ] 𝑅𝑒𝑠𝑢𝑙𝑡 𝑐 = [ ]=[ ]
3 4 3 4 3+3 4+4 6 8

// Online Java Compiler


// Use this editor to write, compile and run your Java code online
import [Link].*;
class Matrix_Manuplations
{
private int matrix_rows ;
private int matrix_columns;
public void Fill_Matrix(int x[][], int rows, int cols)
{
Scanner sc = new Scanner([Link]);
matrix_rows = rows;
matrix_columns= cols;
[Link]("Enter the numbers one by one for the matrix of size " + rows + " columns " + cols);
for (int i = 0 ; i < rows ; i++)
{
for(int j = 0 ; j < cols ; j++)
{
x[i][j] = [Link]();
}
}
return;
}

public void Print_Matrix(int x[][])


{
for (int i = 0 ; i < matrix_rows ; i++)
{
for(int j = 0 ; j < matrix_columns ; j++)
{
[Link]( x[i][j] + " " );
}
[Link]( "\n");

6
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

}
return;
}
public int[][] Add_Matrix(int x[][], int y[][] )
{
int z[][] = new int[matrix_rows][matrix_columns];
for (int i = 0 ; i < matrix_rows ; i++)
{
for(int j = 0 ; j < matrix_columns ; j++)
{
z[i][j] = x[i][j] + y[i][j];
}
}
return z;
}

public int[][] Diff_Matrix(int x[][], int y[][] )


{
int z[][] = new int[matrix_rows][matrix_columns];
for (int i = 0 ; i < matrix_rows ; i++)
{
for(int j = 0 ; j < matrix_columns ; j++)
{
z[i][j] = x[i][j] - y[i][j];
}
}
return z;
}

public static void main(String[] args) {


Matrix_Manuplations matrix = new Matrix_Manuplations();
int rows , cols ;
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of rows for Matrix A ad B");
rows = [Link]();
[Link]("Enter the number of columns for Matrix A ad B");
cols = [Link]();
//Declare matrix A
int a[][] = new int[rows][cols];
int b[][] = new int[rows][cols];
int c[][] = new int[rows][cols];
// Fill Matrix A
[Link]("Enter the values of Matrix A one by one");
matrix.Fill_Matrix(a, rows, cols);
matrix.Print_Matrix(a);

// Fill Matrix B
[Link]("Enter the values of Matrix b one by one");
matrix.Fill_Matrix(b, rows, cols);
matrix.Print_Matrix(b);
[Link]("Sum of two matrix is \n");

// Find the sum of the two matrices


c = matrix.Add_Matrix(a,b);
matrix.Print_Matrix(c);
}

7
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Program for printing patterns in Java


Date 26-11-2023
//Print the following pattern
// 1
// 1 2
// 1 2 3
// 1 2 3 4
class HelloWorld {
public static void main(String[] args) {
for(int i = 1; i <= 4 ; i++)
{
for(int j = 1 ; j <= i ; j++)
{
[Link](j );
}
[Link](" ");
}
}
}

// Online Java Compiler


// Use this editor to write, compile and run your Java code online
//Print the following pattern
// 1
// 2 3
// 4 5 6
// 7 8 9 10
class HelloWorld {
public static void main(String[] args) {
int k = 1;
for(int i = 1; i <= 4 ; i++)
{
for(int j = 1 ; j <= i ; j++)
{
[Link](k + " ");
k++;
}
[Link](" ");
}
}
}
//Print the following pattern
// *
// * *
// * * *
// * * * *
class HelloWorld {
public static void main(String[] args) {
for(int i = 1; i <= 4 ; i++)
{

8
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

for(int j = 1 ; j <= i ; j++)


{
[Link]("*" + " ");
}
[Link]("\r\n");
}
}
}
// 1
// 1 0
// 1 0 1
// 1 0 1 0
class HelloWorld {
public static void main(String[] args) {
for(int i = 1; i <= 4 ; i++)
{
for(int j = 1 ; j <= i ; j++)
{
if(j%2 ==0)
{
[Link]("0" + " ");
}
else
{
[Link]("1" + " ");
}
}
[Link]("\r\n");
}
}
}

Programming – Sorting and searching

Program for Linear search


Searching Algorithms:

Linear search: The most simplest search algorithm where the array need not be ordered
//Linear Search
// Watch this youtube video [Link]
import [Link].*;
class Linear_Search {
public static void main(String[] args) {
int a[] = new int[10];

9
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

int found = 0;
Scanner sc = new Scanner([Link]);
[Link]("Fill the entry in the array 10 elements");
//Initialize the array with some value
for (int i = 0 ; i < 10 ; i++)
{
a[i] = [Link]();
}
[Link]("Enter the number to be searched");
int x = [Link]();
[Link]("Array entered");

for (int i = 0 ; i < 10 ; i++)


{
[Link](a[i]);
}
//Array is filled with values entered by the user
// Let us assume that the number to be searched is 10
// 0 1 2 3 4 5 6 7 8 9
for(int i = 0 ; i < 10; i++)
{

if(a[i] == x)
{
found = 1;
break;
}
}
if(found == 0)
{
//In case we exited the loop without finding it then print not found
[Link]("Number not Found");
}
else
{
[Link]("Found number");
}
}
}

Program for Binary search


Binary search

10
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

class HelloWorld {
public static void main(String[] args) {
int a[] = new int[10];
int x = 47;
//Filling the array
for (int i = 0 ; i < 10; i++ )
{
a[i] = i + 30;
}
[Link]("Original array");
for (int i = 0 ; i < 10; i++ )
{
[Link](i + ", ");
}
[Link]();
for(int i = 0 ; i < 10 ; i ++)
{
[Link](a[i] + ", ");
}
[Link]();
// search for number 35 in this array
int first = 0;
int last = 9;
int mid = 5;
int count = 1;

while( first <= last)


{
mid = (last-first)/2 + first;
[Link]("Loop count : " + count++);
[Link]("first : " +first);
[Link]("Mid : " +mid);
[Link]("last : " +last);

if(x > a[mid])


{
// Search to the right the first pointer will change now
first = mid + 1;

11
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

[Link]("x > a[mid]: Search Right" + x + ">" + a[mid]);

}
else if(x < a[mid])
{
// Search to the left the last pointer will change now
last = mid - 1;
[Link]("x < a[mid]: Search Right" + x + "<" + a[mid]);

}
else
{
//Found the number break from the loop
if(a[mid] == x)
{
[Link]("Found number");
[Link]("Index where found" + a[mid]);
break;

}
}
}
if(first > last)
{
[Link]("Found Not number");
}
}
}
Original array
0 1 2 3 4 5 6 7 8 9
30 31 32 33 34 35 36 37 38 39
Search for the number 47
Loop 1
0 1 2 3 4 5 6 7 8 9
30 31 32 33 34 35 36 37 38 39

Loop count : 1
first : 0
Mid : 4
last : 9
x > a[mid]: Search Right 47>34
Number should be to the right
0 1 2 3 4 5 6 7 8 9
30 31 32 33 34 35 36 37 38 39

Loop count : 2
first : 5
Mid : 7  (9 – 5)/2 + first = 2 + 5 This is a very important step
Mid will be 2 entries to the right of First
0 1 2 3 4 5 6 7 8 9
30 31 32 33 34 35 36 37 38 39

last : 9
x > a[mid]: Search Right47>37
0 1 2 3 4 5 6 7 8 9

12
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

30 31 32 33 34 35 36 37 38 39

Loop count : 3
first : 8
Mid : 8
last : 9
x > a[mid]: Search Right47>38
Since Mid cannot be 8/5 so Mid is also same as first in this case
Loop count : 4
first : 9
Mid : 9
last : 9
0 1 2 3 4 5 6 7 8 9
30 31 32 33 34 35 36 37 38 39

x > a[mid]: Search Right47>39


Found Not number
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
class HelloWorld {
public static void main(String[] args) {
int a[] = new int[10];
int x = 37;
//Filling the array
for (int i = 0 ; i < 10; i++ )
{
a[i] = i + 30;
}
[Link]("Original array");
for (int i = 0 ; i < 10; i++ )
{
[Link](i + ", ");
}
[Link]();
for(int i = 0 ; i < 10 ; i ++)
{
[Link](a[i] + ", ");
}
[Link]();
// search for number 35 in this array
int first = 0;
int last = 9;
int mid = 5;
int count = 1;

while( first <= last)


{
mid = (last-first)/2 + first;
[Link]("Loop count : " + count++);
[Link]("first : " +first);
[Link]("Mid : " +mid);
[Link]("last : " +last);
if(x > a[mid])
{
// Search to the right the first pointer will change now
first = mid + 1;
[Link]("x > a[mid]: Search Right" + x + ">" + a[mid]);

13
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

}
else if(x < a[mid])
{
// Search to the left the last pointer will change now
last = mid - 1;
[Link]("x < a[mid]: Search Right" + x + "<" + a[mid]);

}
else
{
//Found the number break from the loop
if(a[mid] == x)
{
[Link]("Found number");
[Link]("Index where found " + mid);
break;

}
}
}
if(first > last)
{
[Link]("Found Not number");
}
}
}
Original array
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
Loop count : 1
first : 0
Mid : 4
last : 9x > a[mid]: Search Right37>34
Loop count : 2
first : 5
Mid : 7
last : 9
Found number
Index where found 7

Program for Bubble sort


Bubble Sorting : in ascending order
In bubble Sorting After each iteration, the Largest number bubbles to the end

Example :
array: [ 8,7,5,2]

14
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Observe that the largest number has bubbled to the END

Observe number 7 took second last place Observe number 5 took third last place Finally the array is sorted

class BubbleSort_Ascending {
public static void main(String[] args) {
int arr[] = new int[10];
int x = 37;
//Filling the array
for (int i = 0 ; i < 10; i++ )
{
arr[i] = (int)([Link]() * 100);
}
[Link]("Original array\n");
for (int i = 0 ; i < 10; i++ )
{
[Link](i + ", ");
}
[Link]();
for(int i = 0 ; i < 10 ; i ++)
{
[Link](arr[i] + ", ");
}
[Link]("\r\n");

int n = [Link];
// Observe that we are only going to n-1 because at the end of each iteration, the last entry will be filled
for (int i = 0; i < n - 1; i++)

15
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

{
//Observe we are starting from 0 till n-i because every iteration one one entry will get bubbled to the last
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
[Link]("After iteration " + i);
for(int k = 0 ; k < 10 ; k ++)
{
[Link](arr[k] + ", ");
}
[Link]("\r\n");

}
}

Original array
0 1 2 3 4 5 6 7 8 9
50 64 99 12 50 90 99 34 15 70

Observe the coloured entries after each iteration


After iteration 0
50, 64, 12, 50, 90, 99, 34, 15, 70, 99,
After iteration 1
50, 12, 50, 64, 90, 34, 15, 70, 99, 99,
After iteration 2
12, 50, 50, 64, 34, 15, 70, 90, 99, 99,
After iteration 3
12, 50, 50, 34, 15, 64, 70, 90, 99, 99,
After iteration 4
12, 50, 34, 15, 50, 64, 70, 90, 99, 99,
After iteration 5
12, 34, 15, 50, 50, 64, 70, 90, 99, 99,
After iteration 6
12, 15, 34, 50, 50, 64, 70, 90, 99, 99,
After iteration 7
12, 15, 34, 50, 50, 64, 70, 90, 99, 99,
After iteration 8
12, 15, 34, 50, 50, 64, 70, 90, 99, 99,

Bubble sort to sort the array in Descending order


class BubbleSort_Descending {
public static void main(String[] args) {
int arr[] = new int[10];
int x = 37;
//Filling the array
for (int i = 0 ; i < 10; i++ )
{
arr[i] = (int)([Link]() * 100);
}

16
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

[Link]("Original array\n");
for (int i = 0 ; i < 10; i++ )
{
[Link](i + ", ");
}
[Link]();
for(int i = 0 ; i < 10 ; i ++)
{
[Link](arr[i] + ", ");
}
[Link]("\r\n");

int n = [Link];
// Observe that we are only going to n-1 because at the end of each iteration, the last entry will be filled
for (int i = 0; i < n - 1; i++)
{
//Observe we are starting from 0 till n-i because every iteration one one entry will get bubbled to the last
for (int j = 0; j < n - i - 1; j++)
if (arr[j] < arr[j + 1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
[Link]("After iteration " + i);
for(int k = 0 ; k < 10 ; k ++)
{
[Link](arr[k] + ", ");
}
[Link]("\r\n");

}
}

Original array
0 1 2 3 4 5 6 7 8 9
44 32 95 48 32 49 36 44 98 26
After iteration 0
44, 95, 48, 32, 49, 36, 44, 98, 32, 26,
After iteration 1
95, 48, 44, 49, 36, 44, 98, 32, 32, 26,
After iteration 2
95, 48, 49, 44, 44, 98, 36, 32, 32, 26,
After iteration 3
95, 49, 48, 44, 98, 44, 36, 32, 32, 26,
After iteration 4
95, 49, 48, 98, 44, 44, 36, 32, 32, 26,
After iteration 5
95, 49, 98, 48, 44, 44, 36, 32, 32, 26,
After iteration 6
95, 98, 49, 48, 44, 44, 36, 32, 32, 26,
After iteration 7
98, 95, 49, 48, 44, 44, 36, 32, 32, 26,
After iteration 8

17
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

98, 95, 49, 48, 44, 44, 36, 32, 32, 26,

Program for Selection sort


Selection Sorting

class Selection_Ascending {
public static void main(String[] args) {
int arr[] = new int[10];
int x = 37;
//Filling the array
for (int i = 0 ; i < 10; i++ )
{
arr[i] = (int)([Link]() * 100);
}
[Link]("Original array\n");
for (int i = 0 ; i < 10; i++ )
{
[Link](i + ", ");
}
[Link]();
for(int i = 0 ; i < 10 ; i ++)
{
[Link](arr[i] + ", ");
}
[Link]("\r\n");
int n = [Link];
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;

18
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

for (int j = i+1; j < n; j++)


if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first


// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
[Link]("Iteration : " + i);
for(int k = 0 ; k < 10 ; k ++)
{
[Link](arr[k] + ", ");
}
[Link]("\r\n");
}
}
}

Original array
0 1 2 3 4 5 6 7 8 9
17 11 55 51 45 41 73 40 44 59

Iteration : 0
11, 17, 55, 51, 45, 41, 73, 40, 44, 59,
Iteration : 1
11, 17, 55, 51, 45, 41, 73, 40, 44, 59,
Iteration : 2
11, 17, 40, 51, 45, 41, 73, 55, 44, 59,
Iteration : 3
11, 17, 40, 41, 45, 51, 73, 55, 44, 59,
Iteration : 4
11, 17, 40, 41, 44, 51, 73, 55, 45, 59,
Iteration : 5
11, 17, 40, 41, 44, 45, 73, 55, 51, 59,
Iteration : 6
11, 17, 40, 41, 44, 45, 51, 55, 73, 59,
Iteration : 7
11, 17, 40, 41, 44, 45, 51, 55, 73, 59,

class Selection_Descending {
public static void main(String[] args) {
int arr[] = new int[10];
int x = 37;
//Filling the array
for (int i = 0 ; i < 10; i++ )
{
arr[i] = (int)([Link]() * 100);
}
[Link]("Original array\n");
for (int i = 0 ; i < 10; i++ )
{
[Link](i + ", ");
}
[Link]();
for(int i = 0 ; i < 10 ; i ++)

19
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

{
[Link](arr[i] + ", ");
}
[Link]("\r\n");
int n = [Link];
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the maximum element in unsorted array
int max_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] > arr[max_idx])
max_idx = j;

// Swap the found maximum element with the first


// element
int temp = arr[max_idx];
arr[max_idx] = arr[i];
arr[i] = temp;
[Link]("Iteration : " + i);
for(int k = 0 ; k < 10 ; k ++)
{
[Link](arr[k] + ", ");
}
[Link]("\r\n");
}
}
}
Original array
0 1 2 3 4 5 6 7 8 9
77 18 6 37 39 75 64 52 70 48

Iteration : 0
77, 18, 6, 37, 39, 75, 64, 52, 70, 48,
Iteration : 1
77, 75, 6, 37, 39, 18, 64, 52, 70, 48,
Iteration : 2
77, 75, 70, 37, 39, 18, 64, 52, 6, 48,
Iteration : 3
77, 75, 70, 64, 39, 18, 37, 52, 6, 48,
Iteration : 4
77, 75, 70, 64, 52, 18, 37, 39, 6, 48,
Iteration : 5
77, 75, 70, 64, 52, 48, 37, 39, 6, 18,
Iteration : 6
77, 75, 70, 64, 52, 48, 39, 37, 6, 18,
Iteration : 7
77, 75, 70, 64, 52, 48, 39, 37, 6, 18,
Iteration : 8
77, 75, 70, 64, 52, 48, 39, 37, 18, 6,

20
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Programming – Classes and objects

Program for Classes and objects demonstration - Constructors


Date 08-12-2023

// Online Java Compiler


// Use this editor to write, compile and run your Java code online

import [Link].*;
import [Link];
class Employee
{
private int age;
private int id;
// Can be seen by base class and derived class
protected int salary;
public String name;

// Caution Do not add any return type to a constructor it will give an error because Java knows its void
//Constructor with no parameters
Employee()
{
name = "NA";
id = -1;
age = -1;
salary = -1;
}
//Constructor with all parameters filled in
Employee(int age_emp, int id_emp, int salary_emp, String name_emp)
{
name = name_emp;
id = id_emp;
age = age_emp;
salary = salary_emp;
}
//Constructor with Few parameters filled in
Employee(String name_emp)
{
name = name_emp;
id = -2;
age = -2;
salary = -2;
}
public void print_data()
{
[Link]("Employee name" + name);
[Link]("Employee age" + age);
[Link]("Employee id" + id);
[Link]("Employee salary" + salary);
}
public void fill_age(int age_emp)
{
age = age_emp;

21
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

class Organization {
public static void main(String[] args)
{
Employee e1 = new Employee(10, 100, 500, "X");
Employee e2 = new Employee(60, 200, 1000, "Y");
Employee e3 = new Employee();
Employee e4 = new Employee("Ramaswamy");
e1.print_data();
[Link]("-------------------");
e2.print_data();
[Link]("-------------------");
e3.print_data();
[Link]("-------------------");
e4.print_data();
[Link] = "Krihna";
[Link] = 101;
e1.print_data();

[Link]("Hello, World!");
}
}

Program for Classes and objects Copy Constructors


Copy constructor : Creates a copy of the object
// Online Java Compiler
// Use this editor to write, compile and run your Java code online

import [Link].*;
import [Link];
class Employee
{
private int age;
private int id;
protected int salary;
public String name;

//Constructor with no parameters


Employee()
{
name = "NA";
id = -1;
age = -1;
salary = -1;
}
//Constructor with all parameters filled in
Employee(int age_emp, int id_emp, int salary_emp, String name_emp)
{
name = name_emp;
id = id_emp;
age = age_emp;
salary = salary_emp;

22
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Program for Classes and objects Constructors


//Constructor with all parameters filled in
Employee(Employee p)
{
name = [Link];
id = [Link];
age = [Link];
salary = [Link];
}

//Constructor with Few parameters filled in


Employee(String name_emp)
{
name = name_emp;
id = -2;
age = -2;
salary = -2;
}
public void print_data()
{
[Link]("Employee name" + name);
[Link]("Employee age" + age);
[Link]("Employee id" + id);
[Link]("Employee salary" + salary);
}
public void fill_age(int age_emp)
{
age = age_emp;
}
}

class Organization {
public static void main(String[] args)
{
Employee e1 = new Employee(10, 100, 500, "X");
e1.print_data();
[Link]("-------------------\n\r");
Employee e2 = e1;
e2.print_data();
[Link] = "Rama";
e2.print_data();
[Link]("-------------------\n\r");
e1.print_data();
[Link]("-------------------\n\r");
Employee e3 = new Employee(e1);
e3.print_data();
[Link]("-------------------\n\r");
[Link] = "Krishna";
e3.print_data();
[Link]("-------------------\n\r");

[Link] = "Rowdy";
e1.print_data();

23
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

[Link]("-------------------\n\r");
e2.print_data();
[Link]("-------------------\n\r");
e3.print_data();
[Link]("-------------------\n\r");

}
}

Direct Copy copy constructor: Creates a link between two classes


If E1 changes E2 will change. If E2 changes E1 will change

Copy constructor by passing object: Creates an independent copy which is not linked to the main class
If E1 changes E3 will NOT change. If E3 changes E1 will NOT change

Program for Classes and objects Constructors – This keyword in java


// Online Java Compiler
// Use this editor to write, compile and run your Java code online

import [Link].*;
import [Link];
class Employee
{
private int age;
private int id;
protected int salary;
public String name;

//Constructor with no parameters


Employee()
{
name = "NA";
id = -1;
age = -1;
salary = -1;
}
//Constructor with all parameters filled in
Employee(int age_emp, int id_emp, int salary_emp, String name_emp)
{
name = name_emp;
id = id_emp;
age = age_emp;
salary = salary_emp;
}

//Constructor with all parameters filled in


Employee(Employee p)
{
name = [Link];
id = [Link];
age = [Link];
salary = [Link];
}

24
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

//Constructor with Few parameters filled in


Employee(String name_emp)
{
name = name_emp;
id = -2;
age = -2;
salary = -2;
}
public void print_data()
{
[Link]("Employee name" + name);
[Link]("Employee age" + age);
[Link]("Employee id" + id);
[Link]("Employee salary" + salary);
}
public void fill_age(int age_emp)
{
[Link] = age_emp;
}

class Organization {
public static void main(String[] args)
{
Employee e1 = new Employee(10, 100, 500, "X");
e1.print_data();
[Link]("-------------------\n\r");
Employee e2 = e1;
e2.print_data();
[Link] = "Rama";
e2.print_data();
[Link]("-------------------\n\r");
e1.print_data();
[Link]("-------------------\n\r");
Employee e3 = new Employee(e1);
e3.print_data();
[Link]("-------------------\n\r");
[Link] = "Krishna";
e3.print_data();
[Link]("-------------------\n\r");

[Link] = "Rowdy";
e1.print_data();
[Link]("-------------------\n\r");
e2.print_data();
[Link]("-------------------\n\r");
e3.print_data();
[Link]("-------------------\n\r");
e1.fill_age(1000);
e1.print_data();
[Link]("-------------------\n\r");
e2.print_data();
[Link]("-------------------\n\r");
e3.print_data();

25
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

[Link]("-------------------\n\r");

}
}

This: It is used resolve conflicts when there is a name resolution issue. Specially affects when you have multiple classes with
same method name or when you use copy constructor (indirect copy)

Program for Classes and objects Static methods


// Online Java Compiler
// Use this editor to write, compile and run your Java code online

import [Link].*;
import [Link];
class Organization {
public static void main(String[] args)
{
fun();
}
static void fun()
{
[Link](" Fun friday-\n\r");
}
}
If you remove the keyword static then the code will not compile because main is a static method it can only call another static
method. Note static method has ONLY 1 copy in memory.

Autoboxing
Autoboxing is a property in Java where we convert primitive data types to classes. Example

int x = 0 ; // This is a primitive data type where there are not checks done to the data.

Where as Integer x = new Integer(10.0) since the class Integer is not a primitive data type it is considered
to be Autoboxed. By auto boxing we are able to add some checks in the constructor.

Auto Unboxing : This is a process of converting a non primitive datatype to a primitive datatype

Example

Integer x = new Integer(10.0)

int y = (int)(x);

here the variable x which is autoboxed has been unboxed using explicit type conversion
Example 2
// This is a primitive data type
int a = 10;
// This is variable b is autoboxed data type with the default value as a
Integer b = new Integer(a);
// This is variable b is autoboxed data type with the default value as a there are two ways to write this
Integer b = a;

26
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Example 2
// This is variable a is autoboxed data type with the default value as a as 10 because 10 is the integer value of 10.5
Integer a = new Integer(10.5);
// This is variable b is autounboxed data type with the default value as a 10
int b = a;

// Online Java Compiler


// Use this editor to write, compile and run your Java code online

import [Link].*;
import [Link];
class Employee
{
private int age;
private int id;
protected int salary;
public String name;

//Constructor with Few parameters filled in


Employee(int age_emp)
{
name = "NA";
id = -2;
if(age_emp <0)
{
age = 0;
}
else
{
age = age_emp;
}

salary = -2;
}
public void print_data()
{
[Link]("Employee name" + name);
[Link]("Employee age" + age);
[Link]("Employee id" + id);
[Link]("Employee salary" + salary);
}
}

class Organization {
public static void main(String[] args)
{
Employee e1 = new Employee(10);
Integer i = new Integer((int)-7.4);
int j = (int)7.4;
e1.print_data();
[Link]("-------------------\n\r"+i);

}
}

27
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Unit IV Mathematical Library methods – import [Link].*


Table 1 Unit IV Mathematical methods in java

Method Description Positive Example Negative Example


Returns the absolute value of a
`abs(double a)` double value. `[Link](5.5)` returns `5.5` `[Link](-7.2)` returns `7.2`
Returns the smallest double
value that is greater than or
`ceil(double a)` equal to the argument. `[Link](4.3)` returns `5.0` `[Link](-3.8)` returns `-3.0`
Returns the largest double value
that is less than or equal to the
`floor(double a)` argument. `[Link](4.8)` returns `4.0` `[Link](-2.5)` returns `-3.0`
Returns the closest long to the
`round(double a)` argument. `[Link](5.6)` returns `6` `[Link](-3.4)` returns `-3`
Returns the positive square root `[Link](-16.0)` returns `NaN`
`sqrt(double a)` of a double value. `[Link](25.0)` returns `5.0` (Not a Number)
Returns the cube root of a
`cbrt(double a)` double value. `[Link](8.0)` returns `2.0` `[Link](-27.0)` returns `-3.0`
Returns the value of the first
argument raised to the power of `[Link](-2.0, 2.0)` returns
`pow(double a, double b)` the second argument. `[Link](2.0, 3.0)` returns `8.0` `4.0`
Returns Euler's number e raised `[Link](-2.0)` returns
`exp(double a)` to the power of a double value. `[Link](1.0)` returns `2.71828` `0.13534`
Returns the rounded integer to
‘rint(double a)’ the smallest value `[Link](-8.5)` returns `-9.0` `[Link](8.5)` returns `8.0`

28
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Method Description Positive Example Negative Example


`[Link](2.0)` returns `[Link](0.5)` returns `-
`log(double a)` Returns the natural logarithm (base e) of a double value. `0.69315` 0.69315`
`[Link]([Link] / 2)` `[Link](-[Link] / 4)`
`sin(double a)` Returns the trigonometric sine of an angle. returns `1.0` returns `-0.70711`
`[Link](0.0)` returns `[Link](-[Link])`
`cos(double a)` Returns the trigonometric cosine of an angle. `1.0` returns `-1.0`
`[Link]([Link] / 4)` `[Link](-[Link] / 6)`
`tan(double a)` Returns the trigonometric tangent of an angle. returns `1.0` returns `-0.57735`
`toDegrees(doub Converts an angle measured in radians to an approximately `[Link]([Link] / `[Link](-
le angrad)` equivalent angle measured in degrees. 2)` returns `90.0` [Link])` returns `-180.0`
`toRadians(doubl Converts an angle measured in degrees to an approximately `[Link](180.0)` `[Link](-90.0)`
e angdeg)` equivalent angle measured in radians. returns `3.14159` returns `-1.5708`

Chapter 4 String handling – import [Link].*


Table 2 Chapter 4 String functions methods in java

Method Description Example Code Snippet


String str = "Hello"; int length =
`length()` Returns the length of the string. `"Hello".length()` returns `5` [Link]();
Returns the character at the String str = "Hello"; char
`charAt(int index)` specified index. `"Hello".charAt(1)` returns `'e'` charAtIndex = [Link](1);
Concatenates the specified `"Hello".concat(" World")` returns String str = "Hello"; String newStr
`concat(String str)` string to the end. `"Hello World"` = [Link](" World");
Compares the string with the `"hello".equals("Hello")` returns String str = "hello"; boolean
`equals(Object obj)` specified object. `false` isEqual = [Link]("Hello");
String str = "hello"; boolean
Compares the string, ignoring `"hello".equalsIgnoreCase("Hello")` isEqualIgnoreCase =
`equalsIgnoreCase(String str)` case considerations. returns `true` [Link]("Hello");
Returns the index of the first
occurrence of the specified `"Hello World".indexOf("World")` String str = "Hello World"; int
`indexOf(String str)` substring. returns `6` index = [Link]("World");

29
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Returns a new string that is a `"Hello".substring(1)` returns String str = "Hello"; String substr
`substring(int beginIndex)` substring. `"ello"` = [Link](1);
String str = "hello"; String
Converts the string to `"hello".toUpperCase()` returns upperCaseStr =
`toUpperCase()` uppercase. `"HELLO"` [Link]();
String str = "HELLO"; String
Converts the string to `"HELLO".toLowerCase()` returns lowerCaseStr =
`toLowerCase()` lowercase. `"hello"` [Link]();
Removes leading and trailing `" Hello ".trim()` returns String str = " Hello "; String
`trim()` whitespaces. `"Hello"` trimmedStr = [Link]();

30
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Method Description Example Snippet


`startsWith(String Checks if the string starts with `"Hello World".startsWith("Hello")` String str = "Hello World"; boolean
prefix)` the specified prefix. returns `true` startsWithHello = [Link]("Hello");
`"Hello
Checks if the string ends with World".endsWith("World")` String str = "Hello World"; boolean
`endsWith(String suffix)` the specified suffix. returns `true` endsWithWorld = [Link]("World");
Compares two strings
lexicographically. Returns a
positive integer if the first string `"abc".compareTo("def")` returns a
is greater, a negative integer if negative value
`compareTo(String it's smaller, and 0 if they are `"abc".compareTo("aef")` returns a String str1 = "abc"; String str2 = "def"; int
anotherString)` equal. 1 result = [Link](str2);
Returns the index of the first
occurrence of the specified `"Hello World".indexOf("World")` String str = "Hello World"; int index =
`indexOf(String str)` substring. returns `6` [Link]("World");
Returns the index of the last
occurrence of the specified `"Hello World".lastIndexOf("o")` String str = "Hello World"; int lastIndex =
`lastIndexOf(String str)` substring. returns `7` [Link]("o");
Replaces all occurrences of a
`replace(char oldChar, specified character with `"Hello".replace('l', 'X')` returns String str = "Hello"; String replacedStr =
char newChar)` another. `"HeXXo"` [Link]('l', 'X');
`replace(String oldString, Replaces all occurrences of a `"Hello World".replace('Hello', String str = "Hello World"; String
String new String)` specified string with another. 'Bye')` returns `"Bye World"` replacedStr = [Link]('Hello', 'Bye');
“COMPUTER”.reverse() returns String str = "COMPUTER"; String reversed=
`replace(String data,)` Reverses a given string. RETUPMOC [Link]();

Table 3 Chapter 4 String buffer functions methods in java

31
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Method Description Example Code Snippet


Appends the specified string to `new StringBuffer("Hello").append(" StringBuffer sb = new StringBuffer("Hello");
`append(String str)` the end of the `StringBuffer`. World")` returns `Hello World` [Link](" World"); ```
`insert(int offset, Inserts the specified string at `new StringBuffer("Hello").insert(1, StringBuffer sb = new StringBuffer("Hello");
String str)` the specified offset. "i")` returns `Hiello` [Link](1, "i");
`delete(int start, int Deletes characters from `start` `new StringBuffer("Hello").delete(1, StringBuffer sb = new StringBuffer("Hello");
end)` to `end - 1`. 3)` returns `Hlo` [Link](1, 3);
`new
`deleteCharAt(int Deletes the character at the StringBuffer("Hello").deleteCharAt(1)` StringBuffer sb = new StringBuffer("Hello");
index)` specified index. returns `Hllo` [Link](1);
Reverses the characters in the `new StringBuffer("Hello").reverse()` StringBuffer sb = new StringBuffer("Hello");
`reverse()` `StringBuffer`. returns `olleH` [Link]();
Replaces characters from `start`
`replace(int start, int to `end - 1` with the specified `new StringBuffer("Hello").replace(1, StringBuffer sb = new StringBuffer("Hello");
end, String str)` string. 3, "i")` returns `Hilo` [Link](1, 3, "i");
Returns a new `String` that
contains a subsequence of
characters currently in the `new
`StringBuffer`, starting from the StringBuffer("Hello").substring(1)` StringBuffer sb = new StringBuffer("Hello");
`substring(int start)` specified index. returns `ello` String substr = [Link](1);

32
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Chapter 5 User defined methods


Example of user defined method
Table 4 Chapter 5 User defined methods - Simple

public class UserDefinedMethodExample {

// User-defined method to add two integers


public static int addTwoNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum;
}

public static void main(String[] args) {


// Calling the user-defined method
int result = addTwoNumbers(5, 7);

// Printing the result


[Link]("The sum of two numbers is: " + result);
}
}
Table 5 User defined method over loading

public class OverloadingExample {


// Overloaded method to add two integers
public static int add(int num1, int num2) {
return num1 + num2;
}

// Overloaded method to add two doubles


public static double add(double num1, double num2) {
return num1 + num2;
}

public static void main(String[] args) {


// Calling the overloaded methods
int resultInt = add(5, 7);
double resultDouble = add(3.5, 2.5);

// Printing the results


[Link]("Sum of two integers: " + resultInt);
[Link]("Sum of two doubles: " + resultDouble);
}
}

Table 6 Chapter 5 User defined method Impure function – Arrays – Call by reference

public class CallByReferenceExample {

// Method that modifies the array


public static void modifyArray(int[] arr) {
for (int i = 0; i < [Link]; i++) {
arr[i] *= 2; // Doubling each element

33
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

}
}

public static void main(String[] args) {


// Creating an array
int[] numbers = {1, 2, 3, 4, 5};

// Printing the original array


[Link]("Original Array:");
for (int num : numbers) {
[Link](num + " ");
}

// Calling the method that modifies the array


modifyArray(numbers);

// Printing the modified array


[Link]("\nModified Array:");
for (int num : numbers) {
[Link](num + " ");
}
}
}

Original Array:

12345

Modified Array:

2 4 6 8 10

Chapter 6 Classes and objects


Table 7 Chapter 6 Example of a class with public private and protected

// [Link]
public class MainClass {
public static void main(String[] args) {
// Accessing public class
PublicAccessExample publicExample = new PublicAccessExample();
[Link]("Public variable: " + [Link]);
[Link]();

// Accessing protected class


ProtectedAccessExample protectedExample = new ProtectedAccessExample();
[Link]("Protected variable: " + [Link]);
[Link]();

// Accessing default (package-private) class


DefaultAccessExample defaultExample = new DefaultAccessExample();
[Link]("Default variable: " + [Link]);
[Link]();

34
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

// Accessing private class (Note: This will result in a compilation error)


// PrivateAccessExample privateExample = new PrivateAccessExample();
// [Link]("Private variable: " + [Link]);
// [Link]();
}
}
// [Link]
class PublicAccessExample {
public int publicVariable = 10;

public PublicAccessExample() {
[Link]("Public constructor called");
}

public void publicMethod() {


[Link]("Public method called");
}
}

// [Link]
class ProtectedAccessExample {
protected int protectedVariable = 20;

protected ProtectedAccessExample() {
[Link]("Protected constructor called");
}

protected void protectedMethod() {


[Link]("Protected method called");
}
}

// [Link]
class DefaultAccessExample {
int defaultVariable = 30;

DefaultAccessExample() {
[Link]("Default constructor called");
}

void defaultMethod() {
[Link]("Default method called");
}
}

// [Link]
class PrivateAccessExample {
private int privateVariable = 40;

private PrivateAccessExample() {
[Link]("Private constructor called");
}

35
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

private void privateMethod() {


[Link]("Private method called");
}
}

Chapter 7 Constructors
Table 8 Chapter 7 Example of default constructor / Non parameterized

public class DefaultConstructorExample {

// Default constructor (automatically provided if not explicitly defined)


public DefaultConstructorExample() {
[Link]("Default constructor called");
}

public void displayMessage() {


[Link]("Hello from the DefaultConstructorExample class!");
}

public static void main(String[] args) {


// Creating an object of the class
DefaultConstructorExample exampleObject = new DefaultConstructorExample();

// Calling a method on the object


[Link]();
}
}

Table 9 Chapter 7 Example of parameterized constructor

public class Car {


// Instance variables
private String make;
private String model;
private int year;

// Parameterized constructor
public Car(String make, String model, int year) {
[Link] = make;
[Link] = model;
[Link] = year;
}

// Method to display car details


public void displayDetails() {
[Link]("Car Details:");
[Link]("Make: " + make);
[Link]("Model: " + model);

36
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

[Link]("Year: " + year);


}

public static void main(String[] args) {


// Creating an object using the parameterized constructor
Car myCar = new Car("Toyota", "Camry", 2022);

// Calling the displayDetails method to print car details


[Link]();
}
}

Table 10 Chapter 7 Example of Copy constructor

public class Student {


private String name;
private int age;

// Parameterized constructor
public Student(String name, int age) {
[Link] = name;
[Link] = age;
}

// Copy constructor
public Student(Student otherStudent) {
[Link] = [Link];
[Link] = [Link];
}

// Getter methods
public String getName() {
return name;
}

public int getAge() {


return age;
}
public void setAge(int age ) {
[Link] = age;

}
public static void main(String[] args) {
// Creating a student object using the parameterized constructor
Student student1 = new Student("John", 20);
// Creating a new student object using the copy constructor
Student student2 = new Student(student1);
// Creating a student object as a reference
Student student3 = student1;
// Displaying information about the original and copied objects
[Link]("Original Student: " + [Link]() + ", " + [Link]() + " years old");

37
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

[Link]("Copied Student: " + [Link]() + ", " + [Link]() + " years old");
//Observe that any changes to student 3 will affect student 1 also
[Link]("Referenced Student: " + [Link]() + ", " + [Link]() + " years old");
[Link](100);
[Link]("Original Student: " + [Link]() + ", " + [Link]() + " years old");
[Link](200);
[Link]("Copied Student: " + [Link]() + ", " + [Link]() + " years old");
[Link](300);
[Link]("referenced Student: " + [Link]() + ", " + [Link]() + " years old");
[Link]("Original Student: " + [Link]() + ", " + [Link]() + " years old");
//Observe student 1 age is also changed to 300 here

}
}

Chapter 8 Encapsulation and inheritance

Table 11 Chapter 8 Encapsulation

public class EncapsulationExample {

// Private variables (attributes) are not directly accessible outside the class
private String name;
private int age;

// Public methods (getters and setters) provide controlled access to the private variables
public String getName() {
return name;
}

public void setName(String newName) {


// Additional validation or logic can be added here
if (newName != null && ![Link]()) {
name = newName;
} else {
[Link]("Invalid name");
}
}

public int getAge() {


return age;
}

public void setAge(int newAge) {


// Additional validation or logic can be added here
if (newAge > 0) {
age = newAge;
} else {
[Link]("Invalid age");
}

38
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

public static void main(String[] args) {


// Creating an object of the class
EncapsulationExample person = new EncapsulationExample();

// Accessing and modifying data using public methods


[Link]("John");
[Link](25);

// Retrieving and displaying data using public methods


[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());
}
}

Table 12 Chapter 8 Inheritance – Leave this if its tough

public class NestedInheritanceExample {


public static void main(String[] args) {
// Creating an object of the derived class
Dog myDog = new Dog();

// Accessing methods from the base class


[Link](); // Inherited from Animal

// Accessing methods from the intermediate class


[Link](); // Inherited from Mammal

// Accessing methods from the derived class


[Link](); // Specific to Dog
}
}

// Base class
class Animal {
void eat() {
[Link]("Animal is eating");
}
}

// Intermediate class inheriting from Animal


class Mammal extends Animal {
void run() {
[Link]("Mammal is running");
}
}

// Derived class inheriting from Mammal


class Dog extends Mammal {
void bark() {
[Link]("Dog is barking");
}

39
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Computer application Section A Sample question paper


Question 1

1. Study the following picture and identify which object oriented principle is illustrated

They are different breeds of dogs. Each dog eats different types of food and different quantities
of food
a) Inheritance b) polymorphism c) Encapsulation d) Abstraction
2. Identify all the procedural languages listed below
a. Java
b. C
c. FORTRAN
d. Python
e. COBOL
3. Study the code snippet and identify the data members and member methods
import [Link];
public class Evenodd {
int even_numberobtained = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
boolean isEven = checkEven(num);
if(isEven == true)
even_numberobtained = num;

[Link]("Is the number even? " + isEven);


}
public static boolean checkEven(int number) {
return number % 2 == 0; // Find and fix the fault in this line
}
}
4. List a few non graphic characters in Java atleast 4 to be listed
5. Your friend gives you this piece of code and asks you to find the output that is printed and give a better name to the class
What is the output and what will be the name you can suggest your friend.
public class UnknownClass {
public static void main(String[] args) {
int num = 789;
int x = 0;
while (num != 0) {

40
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

// Extract the last digit


x += num % 10;
num /= 10;
}
[Link]("X: " + x);
}
}

6. Your friend gives this piece of code and tells that it has an error spot the error and fix it
public class FaultyCode {
public static void main(String[] args) {
int a = 23;
int b = 7;
int c = b/a * a ;
//I expect the output to be 7 but i am not getting it :(
[Link]("C: " + c);
}
}
7. Identify the output [Link]([Link](-8.912)) ?
a. -8.0 b) -9.0 c) 8.0 d) 9.0
8. State the type of loop in the given segment
do
{
i+ =2
}while(i >= 2 );
}
a) Fixed loop b) finite loop c) infinite loop d) null loop
9. Which of the following loops can lead to a null loop identify all of them
a. For loop b) while loop c) do while loop.
10. What is the output of [Link](-10) ?

Answer Keys Computer application Section A Test your knowledge


Maximum marks : 10

Time limit : 10 minutes


Instructions: This question paper only is for 10 marks the questions are all MCQ based with very little
writing. Total time permitted is 10 min maximum. Please write down the start time and the End time and
your name send me the answers. Please be honest and don’t refer your books or any online source

Question 1

11. Study the following picture and identify which object oriented principle is illustrated

They are different breeds of dogs. Each dog eats different types of food and different quantities
of food

41
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

b) Inheritance b) polymorphism c) Encapsulation d) Abstraction

Answer Key : Polymorphism because its given in the question that each dog eats different types of food
and quantity.

12. Identify all the procedural languages listed below


a. Java
b. C
c. FORTRAN
d. Python
e. COBOL

Answer Key : C, FORTRAN and COBOL

13. Study the code snippet and identify the data members and member methods
import [Link];
public class Evenodd {
int even_numberobtained = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
boolean isEven = checkEven(num);
if(isEven == true)
even_numberobtained = num;

[Link]("Is the number even? " + isEven);


}
public static boolean checkEven(int number) {
return number % 2 == 0; // Find and fix the fault in this line
}
}
Answer Key : Data members even_numberobtained
Member methods: Class member checkEven
Note scanner, isEven, number etc are all local variables
14. List a few non graphic characters in Java atleast 4 to be listed
Answer Key : \t \n \b \r all slash characters are also known as non graphic characters
15. Your friend gives you this piece of code and asks you to find the output that is printed and give a better name to the class
What is the output and what will be the name you can suggest your friend.
public class UnknownClass {
public static void main(String[] args) {
int num = 789;
int x = 0;
while (num != 0) {
// Extract the last digit
x += num % 10;
num /= 10;
}
[Link]("X: " + x);
}
}
Answer Key : X: 24 better name of class SumofDigits
16. Your friend gives this piece of code and tells that it has an error spot the error and fix it
public class FaultyCode {

42
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

public static void main(String[] args) {


int a = 23;
int b = 7;
int c = b/a * a ;
//I expect the output to be 7 but i am not getting it :(
[Link]("C: " + c);
}
}
Answer Key : C should have been d floating point variable and we should do the following
correction
double c = (float)b/a * a
17. Identify the output [Link]([Link](-8.912)) ?
a. -8.0 b) -9.0 c) 8.0 d) 9.0
Answer Key d) 9.0
18. State the type of loop in the given segment
do
{
i+ =2
}while(i >= 2 );
}
b) Fixed loop b) finite loop c) infinite loop d) null loop

Answer Key: c) infinite loop

19. Which of the following loops can lead to a null loop identify all of them
a. For loop b) while loop c) do while loop.

Answer Key: a) for loop b) while loop

20. What is the output of [Link](-10) ?

Answer Key: Nan

Computer application Section A test your knowledge 2


1. Which of the following piece of code is valid to read a character from the user
a) char ch = [Link];
b) char ch = [Link](0);
c) char ch = [Link]().charAt(0);
d) All of the above
e) None of the above
2. What is the output of [Link](-20.4)
a. -20.0
b. -21.0
c. 20
d. 21
3. How many constructors can you define in a class
a. Only one
b. Only two one with a return and one without a return
c. Many each having a separate return type
d. Many without a return

43
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

4. Predict the output


for( int i = 0 ; i <3; i++)
[Link](i);
a) 3
b) 012
c) 123
d) error
5. What is the output of the line [Link](5/3)
a. 1.0
b. 0.0
c. 1.66
d. 2
6. What is the output of the line “Trip”.replace(“p”, “mm”)
a. Trimm
b. Trimmm
c. Trimp
d. Tripm
7. Identify the output for the below code
int rows = 5;
for(int i = rows ; i >=1 i--)
{
for(int j = rows; j >=i; j--)
[Link]("j);
[Link]();
}
a) 5 b) 1 c) 1 d) 5
54 22 12 44
543 333 123 333
5432 4444 1234 2222
54321 55555 12345 11111

8. Predict the output of


int a[] = {5,6,8,4,3,10,-1,-2}
[Link]([Link]([Link](a[7],a[4]), [Link](a[2])));
a) -2.0
b) -2
c) 8.0
d) -8.0
3
𝑀𝑖𝑛(−23 , √2) = 𝑀𝑖𝑛(−8.0, 2) = −8.0

9. What is the output of the piece of code


int a = 10 , b = 4, c=0;
if(a>b ||a!=b)

44
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

c = ++a+--b;
[Link](a+b+c);
a) 14
b) 29
c) 28
d) 27

14+11+3

10. The access specifier that prohibits a class member from being used outside of a class is
a. Private
b. Protected
c. Pubic
d. none

Computer application Section A test your knowledge 2A – Class 9


1. Study the picture. What feature of Java can you relate this picture to

a) Polymorphism
b) Inheritance.
c) Encapsulation
d) Data abstraction
2. Emp E = new Emp(); In this line the variable E can be called as
a. Object.
b. Class
c. Variable
d. None of these
3. Which of the following does not belong to a character set
a. Letters
b. Digits
c. Operators
d. Delimiters
e. None of the above.
4. Arun wanted to print the marks obtained by students as shown below
Name: Marks
Student1 50
Student2 80
What escape sequence can you suggest Arun to add in his code to get the above format?
Answer Escape sequence tab \t

45
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

5. Assertion In the statement Integer i = 10; Integer i can be replaced with int I Reason Integer and
int are same in Java
a. Both A and R are correct
b. Both A and R are wrong
c. A is right R is wrong
d. R is right A is wrong
Answer key : Integer i = 10 is an example of Autoboxing Integer is a class which wraps an int
literal.
6. ( ; ) ( . ) and (, ) are examples of punctuators
7. Identify the correct assignments and rewrite the incorrect ones example

int 1a = 23; This is incorrect variables cannot start with a number the correct notation is int a_1
= 23;

a) int m = 100.0;  int m = 100 ; cannot assign a float to integer


b) String str = “Computer”;  Correct
c) Integer I = null;  Correct
d) float f = 1.0f;  Correct
8. Write the correct Java expression for the following statements
𝑥2 𝑦2
a. + =1
𝑎2 𝑏2
3 2
b. √3𝑥 + 4𝑥 −5
9. a++ is an example of prefix increment True or false  False its post fix
10. write an expression to find the max of a and b using a ternary operator.
(a>b)?a:b

Section A practice paper

Section A [40 Marks]

1. 𝑖𝑓 ((𝑎 > 𝑏)&& (𝑎 > 𝑐)) then we can conclude that


a. 𝑎 𝑖𝑠 𝑡ℎ𝑒 𝑏𝑖𝑔𝑔𝑒𝑠𝑡 𝑛𝑢𝑚𝑏𝑒𝑟
b. b is the biggest number
c. c is the biggest number
d. b is the smallest number
2. Which of the following lines of code will give a syntax error while compiling in Java
a. [Link](“Hello”);
b. [Link]([Link](3,2) + [Link](2,3));
c. [Link](arr(0)) ; // where arr is an array
d. [Link](“substring”.substring(2,4).chatAt(0));
3. A class is
a. An Object factory
b. Blueprint to create objects
c. Specifies methods members and data members
d. All of the above

46
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

4. If 𝑥 = −1 then what will the following statement evaluate to + + 𝑥 − + + 𝑥/− − 𝑥


a. 0
b. 1
c. -1
d. Run time error
5. Consider the following code snippet. What will be the value of x and y given
double X = Double(9.95);
Integer Y = (int)X;
a) X = 9.95 ; Y = 9.0
b) X = 9.95 ; Y = 9.95
c) X = 9.95 ; Y = 9
d) X = 9 ; Y = 9.0
6. If s1 = “hello” and s2 = “World” then [Link](s2) gives False
7. What is the output of the following expression
String s1 = "This is an example of index";
[Link]([Link]("i"));
a) 2 b) 5 c) 21 d) 22
8. Which of the following operators cannot be used in an if-else statement
a. >
b. <=
c. ||
d. ? :
9. JVM converts
a. Bytecode to bytecode of the underlying operating system
b. Byte code to machine code
c. High level code to Byte code
d. Byte code to high level code
10. Assertion : Binary search is more efficient compared to linear search. Reason Linear search
requires lesser comparisons than binary search
a. Assertion is correct
b. Reason is correct
c. Both Assertion and reason are correct
d. Both Assertion and reason are wrong
11. An access specifier that can be accessed by the baseclass and all its inherited classes is
a. Private
b. Public
c. Protected
d. None of the above
12. The return type of the following Java statement “Apples”.comparesTo(“Baskets”) is -1
13. The value a[10] returns the ___ element in an array
a. 9th element
b. 10th element
c. 11th element

47
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

d. 8th element
14. ____ class is used to convert a primitive datatype to its corresponding object
a. String
b. Wrapper
c. System
d. Math
15. Read the following text and choose the correct answer:
Java constructor overloading is a technique in which a class can have any number of constructors
that differ in parameter list. The compiler differentiates these constructors by taking into
account the number of parameters in the list and their type.
Why do we use constructor overloading?
a) To use different types of constructors.
b) Because it's a feature provided.
c) To initialise the object in different ways.
d) To differentiate one constructor from another.
16. Assertion (A) JVM is a Java interpreter loaded in the computer memory as soon as Java is loaded.
Reason (R) JVM is different for different platforms.
a) Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of
Assertion (A).
b) Both Assertion (A) and Reason (R) are true and Reason (R) is not a correct explanation of
Assertion (A).
c) Assertion (A) is true and Reason (R) is false.
d) Assertion (A) is false and Reason (R) is true.
17. “Butane”.endsWith(“ane”) this expression returns true (true/false)
18. What is the output of [Link](25,1/2)
a. 5.0
b. 5
c. 625.0
d. 1.0
19. A function that modifies the parameters passed is called as
a. A pure function
b. Impure function
c. Parameterised function
d. Non parameterised function
20. The precedence of the following operators are AND, NOT, OR,
a. AND NOT OR
b. NOT AND OR
c. OR AND NOT
d. NOT OR AND

Question number 21 to 30 carry 2 marks each

21. Identify the output of the following code snippet


class example {

48
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

public static void main(String[] args)


{
char ch = 'A';
switch(ch) {
case 'B':
[Link]("Char is B");
case 'A':
[Link]("Char is A");
case 'C':
[Link]("Char is C");
default:
[Link]("Char is not A B or C");
}
}
}
Char is A
Char is C
Char is not A B or C

22. Find the output of the following code


In case you notice any errors re write the program with the correction and then mark the output
import [Link].*;
class example {
public static void main(String[] args)
{
String s = "Book";
[Link]([Link]('o') + [Link]('o') +[Link]('K') );
}
}
2
23. Complete the following program note that the program should store the integers given in the
constructor as private data members and the results for each data type as a public data member.
Print the output of each constructor.
import [Link].*;
//Class which multiplies two numbers of given data type and stores them as data members
class multiply
{
private int int_a ;
private int int_b;
public int int_result;
private double double_a ;
private double double_b;
public double double_result;

49
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

//Constructor to multiple two integers


multiply(int x, int y)
{
int_a = x;
int_b = y;
int_result = x*y;
}
// Constructor to multiple two doubles
multiply(double x, double y)
{
double_a = x;
double_b = y;
double_result = x*y;
}
}
// This is the main program
class example {
public static void main(String[] args)
{
//Instance of class multiply
multiply m_int = new multiply(2,3);
multiply m_double = new multiply(2.0,3.0);
[Link]("Multiply integers" + m_int.int_result);
[Link]("Multiply double" + m_double.double_result);
}
}

24. Define Autoboxing with an example


Refer your textbook
25. What is the difference between [Link](0) and break in java?
[Link](0) exits from the main program or terminates the program where as
break exits from the given loop
26. Identify the output generated from this code
class example {
public static void main(String[] args)
{
int a[];
a = new int[]{2,4,6,8,10,12,14,15, 18, 20};
for(int i = 0 ; i < [Link]; i+=2)
{
switch(i%2)

50
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

{
case 0:
a[i] = a[i]+1;
break;
case 1:
a[i] = a[i]-1;
break;
default:
break;

}
}
for(int i = 0 ; i < [Link]; i++)
{
[Link](a[i]);
}
}
}
<<Copy and paste the above code and see the output >>
27. Write a program to output the sum of the following series upto 10 terms
1 + 4 + 9 + 16 + 25 + ⋯
28. You are given an option to use linear search or binary search which one will you
chose when the data size is very small (5 samples) write all the differences
between binary search and linear search
29. Give an example of a null loop using for loop as an example
30. What are the advantages of access specifiers in java give examples.
00000000000
000000000
0000000
00000

51
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

// Online Java Compiler


// Use this editor to write, compile and run your Java code online
import [Link].*;
class RailwayTicket {
String name;
String coach;
long mobileno;
int amt;
int totalamt;
public void accept()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter name");
name = [Link]();
[Link]("Enter coach");
coach = [Link]();
[Link]("Enter mobile no");
mobileno = [Link]();
[Link]("Enter amount");
amt = [Link]();
return;
}
public void update()
{

52
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

if([Link]("First_AC"))
{
totalamt = amt + 700;
}
else if([Link]("Second_AC"))
{
totalamt = amt + 500;
}
else if([Link]("Third_AC"))
{
totalamt = amt + 250;
}
else
{
totalamt = amt;
}
return;
}
void display()
{
[Link]("Enter name: " + [Link]);
[Link]("Enter coach: " + [Link]);
[Link]("Enter amount: " + [Link]);
[Link]("Enter total amt: " + [Link]);

}
}

class MainTicket {

public static void main(String[] args) {


RailwayTicket rt = new RailwayTicket();
[Link]();
[Link]();
[Link]();
[Link]("Hello, World!");
}
}

53
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Practice programs important for exam


1. Define a class called Vehicle with the following description
a. Int vno – vehicle number
b. Int hours – store number of hours vehicle is parked
c. Int minutes – store minutes vehicle was parked (between 0 to 59 only
d. Double bill – to store bill amount

Member methods

e. Void input ()  to take the vehicle number and hours


f. Void calculate to compute the parking rate using the following rule
i. For the first 1 hour charge 5 Rs
ii. For every hour after that charge 3 Rs
iii. If the duration is greater than 30 minutes round it off to the next hour
g. Void display () to display the vehicle number, duration of parking and bill

Question 2
Write a main program which accepts an integer. The class has the method called display to the the
following.
a) Accept an intger from the user
b) If the integer is a prime number then print the following pattern

11

111

1111

c) If the integer is an odd number then check if the number is a magic number,
A number is said to be a neon number if the sum of the even numbers is twice the sum of the
odd numbers
Example number = 1224 odd number sum = 1+3 = 3 even numbers sum = 2 + 4 = 6
d) If the number is 0 then print the pattern
00000
0000
000
00
0

54
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Program 3:
Write a java program to take the marks obtained by 10 students and their name. Name should
be an array of strings and marks should be an array of integers.
Print the rank list of the class by arranging the marks in descending order and print the
corresponding name of the student.

Program 5
Accept an character from the user
If the character is + then add two matrices with dimension 3*3
If the character is - then subtract two matrices with dimension 3*3
If the character is * then check if the given 3* 3 matrix is an identity matrix
If the character is / then find the transpose of a given 3*3 matrix
Use function overloading

55
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Program to count the number of -ve numbers in an integer array and in a double array
using methods
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import [Link].*;
class HelloWorld {
/*
This program counts the number of -ve numbers in an array. For the sake of demonstration, two arrays are
considered one with data type int and the other as double.
To write such a program first we need to decide what all input variables and methods are required
1. we need a method to get integer data from the user
2. we need a method to get double data from the user
3. we can have a method to print the array or display it on the screen
4. we need a method to count the number of -ve numbers in the array
*/

/* This method is called inputarray it takes an array as an input and returns nothing (void) */
public static void inputarray(int x[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the elements of the integer array one by one");
for (int i = 0 ; i < [Link] ; i++)
{
x[i] = [Link]();
}

return;
}
/* This method is called inputarray it takes an array as an input and returns nothing (void) */
/* This is an overloaded method */
public static void inputarray(double x[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the elements of the integer array one by one");
for (int i = 0 ; i < [Link] ; i++)
{
x[i] = [Link]();
}
return;
}

/* Overloaded method to print or display the array */


public static void displayarray(int x[])
{
[Link]("Elements of the array are");
for (int i = 0 ; i < [Link] ; i++)
{
[Link](x[i] + " , " );
}
return;
}
/* Overloaded method to print or display the array */

56
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

public static void displayarray(double x[])


{
[Link]("Elements of the array are");
for (int i = 0 ; i < [Link] ; i++)
{
[Link](x[i] + " , " );
}
[Link]();
return;
}
/* Overloaded method to count -ve numbers in the array */
public static int countnegative(int x[])
{
int count = 0;
for (int i = 0 ; i < [Link] ; i++)
{
if(x[i] < 0)
{
count++;
}
}
return count;
}

/* Overloaded method to count -ve numbers in the array */


public static int countnegative(double x[])
{
int count = 0;
for (int i = 0 ; i < [Link] ; i++)
{
if(x[i] < 0)
{
count++;
}
}
return count;
}

public static void main(String[] args)


{
int array_integer[] = new int[10];
int array_double[] = new int[10];
int count;
[Link]("Enter 10 numbers of the integer array ");
inputarray(array_integer);
[Link]("Display the array ");
displayarray(array_integer);
count = countnegative(array_integer);
[Link]("Count of -ve numbers in the array is " + count);

[Link]("Enter 10 numbers of the double array ");


inputarray(array_integer);
[Link]("Display the array ");

57
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

displayarray(array_integer);
count = countnegative(array_integer);
[Link]("Count of -ve numbers in the array is " + count);
}
}

Using the above logic now attempt the following questions


Do not use methods on these two programs
1. Enter an array of 5 elements. Count the number of even numbers
2. Enter an array of 5 elements count the characters of vowels note vowels = {a, e, i , o , u}

Now merge these two programs to a single program using methods with the following methods

a) Inputarray : This method is overloaded such it can take an array of either integers or characters
b) Displayarray: This method is overloaded such it can display either integers or characters
c) Count: This is an overloaded method that can take an input and implement count of even and odd numbers
Another overloaded method can take a character array as input and count the number of vowels. This method
returns the count to the calling program.
d) Write a main method to invoke these methods.

Also refer to the array problems in this notes and solve them yourself

Take your exercise questions and attempt atleast 5 questions don’t forget to write the VDT for each of them

58
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

Class 10 computer assignments from Lawrence school

Fibonacci series
A Fibonacci series is a series where the next number is obtained by taking the sum of the two previous numbers

Example if the first two numbers are 0 , 1 then the next number is 0+1 = 1

The series will look like this { 0, 1, 0+1=1, 1+1=2, 2+1=3, 3+2=5, 5+3=8 …} or {0, 1, 1, 2, 3, 5, 8, 13, … upto n terms}

/**
* Write a description of class Fibonacci here.
*
* @author (your name)
* @version (a version number or a date)
*/
import [Link].*;

class Fibonacci
{
public static void main()
{
int previous_number = 0;
int current_number = 1;
int next_number = 0;
[Link]("Enter the number of terms required in the fib series");
Scanner sc = new Scanner([Link]);
int n = [Link]();
[Link]("Print the first 2 numbers ");
[Link](previous_number + " , " + current_number + " , " );

for(int i = 3 ; i <= n; i++)


{
next_number = previous_number+ current_number;
[Link](next_number + " , " );
previous_number = current_number;
current_number = next_number;
}
}
}

Pure Even
A number is said to be a Pure even if all the digits in the number are even numbers

Example 2468 is a pure even ; 2469 is not a pure even since 9 is not even

/**
* Write a description of class Fibonacci here.
*
* @author (your name)
* @version (a version number or a date)
*/

59
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

import [Link].*;

class PureEven
{
public static void main()
{
[Link]("Enter the number");
Scanner sc = new Scanner([Link]);
int n = [Link]();
[Link]("Given number" + n );
// We will start with the assumption that the given number is a pure even
// if we find one of number then we will set flag to false and conclude
// that the number is not a pure even

Boolean flag = true;


int digit ;
while(n >0)
{
digit = n - n/10*10 ;
if(digit %2 != 0)
{
// Digit is odd hence number is not pure even
flag = false;
break;
}
// Extract the next digit
n = n/10;
}
if(flag == true)
{
[Link]("is Pure Even");
}
else
{
[Link](" is NOT Pure Even");
}
}
}

Assignment 10 program
Define two arrays an array of cities and their temperatures.

Write a program to search for a given city and print its tempetature if city is not found it should print city
not found

/**
* Write a description of class Fibonacci here.
*
* @author (your name)
* @version (a version number or a date)
*/
import [Link].*;
class Weather
{
public String city[] = new String[3];
public double temperature[] = new double [3];
// This method accepts the city name and temperature from the user

60
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

void accept_city_temperature()
{
Scanner sc = new Scanner([Link]);
for(int i = 0 ; i < [Link]; i++)
{
[Link]("Enter the city name");
city[i] = [Link]();
}
for(int i = 0 ; i < [Link]; i++)
{
[Link]("Enter the city Temperature");
temperature[i] = [Link]();
}

}
int search_city(String city)
{
int index = -1;
city = [Link]();
for(int i = 0 ; i < [Link]; i++)
{

if([Link]([Link][i].toLowerCase())== true)
{
index = i;
break;
}
}
return index;
}
}

/**
* Write a description of class mainmethod here.
*
* @author (your name)
* @version (a version number or a date)
*/
import [Link].*;

public class mainmethod


{
public static void main()
{
Weather obj = new Weather();
Scanner sc = new Scanner([Link]);
String city_tosearch;
int index;
obj.accept_city_temperature();
[Link]("Enter the city name");
city_tosearch = [Link]();
index = obj.search_city(city_tosearch);
if(index == -1)
{
[Link]("City not found");
}
else
{
[Link]("City" + [Link][index] + " Temperature" +
[Link][index]);

61
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620

}
}
}

62

You might also like