Java Programming Basics and Examples
Java Programming Basics and Examples
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);
}
3
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
import [Link].*;
class Factorial {
4
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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
}
}
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;
}
// 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");
7
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
8
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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");
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");
}
}
}
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;
11
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" + 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
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
Example :
array: [ 8,7,5,2]
14
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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
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,
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
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;
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
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!");
}
}
import [Link].*;
import [Link];
class Employee
{
private int age;
private int id;
protected int salary;
public String name;
22
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");
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");
}
}
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
import [Link].*;
import [Link];
class Employee
{
private int age;
private int id;
protected int salary;
public String name;
24
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");
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)
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
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;
import [Link].*;
import [Link];
class Employee
{
private int age;
private int id;
protected int salary;
public String name;
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
28
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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
31
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
32
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
Table 6 Chapter 5 User defined method Impure function – Arrays – Call by reference
33
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
}
}
Original Array:
12345
Modified Array:
2 4 6 8 10
// [Link]
public class MainClass {
public static void main(String[] args) {
// Accessing public class
PublicAccessExample publicExample = new PublicAccessExample();
[Link]("Public variable: " + [Link]);
[Link]();
34
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
public PublicAccessExample() {
[Link]("Public constructor called");
}
// [Link]
class ProtectedAccessExample {
protected int protectedVariable = 20;
protected ProtectedAccessExample() {
[Link]("Protected constructor 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
Chapter 7 Constructors
Table 8 Chapter 7 Example of default constructor / Non parameterized
// Parameterized constructor
public Car(String make, String model, int year) {
[Link] = make;
[Link] = model;
[Link] = year;
}
36
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
// 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 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
}
}
// 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;
}
38
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
// Base class
class Animal {
void eat() {
[Link]("Animal is eating");
}
}
39
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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;
40
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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) ?
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
Answer Key : Polymorphism because its given in the question that each dog eats different types of food
and quantity.
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;
42
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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.
43
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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
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;
46
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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
48
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
49
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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
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 {
53
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
Member methods
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;
}
56
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
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);
}
}
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
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 + " , " );
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
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].*;
61
Vikas Learning center.
HSR Layout Sector 7 Bangalore 560102
Ph +91 86181 54620
}
}
}
62