0% found this document useful (0 votes)
19 views

Core JAVA 1 - Content

Uploaded by

roman55reigns88
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)
19 views

Core JAVA 1 - Content

Uploaded by

roman55reigns88
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
You are on page 1/ 59

Practical - 1

Aim: Study of JAVA and write a program in JAVA to display a Message.

Introduction: Java is a general-purpose and object-oriented computer programming


language, specifically designed to have as few implementation dependencies as possible. It is
intended to let application developers "write once, run anywhere (WORA)”, meaning that code
that runs on one platform does not need to be recompiled to run on another. Java applications are
typically compiled to byte code (class file) that can run on any Java virtual machine (JVM)
regardless of computer architecture. Java is one of the most popular programming languages in
use, particularly for client-server web applications.
Java was originally developed by James Gosling at Sun Microsystems, now merged with Oracle
and released in 1995 as a core component of Sun Microsystems' Java platform. The language
derives much of its syntax from C and C++, but it has fewer low-level facilities than either of
them.
The original and reference implementation Java compilers, virtual machines, and class
libraries were developed by Sun from 1991 and first released in 1995. As of May 2007, in
compliance with the specifications of the Java Community Process, Sun relicensed most of its
Java technologies under the GNU General Public License.

PRINCIPLES
There were five primary goals in the creation of the Java language:

1. It should be "simple, object-oriented and familiar"


2. It should be "robust and secure"
3. It should be "architecture-neutral and portable"
4. It should execute with "high performance"
5. It should be "interpreted, threaded, and dynamic"

PLATFORM INDEPENDENT
One characteristic of Java is portability, which means that computer programs written in the Java
language must run similarly on any hardware / operating-system platform. This is achieved by
compiling the Java language code to an intermediate representation called Java byte code,
instead of directly to platform-specific machine code. Java byte code instructions are analogous
to machine code, but they are intended to be interpreted by a virtual machine (VM) written
specifically for the host hardware.
End-users commonly use a Java Runtime Environment (JRE) installed on their own machine for
standalone Java applications, or in a Web browser for Java applets. Standardized libraries
provide a generic way to access host-specific features such as graphics, threading,
and networking.
A major benefit of using byte code is porting. However, the overhead of interpretation means
that interpreted programs almost always run more slowly than programs compiled to native
executables would. Just-in-Time (JIT) compilers were introduced from an early stage that
compiles byte codes to machine code during runtime.

The various application areas of JAVA (Editions) include:


* Java Platform Micro Edition (Java ME) — Targeting environments with limited resources.

* Java Platform Standard Edition (Java SE) — Targeting workstation environments.

* Java Platform Enterprise Edition (Java EE) — Targeting large distributed enterprise or
Internet environments.

JDK

The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java
EE or Java ME platforms released by Oracle Corporation in the form of a binary product aimed
at Java developers on Solaris, Linux, Mac OS X or Windows. Since the introduction
of Java platform, it has been by far the most widely used Software Development Kit (SDK). On
17 November 2006, Sun announced that it would be released under the GNU General Public
License (GPL), thus making it free software.

The JDK has as its primary components a collection of programming tools, including:

 appletviewer – This tool can be used to run and debug Java applets without a web browser
 java – The loader for Java applications. This tool is an interpreter and can interpret the class
files generated by the javac compiler.
 javac – The Java compiler, which converts source code into Java byte code
 javadoc – The documentation generator, which automatically generates documentation
from source code comments
 jar – The archiver, which packages related class libraries into a single JAR file. This tool
also helps manage JAR files.
 jdb – The debugger
JRE

The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java
Development Kit (JDK), a set of programming tools for developing Java applications. The Java
Runtime Environment provides the minimum requirements for executing a Java application; it
consists of the Java Virtual Machine (JVM), core classes, and supporting files.

JVM

A Java virtual machine (JVM) is a virtual machine that can execute Java byte code. It is the code
execution component of the Java platform. According to SUN Microsystems, there are over 5.5
billion JVM-enabled devices.

Program:

class Message
{
public static void main(String[] args)
{
System.out.println("\n HELLO WORLD");
}
}

Output:

HELLO WORLD
Practical - 2
Aim: Write a program in JAVA to initialize 3 variables, compute their sum and display the
result.

Tokens: The smallest unit of a JAVA program is called a Token. Tokens are indivisible. Tokens
include Keywords, Identifiers, Literals, Operators, Separators and Comments.

Keywords: These are pre-defined words or reserved words; each keyword has a specific
meaning and a specific purpose. They are always written in lower case. They can only be used
for the purpose, for which they are already defined; we can‟t redefine their purpose, nor can they
be used as names of identifiers or variables.

Some common keywords of JAVA include boolean, class, catch, extends, final, finally,
implements, import, interface, new, package, private, protected, public, return, static, super,
synchronized, this, throw, throws, assert, etc.

Operators: They are the special symbols used to perform operations. JAVA support Arithmetic
operators (+, -, *, / and %), Assignment operators (=, +=, -=, *=, /= and %=), Relational
operators (<, <=, >, >=, == and !=), Unary operators (-, ++ and --), Logical operators (&&, || and
!), Bitwise operators (&, |, ^ and ~), Shift operators (<< and >>) and Ternary operator (condition
? TRUE Statement : FALSE Statement;).

Expressions: The combination of Tokens in a meaningful form forms an Expression or a


Statement. Common expressions in a program include Arithmetic expressions, Relational
expressions, Variable Declaration expression, Variable Initialization expression, Input / Output
expression, etc.
Program:

class SimpleSum
{
public static void main(String[] args)
{
int a = 5, b = 7, c = 8, s = 0;
s = a + b + c;
System.out.println(“Sum of 3 Numbers is : “ + s);
}
}

Output:

Sum of 3 Numbers is : 20
Practical - 3
Aim: Write a program in JAVA to compute average of 3 numbers and perform necessary type
casting.

Type Casting: It is a technique that converts a data type to another, both automatically and
manually. The automatic conversion is done implicitly by the Compiler; the manual conversion
is done by the Programmer. The type casting done by the Compiler is called Implicit Type
Casting; the type casting done by the programmer is called Explicit Type Casting.

Type Casting is further categorized as Narrowing and Widening. The technique of converting a
higher data type into a lower data type is called Narrowing. Alternatively, the technique of
converting a lower data type into a higher data type is called Widening.

Command Line Arguments: It represents the input or data passed at the time of running a
JAVA program. The data passed from the Console is received by the JAVA program as input
through „args[]‟ of „main()‟.

Program:

class TypeCastCommandLine
{
public static void main(String[] args)
{
int a = 0, b = 0, c = 0, s = 0;
double avg = 0.0;

a = Integer.parseInt(args[0]); // Type Casting – String is converted to INT


b = Integer.parseInt(args[1]); // Type Casting – String is converted to INT
c = Integer.parseInt(args[2]); // Type Casting – String is converted to INT

s = a + b + c;
avg = s / 3.0;
// Type Casting – Taking DOUBLE Denominator to get DOUBLE Result
System.out.println(“Average of Three Numbers is : ” + avg);
}
}

Output:

Location_Of_JAVA_File>javac TypeCastCommandLine.java

Location_Of_JAVA_File>java TypeCastCommandLine 5 7 8

Average of Three Numbers is : 6.666666666666667


Practical - 4
Aim: Write a program in JAVA to take 3 numbers as Input from User, compute Average and
display the result.

Scanner: There are three main components of a program, namely Input, Process and Output. A
Program is a way to interact with Computer; it represents a task to perform. Scanner class is a
pre-defined class in JAVA, used to take Input from User. Scanner class is defined in the „util‟
package.

Built-In Library of JAVA is available in form of Packages; a Package comprise of Classes and
Sub-Packages. A Class contains multiple Methods used to carry out the specified operations. To
use a Class, first we need to call or import the Package in which it is specified. A Built-In
Package of JAVA can be called / imported in the Program, as:

import java.Package_Name.*;

// For using all Classes of the Package imported

import java.util.*;

import java.Package_Name.Class_Name;

// For using the specified Class of the specified Package in our Program

import java.util.Scanner;

To use a Class, first we need to create its Object and then carry out the operations by calling the
Methods of the Class using Member Selection Operator (.), as:

Class_Name Object_Name = new Constructor(Parameters_If_Applicable);

// Creating an Object of a Class

Scanner scan = new Scanner(System.in);


Object_Name.Method_Name();

// To Call a Method of a Class using Object

scan.nextInt();

Program:

import java.util.*;

class ScannerExample
{
public static void main(String[] args)
{
int a = 0, b = 0, c = 0, s = 0;
double avg = 0.0;
Scanner scan = new Scanner(System.in);

System.out.println("Enter Three Integers : ");


a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();

s = a + b + c;
avg = s / 3.0;
System.out.println("Average of Three Numbers is : " + avg);
}
}

Output:

Enter Three Integers :


25
50
100

Average of Three Numbers is : 58.333333333333333


Practical - 5
Aim: Write a program in JAVA to take a number as Input from User and check whether it is 0,
1, Even or Odd.

Branching Logic: Conditions are used to implement Branching Logic in Programming.


Conditions are the expressions or statements, having binary output, i. e., either TRUE or FALSE;
however, some conditions have more than two branches as their outcome. There are some
statements in a Program that will execute only when the specified condition is TRUE; if
condition is FALSE, these statements will not execute at all. With Programs having Linear or
Sequential Flow, all the statements will execute in the order in which they are written. However,
with Branching Logic, there are some statements whose execution depends on the condition.
Sometimes, these statements will execute and sometimes not. So, a program having branching
implemented in it will have at least two possible flows.

There are two common ways of implementing Branching Logic in a Program, namely IF ELSE
Statements and SWITCH CASE Statement. IF ELSE Statements are further categorized into 4
types, as Simple IF, IF ELSE, IF ELSE Ladder and Nested Conditions.
Simple IF: It is used when we need to handle only one state of condition in the program, i. e.,
only TRUE state. Typically, the condition to test is associated with IF. The statements specified
in the IF Block will execute, if the condition associated with IF is TRUE; otherwise, the
statements will not execute. The syntax to implement Simple IF is:

if(condition) { Statements of IF Block; // Execute when condition is TRUE }

IF ELSE: It is typically implemented, when we need to handle both the outcomes of the
condition, i. e., TRUE as well as FALSE. It comprises two blocks, namely IF Block with which
the condition is associated and an ELSE Block. The statements of IF Block will execute, when
the condition associated is TRUE; if the condition associated with IF is FALSE, the statements
of ELSE Block will execute. In every case, either statements of IF Block will execute or
statements of ELSE Block will execute, but not both. The syntax to implement IF ELSE is:

if(condition) { Statements of IF Block; // Execute when condition is TRUE }

else { Statements of ELSE Block; // Execute when condition is FALSE }

IF ELSE Ladder: It is also known as IF – ELSE IF – ELSE. It is mainly implemented when we


need to check multiple conditions, one after another; that‟s why called IF ELSE Ladder. The
next condition will be checked, only if the current condition is FALSE. It is mostly used with
conditions having more than 2 possible outcomes. Each ELSE IF Block acts as an ELSE Block
for the previous condition and IF Block for the current condition. ELSE specified at the end will
execute, if none of the condition is TRUE; otherwise the IF / ELSE IF Block will execute whose
associated condition is TRUE. The syntax for IF ELSE Ladder is:

if(condition_1) { Statements 1; // Execute when condition_1 is TRUE }

else if(condition_2) {
Statements 2; // Execute when condition_1 is FALSE and condition_2 is TRUE }

else if(condition_3) { Statements 3;


// Execute when condition_1 and condition_2 are FALSE; condition_3 is TRUE }

else { Statements 4; // Execute when all conditions mentioned above are FALSE }
Nested Condition: Nesting in programming means implementing the same programming
concept in that concept, i. e., condition inside another condition is called Nested Condition, loop
inside another loop is called Nested Loop, method inside another method is called Nested
Method, class inside another class is called Nested Class, etc.

If a condition is specified another condition, i. e., if another condition is tested as part of the
outcome of a condition, then it is called Nested Condition. It is implemented using Nested IF
ELSE as:

if(external_condition) {
if(internal_condition_1) {
Statements 1; // Execute when both external_condition and internal_condition_1 are TRUE
}

else {
Statements 2;
// Execute when external_condition is TRUE and internal_condition_1 is FALSE
} }

else {
if(internal_condition_2) {
Statements 3;
// Execute when external_condition is FALSE and internal_condition_2 is TRUE
}

else {
Statements 4; // Execute when both external_condition and internal_condition_2 are FALSE
} }

Program:

import java.util.Scanner;

class EvenOdd01 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
System.out.println("Enter a Positive Integer (>= 0) : ");
num = scan.nextInt();
if(num == 0)
System.out.println("Number is 0 !");

else if(num == 1)
System.out.println("Number is 1 !");

else if((num % 2) == 0)
System.out.println("Number is Even !");

else
System.out.println("Number is Odd !");
}
}

Output:

Run 1
Enter a Positive Integer (>= 0) : 5
Number is Odd !

Run 2
Enter a Positive Integer (>= 0) : 8
Number is Even !

Run 3
Enter a Positive Integer (>= 0) : 1
Number is 1 !

Run 4
Enter a Positive Integer (>= 0) : 0
Number is 0 !
Practical - 6
Aim: Write a program in JAVA to implement simple arithmetic calculator using SWITCH
CASE.

SWITCH CASE: It is second technique to implement Branching in a program. It is an alternate


to IF ELSE Ladder. It is used with conditions having multiple possible outcomes. It comprises of
two components; first CASE Blocks, one for TRUE outcome of each condition and a SWITCH
Block that comprises all CASE Blocks. In case, all the conditions are FALSE, a DEFAULT
Block is specified after all CASE Blocks.

There is a drawback with SWITCH CASE that in case, if a CASE Block is executed after its
condition is TRUE, all CASE Blocks specified after it will also execute. This drawback can be
overcomed by using a BREAK Statement at the end of each CASE Block. BREAK terminates
the execution of the current Block (SWITCH or Loop). The execution of SWITCH CASE
depends on the “choice”, passed as an argument in the SWITCH Block. The syntax to implement
SWITCH CASE is:

switch(choice) {
case 1: { Statements 1; break; } // Execute when “choice” passed is 1
case 2: { Statements 2; break; } // Execute when “choice” passed is 2
case 3: { Statements 3; break; } // Execute when “choice” passed is 3
default: { Statements 4; break; }
// Execute when “choice” is any number except 1, 2 or 3
}

Program:

import java.util.*;

class SwitchCaseCalc {
public static void main(String[] args) {
int x = 0, y = 0, c = 0;
Scanner scan = new Scanner(System.in);

System.out.println("Enter 2 Numbers : ");


x = scan.nextInt(); y = scan.nextInt();
System.out.println("\n 1 for ADD \n 2 for SUB \n 3 for MUL \n 4 for DIV \n 5 for MOD");
System.out.println("Enter your Choice : ");
c = scan.nextInt();

switch(c) {
case 1: { int r = x + y; System.out.println("SUM is : " + r); break; }

case 2: { int r = x - y; System.out.println("DIFFERENCE is : " + r); break; }

case 3: { int r = x * y; System.out.println("PRODUCT is : " + r); break; }

case 4: { float r = (float) x / y; System.out.println("DIVISION is : " + r); break; }

case 5: { int r = x % y; System.out.println("REMAINDER is : " + r); break; }

default:
System.out.println("INVALID CHOICE \n PLEASE SELECT A VALID OPERATION");
}

} }

Output:

Run 1

Enter 2 Numbers : 12 7

1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 1

SUM is : 19

Run 2

Enter 2 Numbers : 12 5

1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 2

DIFFERENCE is : 7
Run 3

Enter 2 Numbers : 7 5

1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 3

PRODUCT is : 35

Run 4

Enter 2 Numbers : 25 7

1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 4

DIVISION is : 3.5714285

Run 5

Enter 2 Numbers : 97 11

1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 5

REMAINDER is : 9

Run 6

Enter 2 Numbers : 25 5

1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 6

INVALID CHOICE
PLEASE SELECT A VALID OPERATION
Practical - 7
Aim: Write a program in JAVA to take a number as Input from User and print its Table.

Iteration: Iteration in programming means to perform same operation repeatedly, one after
another, at a specific point in a program. Iteration is a synonym for repetition in programming. It
is mainly implemented using Loops or Looping structures.

Loop: It is a programming concept used to achieve Iteration or to execute a statement or set of


statements multiple times or repeatedly. It is based on conditions and a variable, most of the
times. Three details about looping variable are specified for execution of a loop; first, the initial
value; second, the boundary value or ending value or condition that will be used to terminate the
loop, if FALSE and third, the update in value of looping variable after each iteration to avoid
infinite loop.

Loops are broadly categorized into 2 types, as Entry Controlled Loops and Exit Controlled
Loops. The looping structure in which first, the condition is checked; if TRUE, statements are
executed; otherwise not, are called Entry Controlled Loops. The statements will never execute, if
condition is FALSE. WHILE Loop and FOR Loop are examples of Entry Controlled Loops.

The loops in which first the statements are executed and then the condition is checked are called
Exit Controlled Loops. In this, the statements will execute once, even when the condition is
FALSE. DO WHILE Loop falls in this category of Loops.

Break: It is a statement used to terminate a Loop or any other programming structure; before
reaching the boundary, based on another condition.
Continue: It is a statement used to skip some iterations of loop, based on some conditions.

The syntax for Looping Structures are:

WHILE Loop

initiailize loop_var;

while(condition) { Statements to execute repeatedly; update loop_var; }

FOR Loop

for(initialize loop_var; condition; update loop_var) {


Statements to execute repeatedly;
}

DO WHILE

initialize loop_var;

do { Statements to execute repeatedly; update loop_var; } while(condition);

BREAK

for(initialize loop_var; condition; update loop_var) {


if(break_condition) break;

Statements to execute repeatedly; }

CONTINUE

initialize loop_var;

while(condition) {
if(continue_condition) continue;

Statements to execute repeatedly;


update loop_var; }
Program:

import java.util.Scanner;

class Table {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
System.out.println("Enter a Positive Integer (> 0) : ");
num = scan.nextInt();

for(int i = 1; i <= 10; i++) {


int t = num * i;
System.out.println(num + " * " + i + " = " + t);
}

} }

Output:

Enter a Positive Integer (> 0) : 8

8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
Practical - 8
Aim: Write a program in JAVA to display the „*‟ Pyramid of order „n‟ shown below:

*
* *
* * *
* * * *
* * * * *

Nested Loop: A loop implemented inside another loop is called a Nested Loop. It is mainly used
to draw 2 D structures, patterns, etc or to work with 2 D arrays, usually Matrices. The syntax for
Nested Loop is:

for(initialize loop_var_1; condition_1; update loop_var_1) {


for(initialize loop_var_2; condition_2; update loop_var_2) {
Statements;
} }

If the external loop will execute „n‟ times and internal loop will execute „m‟ times; then
„Statements‟ will execute „n * m‟ times for a Nested Loop. For example, if external loop
executes 5 times and internal loop executes 10 times; then in total, there will be „5 * 10 = 50‟
iterations of this Nested Loop.

Program:

import java.util.*;

class NestedLoopPyramid
{
public static void main(String[] args)
{
int n = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the Size of * Pyramid to display : ");
n = s.nextInt();
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if((i + j) >= (n - 1))
System.out.print("*");

else
System.out.print(" ");

System.out.print(" ");
}

System.out.println();
}

}
}

Output:

Enter the Size of * Pyramid to display : 7

* *

* * *

* * * *

* * * * *

* * * * * *

* * * * * * *
Practical - 9
Aim: Write a program in JAVA to initialize a 1 D Array through User Input, compute sum and
display the result.

Array: An Array is a homogeneous collection of elements that reside at contiguous memory


locations. A homogeneous collection means all elements of an Array must be of same type, i. e.,
all Integers or all Floats or all Doubles. It allows you to store multiple elements having same
name but different index.

Compared to C++, where an Array must have static / constant size, unless Pointers are used for
dynamic memory allocation, the standard implementation of Array in JAVA allows you to keep
size of Array either constant or variable; the only concern is that the variable representing the
size of Array must be initialized before declaring the Array.

Elements are referred using Indices in an Array; by default, the index of first element is 0, the
index of second element is 1, index of third element is 2 and so on. An Array is a linear data
structure that allows random access to all elements using index.

The common operations to perform on an Array include insertion, deletion, update, traversing,
search and sort. Insertion and Deletion in Array can be performed at beginning, end or at any
random position / index. Arrays are mainly classified as 1 Dimensional Arrays and Multi
Dimensional Arrays.

1 D Array: The simplest implementation of Arrays is 1 D Array. In this, each element is referred
using a single index. A 1 D Array is declared as:

Data_Type[] Name_Of_Array = new Data_Type[Size];

int[] num = new int[10];

To declare an Array, we must specify the Data Type and Size, as represented in the above
statement. Here, „num‟ is an Array of „int‟ type having size of „10‟. „[]‟ is used to represent an
Array and each element of the Array is referred as „num[x]‟, where „x‟ is the index of the Array,
whose element is to be accessed.
A variable sized Array in JAVA is declared as:

int[] num = new int[Size];

Here, „num‟ is an Array comprising „Size‟ number of Integers; however, to pass „Size‟, we must
initialize it before specifying it in the Array.

Program:

import java.util.*;

class ArrayExample {
public static void main(String[] args) {
int n = 0; Scanner sc = new Scanner(System.in);

System.out.println("Enter the Size of Array : ");


n = sc.nextInt();

int[] num = new int[n]; int i, sum = 0;

System.out.println("Enter Elements of Array : ");


for(i = 0; i < n; i++)
num[i] = sc.nextInt();

sum = num[0];
for(i = 1; i < n; i++) { sum = sum + num[i]; }

System.out.println("\n Sum of Array Elements is : " + sum);


} }

Output:

Enter the Size of Array : 8

Enter Elements of Array :


2 3 5 7 8 16 20 12

Sum of Array Elements is : 73


Practical - 10
Aim: Write a program in JAVA to perform addition and multiplication of two matrices.

2 D Array: An Array whose element is referred using 2 indices is called a 2 D Array. 2 D


Arrays are mainly implemented in program to perform operations related to Matrices, like Matrix
Addition, Subtraction and Multiplication. A 2 D Array in JAVA is declared as:

Data_Type[][] Array_Name = new Data_Type[Size1][Size2];

int[][] m = new int[5][3];

In the above example, a 2 D Array „m‟ is declared. Consider, „m‟ as a Matrix having number of
rows, equal to Size1, i. e., 5 and number of columns as Size2, i. e., 3. Depending on the
requirement, both sizes can be same or different.

For 2 D Array also, the memory allocation must be contiguous. If the sizes of 2 D Array are
„Size1‟ and „Size2‟, then it will have a total of „Size1 * Size2‟ elements. For example, in „m‟,
there will be „5 * 3 = 15‟ elements.

Program:

import java.util.Scanner;

class MatrixOp {
public static void main(String[] args) {
int[][] a = new int[3][3];
int[][] b = new int[3][3];
int[][] s = new int[3][3];
int[][] p = new int[3][3];

Scanner sc = new Scanner(System.in);


System.out.println("Enter Elements of First 3X3 Matrix : ");
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
a[i][j] = sc.nextInt();
System.out.println("Enter Elements of Second 3X3 Matrix : ");
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
b[i][j] = sc.nextInt();

System.out.println("First 3X3 Matrix is : \n");


for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
System.out.print(a[i][j]);
System.out.print(" "); }

System.out.println(); }

System.out.println("Second 3X3 Matrix is : \n");


for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
System.out.print(b[i][j]);
System.out.print(" "); }

System.out.println(); }

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


for(int j = 0; j < 3; j++)
s[i][j] = a[i][j] + b[i][j];

System.out.println("SUM of Matrices is : \n");


for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
System.out.print(s[i][j]);
System.out.print(" "); }

System.out.println(); }

for(int i = 0; i < 3; i++) {


for(int j = 0; j < 3; j++) {
p[i][j] = 0;

for(int k = 0; k < 3; k++) {


p[i][j] = p[i][j] + (a[i][k] * b[k][j]); }
} }
System.out.println("PRODUCT of Matrices is : \n");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
System.out.print(p[i][j]);
System.out.print(" "); }

System.out.println(); }
} }

Output:

Enter Elements of First 3X3 Matrix:


1 2 3
4 5 6
7 8 9

Enter Elements of Second 3X3 Matrix:


1 1 1
1 1 1
1 1 1

First 3X3 Matrix is:


1 2 3
4 5 6
7 8 9

Second 3X3 Matrix is:


1 1 1
1 1 1
1 1 1

SUM of Matrices is:


2 3 4
5 6 7
8 9 10

PRODUCT of Matrices is:


6 6 6
15 15 15
24 24 24
Practical - 11
Aim: Define a class Student with Data Members [String name, int age and float cgpa] and
Member Methods [getData() and showData() for taking Input and displaying the Output
respectively]. Initialize an Object of this class and access the Member Methods. Implement this
scenario in JAVA.

Object Oriented Programming: Object Oriented Programming (OOP) is a programming


paradigm, based on the concept of „Objects‟ that contain Data and Code; Data in form of
Attributes and Code in form of Methods. The Methods associated with Objects can access and
modify the values of the associated Attributes. Objects interact with each other through some
Message Passing mechanism, often Method Calls. Most of the Programming Languages based
on the principles of OOP are Class based, i. e., Objects are instance of Classes that determine
their type.

The benefits of OOP over Procedure Oriented Programming (POP) include Reusability,
Extensibility, Modifiability, etc. POP focuses on Procedures and Data is globally accessible; in
contrast, OOP focuses on Objects and Data. In OOP, access to Data is restricted; this is possible
by using the Access Specifiers. POP follows Top Down approach, while OOP follows Bottom
Up approach. Modularity using Classes forms the basis of Bottom Up approach in OOP.

The common principles of OOP include Class, Objects, Abstraction, Encapsulation, Data Hiding,
Dynamic Binding, Polymorphism, Inheritance, Message Passing or Object Interaction. The
common programming languages that follow OOP paradigm include C++, JAVA, PYTHON,
C#, Visual Basic, R, Kotlin, Swift, LISP, etc.

Class: A Class is a blue-print that specifies the creation of Objects. It is a logical entity that can
be considered as collection of Objects. “class” Keyword is used to specify a Class in JAVA. It
comprises of Data Members (Attributes) and Member Methods (Code); all Objects of this Class
have a specific value for Attributes and can invoke all associated Methods.

The access to Class Members can be restricted using Access Specifiers. JAVA supports 4 Access
Specifiers, namely Private, Protected, Package and Public. By default, the access is Package.

Object: It is a real world or run time entity. An Object is an instance of a Class. It consumes
Memory Space; in contrast, Class doesn‟t consume any Memory Space. Objects can interact with
each other. An entity that has State and Behavior is an Object.
Encapsulation: Binding of Data and Code together as a single unit is called Encapsulation.
Class promotes Encapsulation, as it contains Data (Attributes) and Methods (Code). It is the most
striking feature of Class.

Abstraction: The principle that allows showcasing only necessary functionality and hides the
implementation details is called Abstraction. Class implements Abstraction and encapsulates all
essential properties of the Object to be created. Objects perform the operations; however they do
not specify the implementation details.

Data Hiding: Due to Encapsulation, the Data Members of the class area accessible only to the
Member Methods defined in the Class. Normally, Member Methods are declared as Public, so
that they are accessible from outside the Class, but the Data Members are declared Private, so
that they are accessible only to Methods of the same Class. The Data Members of the Class are
not accessible to the outside world, due to restrictions imposed on them using Access Specifiers.
This concept is known as Data Hiding or Information Hiding, as Data Members are local to
Class.

Dynamic Binding: Binding refers to the Linking of a Procedure Call to the Code to be executed,
in response to that Call. Mostly, the Binding is Static, performed at Compile Time. However,
OOP supports Dynamic Binding also. Dynamic Binding means that the Code associated with a
given Procedure Call is unknown, until the time of the Call at Run Time. Dynamic Binding is
also known as Run Time Binding.

Polymorphism: The word „Polymorphism‟ is a Greek Word that means “Ability to take more
than one Form”. Objects are Polymorphic in nature; they behave differently in different
situations, just as Humans do. An operation may exhibit different behavior at different instances,
depending on the type of data used on that instance. In JAVA, Polymorphism is achieved using
Method Overloading and Method Overriding.

Inheritance: It is the most striking feature of OOP that promotes Reusability of Code. It is the
process in which Object of a Class acquire properties of Object of another Class. Inheritance
creates a hierarchical relationship among Classes. It is a process in which a Derived Class
exhibits the characteristics or properties of Base Class.
The Class whose properties are being reused or derived is called Base Class or Parent Class or
Super Class. The Class that reuses the properties of Base Class is called Derived Class or Sub
Class or Child Class. The Child Class inherits the properties of the Base Class.

Object Interaction: An Object Oriented Program consists of a set of Objects that communicate
with each other. Communication among Objects occur by sending and receiving Messages; just
as People pass Messages with one another using some Message Passing mechanism.
Traditionally, Method Calls are used to achieve communication among Objects, where Data to
share is passed as Arguments in the Method Call.

A Class in JAVA is defined as:

class CLASS_NAME {
private DATA_MEMBERS;
-----
public MEMBER_METHODS() {
Method Definition;
}
-----
}

An Object in JAVA is initialized as:

CLASS_NAME OBJECT_NAME = new CLASS_NAME(ARGUMENTS_IF_APPLICABLE);

Program:

import java.util.Scanner;

class ClassObject
{
private String name;
private int age;
private float cgpa;
Scanner scan;

public void getData()


{
scan = new Scanner(System.in);
System.out.println("Enter Your Name : ");
name = scan.nextLine();
System.out.println("Enter Your Age : ");
age = scan.nextInt();
System.out.println("Enter Your CGPA : ");
cgpa = scan.nextFloat();
}

public void showData()


{
System.out.println("Your Name is : " + name);
System.out.println("Your Age is : " + age);
System.out.println("Your CGPA is : " + cgpa);
}

public static void main(String[] args)


{
ClassObject obj = new ClassObject();
obj.getData();
obj.showData();
}
}

Output:

Enter Your Name : Sachin R Tendulkar


Enter Your Age : 49
Enter Your CGPA : 8.98

Your Name is : Sachin R Tendulkar


Your Age is : 49
Your CGPA is : 8.98
Practical - 12
Aim: Define a class Compute with overloaded methods [void add(), int add(int, int) and double
add (double, double, double)]. Implement this in JAVA.

Method Overloading: It is a technique to achieve Polymorphism in JAVA. Method


Overloading is a technique to specify multiple Methods having the same name, but different
number or types of parameters in the same Class. If we have only one operation to perform in a
Class, Method Overloading increases the Readability of the program. Depending on the number
and type of arguments, the specific overloaded method will invoke to perform the operation.

There are two ways of implementing Method Overloading, as:

By changing the number of Arguments: All overloaded methods must have different number
of arguments, if all arguments are of the same data type.

By changing the data type: If the number of arguments in all overloaded methods is same, their
type must be different. No two overloaded methods can have same sequence of data types in 2
definitions.

Simply by changing the Return Type of the Methods, it is not possible to implement Method
Overloading. This is because it results in Ambiguity.

Program:

import java.util.*;

class MethodOverload {
public void add() {
Scanner sc = new Scanner(System.in);
int n1 = 0, n2 = 0, n3 = 0, sum = 0;

System.out.println("Enter 3 Integers : ");


n1 = sc.nextInt();
n2 = sc.nextInt();
n3 = sc.nextInt();

sum = n1 + n2 + n3;
System.out.println("SUM of 3 Numbers by Overloaded Method 1 is : " + sum); }

public void add(int x, int y) {


int temp = x + y;
System.out.println("SUM of 3 Numbers by Overloaded Method 2 is : " + temp); }

public void add(double a, double b, double c) {


double temp = a + b + c;
System.out.println("SUM of 3 Numbers by Overloaded Method 3 is : " + temp); }

public static void main(String[] args) {


int arg1 = 0, arg2 = 0;
double par1 = 0.0, par2 = 0.0, par3 = 0.0;
Scanner scmain = new Scanner(System.in);

System.out.println("Enter 2 Integers : ");


arg1 = scmain.nextInt();
arg2 = scmain.nextInt();

System.out.println("Enter 3 Floating Point Numbers : ");


par1 = scmain.nextDouble();
par2 = scmain.nextDouble();
par3 = scmain.nextDouble();

MethodOverload obj = new MethodOverload();


obj.add();
obj.add(arg1, arg2);
obj.add(par1, par2, par3);
} }

Output:

Enter 2 Integers : 25 34
Enter 3 Floating Point Numbers : 4.567 3.444 12.876
Enter 3 Integers : 25 50 100

SUM of 3 Numbers by Overloaded Method 1 is : 175


SUM of 2 Numbers by Overloaded Method 2 is : 59
SUM of 3 Numbers by Overloaded Method 3 is : 20.887
Practical - 13
Aim: Define a class Student with Data Members [String name, int age and float cgpa] and
Member Method [showData() for displaying the Output respectively]. Define a Parameterized
Constructor to initialize the Data Members through User Input. Initialize an Object of this class
and access the Member Methods. Implement this scenario in JAVA.

Constructor: A Constructor is a block of code, similar to a Method in JAVA. It is called when


an instance of a Class is created. When the Constructor is called, Memory for an Object is
created. It is a special method used to initialize an Object. Every time, an Object is created using
“new” Keyword, one Constructor of the Class is called. If there is no Constructor defined in a
Class, the Default Constructor will be automatically provided by the JAVA Compiler for
initializing the Object. It is called Constructor because it constructs the values at the time of
Object creation. “finalize()” perform clean-up activities, just like Destructor in C++.

Properties of Constructor:

~ It must have the same name as the name of the Class.


~ It doesn‟t have any Return Type; not even VOID.
~ A JAVA Constructor can‟t be ABSTRACT, STATIC, FINAL or SYNCHRONIZED.
~ It is invoked automatically.

Mostly, a Constructor is specified as Public. There are 2 types of Constructors in JAVA, as:

Default: It doesn‟t have any argument list associated with it. It will assign same default values of
Attributes to all Objects. Although, you can write I/O statements in its body, to retrieve values
for different Attributes of Object from User.

Parameterized: It will accept parameters or arguments while invoking or calling. It will assign
the passed values to the Attributes of Objects.

There is no Copy Constructor in JAVA. However, there are 3 techniques for copying the values
of one Object to another, as:

~ By passing Constructor as an argument to another Constructor


~ By assigning the values of one Object to another
~ By using clone() of the Object Class
Program:

import java.util.Scanner;

class ParamConstructor {
private String name;
private int age;
private float cgpa;

public ParamConstructor(String nm, int ag, float cg) {


name = nm;
age = ag;
cgpa = cg; }

public void showData() {


System.out.println("Your Name is : " + name);
System.out.println("Your Age is : " + age);
System.out.println("Your CGPA is : " + cgpa); }

public static void main(String[] args) {


Scanner scan = new Scanner(System.in);
System.out.println("Enter Your Name : ");
String unm = scan.nextLine();
System.out.println("Enter Your Age : ");
int uag = scan.nextInt();
System.out.println("Enter Your CGPA : ");
float ucg = scan.nextFloat();

ParamConstructor obj = new ParamConstructor(unm, uag, ucg);


obj.showData();
} }

Output:

Enter Your Name : Sachin R Tendulkar


Enter Your Age : 49
Enter Your CGPA : 8.98

Your Name is : Sachin R Tendulkar


Your Age is : 49
Your CGPA is : 8.98
Practical - 14
Aim: Write a program to demonstrate the different String operations in JAVA.

String: JAVA String is an Object that represents a sequence of Characters. It can be considered
as an Array of Characters or a Character Array. String is a Class in JAVA; it is a part of “lang”
Package that is included in all JAVA programs by default, so there is no need to import it
explicitly, just like other Packages.

Strings are immutable; once created, they can‟t be modified or overridden. It provides Methods
for performing operations on Strings, like compare(), concat(), split(), length(), replace(), etc.

There are 2 ways of creating a String in JAVA, as:

By String Literal: In this approach, a value is assigned to a String Object, as:

String s_name = “VALUE”;

String s = “Hello India !”;

In this approach, JVM checks the “String Constant Pool” for existence of the String; if String
already exists there, a Reference to a Pooled Instance is returned. It means two Strings having
same value will have same reference in Pool. If String doesn‟t exist in the Pool, then only a new
String instance is created in the Pool. This results in efficient utilization of Memory.

By ‘new’ Keyword: In this approach, JVM creates a new String Object in Heap and the value
assigned to it will be placed in the Pool. The Object will always point to the Heap. It can be
implemented as:

String s_name = new String(“VALUE”);

String s = new String(“Hello India !”);


The common Methods provided by the String Class include:

METHOD NAME DESCRIPTION

char charAt(int index) It returns the Character at the specified index.


int length() It returns the Length of String.
String substring(int begId) It returns Substring, starting from „beginIndex‟.
String substring(int begId, int endId It returns Substring from „begId‟ to „endId – 1‟ indices.
~ It returns TRUE, if „cs‟ is in the String
boolean contains(CharSequence cs)
~ Otherwise it returns FALSE.
boolean isEmpty() It checks if String is Empty.
String concat(String str) It concatenates „str‟ with specified String.
It replaces all occurrences of „c_old‟ with „c_new‟ in
String replace(char c_old, char c_new)
given string.
It returns the Index / Position of specified Character in
int indexOf(int ch)
the String.
String toLowerCase() It returns the String with all Alphabets in Lower Case.
String toUpperCase() It returns the String with all Alphabets in Upper Case.
It removes all the SPACES at beginning and end of
String trim()
String.

Program:

import java.util.*;

class StringExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String instr = "";

System.out.println("Enter Input String : ");


instr = sc.nextLine();
System.out.println("Entered String is : " + instr);

int len = instr.length();


System.out.println("Length of Entered String is : " + len);
System.out.println("String in UPPER CASE is : " + instr.toUpperCase());
System.out.println("String in LOWER CASE is : " + instr.toLowerCase());
int index = 0;
System.out.println("Specify Index to access the Character : ");
index = sc.nextInt();
System.out.println("Character at Index " + index +" is : " + instr.charAt(index));

System.out.println("Specify the Character to look for : ");


String strch = sc.next();
char ch = strch.charAt(0);
System.out.println("Index of " + ch + " is : " + instr.indexOf(ch));

sc.nextLine();
String instr1 = "", instr2 = "";
System.out.println("Enter the First String to Concat : ");
instr1 = sc.nextLine();
System.out.println("Enter the Second String to Concat : ");
instr2 = sc.nextLine();

String concatstr = instr1.concat(" ").concat(instr2);


System.out.println("Concatenated String is : " + concatstr);

System.out.println("Specify 2 Bounds to generate Sub String : ");


int beg = sc.nextInt();
int end = sc.nextInt();
System.out.println("Sub String from Index " + beg + " is : " + concatstr.substring(beg));
System.out.println("Sub String from " + beg + " to " + end + " is : " + concatstr.substring(beg,
end));

System.out.println("Enter a String with few Leading, In Between and Trailing Spaces : ");
sc.nextLine();
String spstr = sc.nextLine();
System.out.println("Entered String with Invalid Spaces is : " + spstr);

System.out.println("Valid String after Eliminating Invalid Spaces is : " + spstr.trim());


}
}
Output:

Enter Input String : This is the First String Example


Entered String is : This is the First String Example
Length of the Entered String is : 32
String in UPPER CASE is : THIS IS THE FIRST STRING EXAMPLE
String in LOWER CASE is : this is the first string example

Specify Index to access the Character : 14


Character at Index 14 is : r
Specify the Character to look for : i
Index of i is : 2

Enter the First String to Concat : Hello


Enter the Second String to Concat : India
Concatenated String is : Hello India
Specify 2 Bounds to generate Sub String : 2 9
Sub String from 2 to 9 is : llo Ind

Enter a String with few Leading, In Between and Trailing Spaces : ___He__llo__India__
Entered String with Invalid Spaces is : ___He__llo__India__
Valid String after Eliminating Invalid Spaces is : He__llo__India
Practical - 15
Aim: Write a program to demonstrate the use of String Buffer in JAVA.

StringBuffer: StringBuffer Class in JAVA allows the creation of Mutable Strings. By default,
Strings are immutable. It allows changes in Strings, thereby making them mutable. It is Thread
Safe, i. e., multiple Threads can‟t access it simultaneously.

The common Constructors of StringBuffer Class include:

CONSTRUCTOR DESCRIPTION
StringBuffer() It creates an Empty StringBuffer with Initial Capacity of 16.
StringBuffer(String str) It creates a StringBuffer with specified String „str‟.
StringBuffer(int capacity) It creates an Empty String Buffer with „capacity‟ as Length.

The common Methods of StringBuffer Class include:

METHOD NAME DESCRIPTION


~ It appends „s‟ to the specified StringBuffer
~ It is an Overloaded Method
append(String s)
~ It can be used to append FLOAT, INT,
CHAR, DOUBLE, etc.
~ It inserts „s‟ at „pos‟ Index in the
StringBuffer
insert(int pos, String s) ~ It is an Overloaded Method
~ It can insert CHAR, FLOAT, INT,
DOUBLE, etc.
It replaces the Substring from „begId‟ to
replace(int begId, int endId, String s)
„endId – 1‟ Indices with „s‟.
It deletes the Substring from „begId‟ to
delete(int begId, int endId)
„endId – 1‟ Indices.
It reverses the sequence of Characters in
reverse()
String Buffer.
It returns the current Capacity of the
capacity()
StringBuffer.
It returns the Character present at „index‟
chatAt(int index)
Position.
It returns the Length of StringBuffer, i. e.,
length()
total number of Characters present.
substring(int begId) It returns Substring starting from „begId‟.
It returns Substring starting from „begId‟ to
substring(int begId, int endId
„endId – 1‟.
It ensures that the Capacity of StringBuffer
ensureCapacity(int minCap)
should be a least equal to „minCap‟.

If the Capacity of StringBuffer is exhausted, its Capacity increases by „(old_capacity * 2) + 2‟.


For example, if current capacity of StringBuffer is 21 and it gets exhausted (Filled Completely),
then the new capacity will be ‟(21 * 2) + 2 = 42 + 2 = 44‟.

Program:

import java.util.*;

class StringBufferDemo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String to initialize a String Buffer : ");
String s1 = scan.nextLine();
StringBuffer str_buf = new StringBuffer(s1);
System.out.println("String in String Buffer is : " + str_buf);
System.out.println("Capacity : " + str_buf.capacity());

System.out.println("Enter a String to APPEND to String Buffer : ");


s1 = scan.nextLine();
str_buf.append(' ');
str_buf.append(s1);
System.out.println("Updated String in String Buffer is : " + str_buf);
System.out.println("Capacity : " + str_buf.capacity());

System.out.println("Specify a String to INSERT in String Buffer : ");


s1 = scan.nextLine();
System.out.println("Specify the Position to INSERT the String : ");
int pos = scan.nextInt();
str_buf.insert(pos, s1);
System.out.println("String Buffer after INSERT is : " + str_buf);
System.out.println("Capacity : " + str_buf.capacity());

str_buf.replace(6, 11, "Incredible");


System.out.println("String Buffer after REPLACE is : " + str_buf);
System.out.println("Capacity : " + str_buf.capacity());

str_buf.delete(6, 16);
System.out.println("String Buffer after DELETE is : " + str_buf);
System.out.println("Capacity : " + str_buf.capacity());

System.out.println("Reverse String Buffer is : " + str_buf.reverse());


System.out.println("Current Capacity of String Buffer is : " + str_buf.capacity());
}
}

Output:

Enter a String to initialize a String Buffer : Hello


String in String Buffer is : Hello
Capacity : 21
Enter a String to APPEND to String Buffer : India
Updated String in String Buffer is : Hello India
Capacity : 21

Specify a String to INSERT in String Buffer : Great_


Specify the Position to INSERT in String Buffer : 6
String Buffer after INSERT is : Hello Great India
Capacity : 21

String Buffer after REPLACE is : Hello Incredible India


Capacity : 44
String Buffer after DELETE is : Hello India
Capacity : 44

Reverse String Buffer is : aidnI olleH


Current Capacity of String Buffer is : 44
Practical - 16
Aim: Write a program to demonstrate the use of THIS for accessing the members of the same
class.

‘this’: It is a JAVA Keyword that refers to the current Object. It can be used as a Reference
Variable to point to the current Object, current Class Data, Members or Constructor. The most
common use of „this‟ is to eliminate the confusion between Class Attributes and Parameters with
the same name. There are 6 main uses of „this‟ in JAVA. They are:

~ It is used to refer an Instance Variable of the current Class.

~ It is used to invoke a Method of the current Class implicitly.

~ “this()” is used to invoke the Constructor of the current Class.

~ It can be passed as an argument in a Method Call.

~ It can be passed as an argument in a Constructor Call.

~ It can be used to return the Instance of the current Class from the Method.

Program:

import java.util.*;

class ThisExample
{
int x, y, z, product;

public ThisExample(int x, int y, int z)


{
this.x = x;
this.y = y;
this.z = z;
product = 1;
}

public void compute()


{
product = x * y * z;
}

public void show()


{
this.compute();
System.out.println("PRODUCT of 3 Numbers is : " + product);
}

public static void main(String[] args)


{
int m = 0, n = 0, p = 0;
Scanner sc = new Scanner(System.in);

System.out.println("Enter 3 Integers : ");


m = sc.nextInt();
n = sc.nextInt();
p = sc.nextInt();

ThisExample obj = new ThisExample(m, n, p);


obj.show();
}
}

Output:

Enter 3 Integers :
5
7
11

Product of 3 Numbers is : 385


Practical - 17
Aim: Define a class Base with Data Members [String name and int age] and Member Methods
[getBaseData() and showBaseData()]. Define another class Child with Data Members [String
branch and int sem] and Member Methods [getChildData() and showChildData()]. Child is
derived from Base. Initialize an Object of Child and access all its Member Methods as well as
Member Methods of Base to show the existence of Inheritance among them. Implement this
scenario in JAVA.

Inheritance: It is the most striking feature of OOP that promotes Reusability of Code. It is the
process in which Object of a Class acquire properties of Object of another Class. Inheritance
creates a hierarchical relationship among Classes. It is a process in which a Derived Class
exhibits the characteristics or properties of Base Class.

The Class whose properties are being reused or derived is called Base Class or Parent Class or
Super Class. The Class that reuses the properties of Base Class is called Derived Class or Sub
Class or Child Class. The Child Class inherits the properties of the Base Class. Inheritance
represents “is a” relationship among Classes.

Types of Inheritance: JAVA supports 4 types of Inheritance, namely Simple or Single Level
Inheritance, Multi Level Inheritance, Hierarchical Inheritance and Hybrid Inheritance. “extends”
Keyword is used to specify Inheritance relationship among Classes.
When a Child Class inherits the properties of a Base Class, then it is called Simple or Single
Level Inheritance. When a Child Class inherits the properties of a Base Class and then this Child
Class later becomes Base Class for another Class, then it is called Multi Level Inheritance. When
a single Base Class is derived to multiple Child Classes, then it is called Hierarchical Inheritance.
A Inheritance hierarchy in which there exists Multi Level Inheritance among some Classes and
Hierarchical Inheritance among some Classes, then it is called Hybrid Inheritance in JAVA.

The syntax for implementing Simple Inheritance in JAVA is:

class Base {
Data Members of Base Class;
Member Methods of Base Class; }

class Derived extends Base {


// Data Members of Base Class inherited due to „extends‟
Data Members of Child Class;
// Member Methods of Base Class inherited due to „extends‟
Member Methods of Child Class; }

Program:

import java.util.*;

class Base {
private String name;
private int age;

public void getBaseData() {


Scanner scbase = new Scanner(System.in);
System.out.println("Enter your Name : ");
name = scbase.nextLine();

System.out.println("Enter your Age : ");


age = scbase.nextInt(); }

public void showBaseData() {


System.out.println("Your Name is : " + name);
System.out.println("Your Age is : " + age); }
}
class Child extends Base {
private String branch;
private int sem;

public void getChildData() {


Scanner scder = new Scanner(System.in);
System.out.println("Enter your Branch : ");
branch = scder.nextLine();

System.out.println("Enter your Semester : ");


sem = scder.nextInt(); }

public void showChildData() {


System.out.println("Your Branch is : " +branch);
System.out.println("Your Semester is : " + sem); }
}

class TestSimpleInherit {
public static void main(String[] args) {
Child obj = new Child();
obj.getBaseData();
obj.getChildData();

obj.showBaseData();
obj.showChildData();
} }

Output:

Enter your Name : Raj Kumar


Enter your Age : 21
Enter your Branch : CSE
Enter your Semester : 8

Your Name is : Raj Kumar


Your Age is : 21
Your Branch is : CSE
Your Semester is : 8
Practical - 18
Aim: Define a class Base with Member Methods [void show()]. Define a class Child derived
from Base. Child modifies the definition of show(). Prove that for derived method show(), two
different definitions exist in the scenario. Implement this in JAVA.

Method Overriding: If the Child Class redefines or modifies the inherited Method of the Base
Class, then it is called Method Overriding. If the Child Class provides the specific
implementation of the Method, already declared in the Base Class, it is known as Method
Overriding. It is a technique to achieve Run Time Polymorphism.

The overridden method of the Child Class must have the same name as in the Base Class. The
overridden method must have the same parameters as in the Base Class. There must be a “is a”
relationship among Classes, i. e., Inheritance.

Program:

class Base {
public void show () {
System.out.println("SHOW METHOD IN BASE CLASS"); }
}

class Child extends Base {


public void show () {
System.out.println("OVERRIDDEN SHOW METHOD IN CHILD CLASS"); }
}

class TestOverriding {
public static void main(String[] args) {
Base objbase = new Base(); objbase.showOverride();

Child obj = new Child(); obj.showOverride();


} }

Output:

SHOW METHOD IN BASE CLASS


OVERRIDDEN SHOW METHOD IN CHILD CLASS
Practical - 19
Aim: Write a program to demonstrate the use of SUPER for accessing the members of the Base
class.

‘super’: It is a reference variable that refers to an Object of the immediate Base Class. Whenever
an Instance of Child Class is created, an Instance of Base Class is created implicitly, which is
referred by using “super” Keyword. There are 3 main uses of “super” in JAVA as:

~ It is used to refer an Instance Variable of immediate Base Class.

~ It is used to invoke a Method of immediate Base Class.

~ “super()” is used to invoke the Constructor of the immediate Base Class.

Program:

class SuperExampleParent {
public void show() {
System.out.println("This is SHOW() in Parent Class"); }
}

class SuperExampleChild extends SuperExampleParent {


public void show() {
super.show();
System.out.println("This is SHOW() in Child Class"); }

public static void main(String[] args) {


SuperExampleChild obj = new SuperExampleChild();
obj.show();
} }

Output:

This is SHOW() in Parent Class


This is SHOW() in Child Class
Practical - 20
Aim: Write a program to demonstrate the use of Abstract Class and its extension to another
Class in JAVA.

Abstract Class: A Class which is declared with “abstract” Keyword is called an Abstract Class
in JAVA. It can have Abstract Methods, as well as non abstract methods. It can only be used as
Base Class for extension. Mostly, Abstract Class is used to create a new Inheritance hierarchy.
Abstract Class can never be instantiated; this means that it is not possible to create an Object of
Abstract Class.

Abstract Method: A Method declared using Abstract Keyword is called an Abstract Method.

Final: “final” Keyword in JAVA is used to restrict the usage of programming structures. A
Variable, Method or Class can be declared as “final”. If a variable is declared as “final”, its value
can‟t be changed. If a method is declared as “final”, it can‟t be overridden. If a Class is declared
as “final”, it can‟t be extended.

Abstract Class is mainly used to initialize the new Inheritance hierarchy among Classes; in
contrast, the Final Class is mainly used to terminate the existing Inheritance hierarchy among
Classes.

Program:

abstract class Shape


{ abstract void draw(); }

class Rectangle extends Shape


{
void draw()
{
System.out.println("This is Rectangle - A Shape");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("This is Circle - A Shape");
}
}

class Triangle extends Shape


{
void draw()
{
System.out.println("This is Triangle - A Shape");
}
}

class AbstractDemo
{
public static void main(String[] args)
{
Shape rect = new Rectangle();
rect.draw();

Shape cir = new Circle();


cir.draw();

Shape tri = new Triangle();


tri.draw();
} }

Output:

This is Rectangle – A Shape


This is Circle – A Shape
This is Triangle – A Shape
Practical - 21
Aim: Declare an interface I1 with Method [void show()]. Define a class C1 with Data Member
[String name]. Use constructor of C1 to initialize the name and C1 will implement I1, so that
show() will display the name as output. Implement this scenario in JAVA.

Interface in JAVA: An “Interface” in JAVA is a blue-print of a Class. It has Static Constants


and Abstract Methods. It is a mechanism to achieve Abstraction in JAVA, similar to Abstract
Class. It can be considered as a technique to achieve the same functionality as Multiple
Inheritance. It also represents the “is a” relationship.

Similar to Abstract Class, Interface can‟t be instantiated. It is used to achieve Loose Coupling.
“interface” Keyword is used to declare an Interface in JAVA. All the Methods in an Interface are
declared with “empty body”; all the fields are Public, Static and Final by default. A Class that
implements an Interface must define or implement all Methods declared in the Interface.
“implements” Keyword is used to associate a Class with an Interface.

A Class can extend only one another Class; however, a Class can implement multiple Interfaces
simultaneously. Similar to Class, an Interface can extend another Interface. The syntax to
implement Interface in JAVA is:

interface INTERFACE_NAME {
static constants;
abstract methods;
}

class CLASS_NAME implements INTERFACE_NAME {


Define abstract methods of INTERFACE_NAME; }

interface I1 { abstract methods 1; }

interface I2 extends I1 {
// abstract methods 1 will be the part of I2, due to „extends‟
abstract methods 2;
}
Program:

import java.util.Scanner;

interface I1 { public void show(); }

class C1 implements I1
{
private String name;

public C1()
{
System.out.println("Enter Your Name : ");
Scanner scan = new Scanner (System.in);
name = scan.nextLine();
}

public void show()


{
System.out.println("Your Name is : " + name);
}
}

class TestInterface
{
public static void main(String[] args)
{
C1 obj1 = new C1();
obj1.show();
} }

Output:

Enter Your Name : Rohit Sharma

Your Name is : Rohit Sharma


Practical - 22
Aim: Declare an interface Player with Method [void showPlayerDetails()]. Define 3 classes
CricketPlayer with Data Members [int matches, int runs, int wickets and int catches],
TennisPlayer with Data Members [int matches, int titles and int grand_slams] and
FootBallPlayer with Data Members [int matches and int goals]. Use constructors to take details
of these Players as input from user. CricketPlayer, TennisPlayer and FootBallPlayer will
implement the Player interface. Implement this scenario in JAVA.

Implementing an Interface in Multiple Classes: An Interface in JAVA can be implemented in


different Classes with different definitions. Let, I be the Interface and C1, C2 and C3 be the 3
Classes that will implement I, then the implementation will be given, as:

interface I { public void Method_Name(); }

class C1 implements I {
Data Members of C1;
Member Methods of C1;
public void Method_Name() { Definition for Class C1; }
}

class C2 implements I {
Data Members of C2;
Member Methods of C2;
public void Method_Name() { Definition for Class C2; }
}

class C3 implements I {
Data Members of C3;
Member Methods of C3;
public void Method_Name() { Definition for Class C3; }
}
Program:

import java.util.*;

interface Player { public void showPlayerDetails(); }

class CricketPlayer implements Player {


private int matches, runs, wickets, catches;

public CricketPlayer(int matches, int runs, int wickets, int catches) {


this.matches = matches;
this.runs = runs;
this.wickets = wickets;
this.catches = catches;
}

public void showPlayerDetails() {


System.out.println("Matches Played by Cricketer : " + matches);
System.out.println("Runs Scored by Cricketer : " + runs);
System.out.println("Wickets Taken by Cricketer : " + wickets);
System.out.println("Catches Taken by Cricketer : " + catches);
} }

class TennisPlayer implements Player {


private int matches, titles, grand_slams;

public TennisPlayer(int matches, int titles, int grand_slams) {


this.matches = matches;
this.titles = titles;
this.grand_slams = grand_slams;
}

public void showPlayerDetails() {


System.out.println("Matches Played by Tennis Player : " + matches);
System.out.println("Titles Won by Tennis Player : " + titles);
System.out.println("Grand Slams for Tennis Player : " + grand_slams);
} }

class FootBallPlayer implements Player {


private int matches, goals;

public FootBallPlayer(int matches, int goals) {


this.matches = matches;
this.goals = goals; }
public void showPlayerDetails() {
System.out.println("Matches Played by FootBaller : " + matches);
System.out.println("Goals Hit by FootBaller : " + goals);
} }

class OneInterfaceMultipleClassExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int c_m = 0, c_r = 0, c_w = 0, c_c = 0, t_m = 0, t_t = 0, t_gs = 0, f_m = 0, f_g = 0;
System.out.println("Specify the Matches Played, Runs Scored, Wickets Taken and Catches
Taken by Cricketer : ");
c_m = scan.nextInt();
c_r = scan.nextInt();
c_w = scan.nextInt();
c_c = scan.nextInt();

System.out.println("Specify the Matches Played, Titles Wons and Grand Slams Won by Tennis
Player : ");
t_m = scan.nextInt();
t_t = scan.nextInt();
t_gs = scan.nextInt();

System.out.println("Specify the Matches Played and Goals Hit by Footballer : ");


f_m = scan.nextInt();
f_g = scan.nextInt();

CricketPlayer cric_obj = new CricketPlayer(c_m, c_r, c_w, c_c);


cric_obj.showPlayerDetails();

TennisPlayer t_obj = new TennisPlayer(t_m, t_t, t_gs);


t_obj.showPlayerDetails();

FootBallPlayer fb_obj = new FootBallPlayer(f_m, f_g);


fb_obj.showPlayerDetails();
} }
Output:
Specify the Matches Played, Runs Scored, Wickets Taken and Catches Taken by Cricketer :
700 35000 205 275

Specify the Matches Played, Titles Won and Grand Slams Won by Tennis Player :
700 125 15
Specify the Matches Played and Goals Hit by Footballer :
800 700

Matches Played by Cricketer : 700


Runs Scored by Cricketer : 35000
Wickets Taken by Cricketer : 205
Catches Taken by Cricketer : 275

Matches Played by Tennis Player : 700


Titles Won by Tennis Player : 125
Grand Slams for Tennis Player : 15

Matches Played by Footballer : 800


Goals Hit by Footballer : 700
Practical - 23
Aim: Declare interfaces Sum with Method [int add()], Product with Method [double multiply()]
and Average with Method [double mean()]. Define a class Calculator with Data Members [int
n1, int n2, int n3, double d1, double d2 and double d3]. Use constructor or some other Member
Method to take input of these data members from user. Calculator will implement Sum, Product
and Average interfaces. add() will compute sum of n1 and n3; multiply() will compute product of
d1 and d3; mean() will compute average of n2 and d2. Implement this scenario in JAVA.

Implementing Multiple Interfaces in a Class: A Class in JAVA can implement multiple


Interfaces simultaneously. Let, I1, I2 and I3 be the 3 Interfaces and C be the Class that will
implement all 3 Interfaces, then the implementation will be given, as:

interface I1 { public void Method_Name_1(); }

interface I2 { public void Method_Name_2(); }

interface I3 { public void Method_Name_3(); }

class C implements I1, I2, I3 {


Data Members of C;
Member Methods of C;

public void Method_Name_1() { Definition of Method_Name_1; }

public void Method_Name_2() { Definition of Method_Name_2; }

public void Method_Name_3() { Definition of Method_Name_3; }


}

Program:

import java.util.*;

interface Sum { public int add(); }

interface Product { public double multiply(); }


interface Average { public double mean(); }

class Calculator implements Sum, Product, Average {


private int n1, n2, n3;
private double d1, d2, d3;

public Calculator(int n1, int n2, int n3, double d1, double d2, double d3) {
this.n1 = n1;
this.n2 = n2;
this.n3 = n3;

this.d1 = d1;
this.d2 = d2;
this.d3 = d3;
}

public int add() { return (n1 + n3); }

public double multiply() { return (d1 * d3); }

public double mean() { double temp = d2 + n2; return (temp / 2.0); }


}

class OneClassMultipleInterfaceExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num1 = 0, num2 = 0, num3 = 0;
double dnum1 = 0.0, dnum2 = 0.0, dnum3 = 0.0;
System.out.println("Enter 3 Integers : ");
num1 = scan.nextInt();
num2 = scan.nextInt();
num3 = scan.nextInt();

System.out.println("Enter 3 Floating Point Numbers : ");


dnum1 = scan.nextDouble();
dnum2 = scan.nextDouble();
dnum3 = scan.nextDouble();

Calculator c_obj = new Calculator(num1, num2, num3, dnum1, dnum2, dnum3);


int r1 = c_obj.add();
double r2 = c_obj.multiply();
double r3 = c_obj.mean();
System.out.println("SUM of NUM1 and NUM3 is : " + r1);
System.out.println("PRODUCT of DNUM1 and DNUM3 is : " + r2);
System.out.println("AVERAGE of NUM2 and DNUM2 is : " + r3);
} }

Output:

Enter 3 Integers :
25 50 100
Enter 3 Floating Point Numbers :
23.6 24.8 25.7

SUM of NUM1 and NUM3 is : 125


PRODUCT of DNUM1 and DNUM3 is : 606.52
AVERAGE of NUM2 and DNUM2 is : 37.4

You might also like