0% found this document useful (0 votes)
9 views83 pages

BSC 3rdsem Course5 Java

The document outlines the concepts of Object Oriented Programming (OOP) using Java, covering key topics such as classes, objects, inheritance, encapsulation, abstraction, and polymorphism. It also contrasts procedural programming with OOP and discusses Java data types, including primitive and non-primitive types. Additionally, the document includes sections on arrays, strings, exception handling, and GUI programming with Swing.

Uploaded by

sunithaguntaka0
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)
9 views83 pages

BSC 3rdsem Course5 Java

The document outlines the concepts of Object Oriented Programming (OOP) using Java, covering key topics such as classes, objects, inheritance, encapsulation, abstraction, and polymorphism. It also contrasts procedural programming with OOP and discusses Java data types, including primitive and non-primitive types. Additionally, the document includes sections on arrays, strings, exception handling, and GUI programming with Swing.

Uploaded by

sunithaguntaka0
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

Object Oriented Programming using Java 1

Unit 1 : OOP concepts & Java Programming

01. Write about Object Oriented Programming concepts. - 03


02. Write differences between procedural & Object oriented programming concepts. - 07
03. Write about data types in Java. - 08
04. Explain Type conversion & Type casting. - 10
05. Scope of variables in Java. - 11
06. Write about Operators in Java. - 12
07. Write about decision control (or) conditional statements in Java. - 15
08. Write about looping (or) iterative statements in Java. - 20
09. Explain about accepting Input & displaying output in Java. - 23

Unit 2 : Arrays, Strings, Classes & Objects, Inheritance, Polymorphism

01. What are the different types of Arrays in Java? - 25


02. Explain command line arguments in Java. - 26
03. How to create strings? Explain methods in String class. - 27
04. Write about classes & objects in OOP. - 30
05. Inheritance in Java. - 32
06. Polymorphism in Java. - 36
07. Dynamic binding in Java. - 38
08. Abstract methods & Abstract classes in Java. - 39

Unit 3 : Interfaces, Packages & Exception Handling


01. Write differences between Abstract classes & Interfaces. - 41
02. Write about ‘Interfaces’ in Java. - 43
03. Write about ‘Packages’ in Java. - 45
04. Write about ‘Exception Handling’ in Java. - 47

Object Oriented Programming using Java – Sudheer Kumar


2

Unit 4 : Threads & Streams

01. Write differences between Multiprocessing & Multithreading. - 51


02. What are threads? Write different states in ‘Thread Life Cycle’? Explain. - 52
03. Explain about ‘Thread priority’ & ‘Thread Synchronization’. - 55
04. Write about ‘Inter Thread Communication’. - 58
05. Write about ‘Streams’ in Java. (or) Explain Byte Stream & Character Stream classes. - 59
06. Explain Read data from a file using FileInputStream & create a file using FileOutputStream. - 61
07. Explain Read data from a file using FileReader & create a file using FileWriter. - 61
08. Write about Serialization & Deserialization of objects. - 62

Unit 5 : GUI Programming with Swing, Event Handling

01. Write differences between AWT & Swing. - 65


02. Explain MVC architecture in Java. - 66
03. Write about Layout Managers in Java. - 69
04. Write about ‘Event Handling’ in Java. (or) Explain ‘The Delegation event model’. - 74
05. How to handle Mouse events? - 77
06. How to handle Keyboard events? - 79

Model Question paper 1 - 80


Model Question paper 2 - 81

Object Oriented Programming using Java – Sudheer Kumar


Unit 1 : OOP concepts & Java Programming
3
01. Write about Object Oriented Programming concepts.

Object Oriented Programming:

 Object Oriented programming is a programming style which is associated with the concepts like class, object,
Inheritance, Encapsulation, Abstraction, Polymorphism.
 Most popular programming languages like Java, C++ etc. follow an object-oriented programming paradigm.
 An object-based application in Java is based on declaring classes, creating objects from them and interacting
between these objects.
 Following are the basic concepts of Object Oriented Programming.

Class:

 A Class is user defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class (object).
 A class is like a blueprint for an object.
Example: Consider the class of Cars. There may be many cars with different names and brand, but all of them
will share some common properties like no_of_wheels, speed_limit, mileage_range, apply_breaks,
increase_speed etc.
 Data members are the data variables and member functions are the functions used to manipulate these
variables.
 These data members and member functions together define the properties and behavior of the objects in a
class.
 In the above example of class Car, the data members will be no_of_wheels, speed_limit, mileage_range etc.
and member functions are apply_brakes, increase_speed etc.

Syntax:
class <class_name>{
data members
--------------
--------------
member functions
}

Ex:
class Car{
int no_of_wheels;
int speed_limit;
int mileage_range;
void apply_breaks(){
….
}
void increase_speed(){
}
}

Object Oriented Programming using Java – Sudheer Kumar


Object:
4
 An object is an instance of a class. When a class is defined, no memory is allocated but when an object is
created for that class, memory is allocated.
 When we send a message to an object, we are asking that object to execute one of its methods.
 The data members and member functions of class can be accessed using the dot(‘.’) operator with the object.
 For example, if the name of object is ‘obj’ and we want to access the member function with the name
printName() then we have to write [Link]() .

Syntax to create an object:


ClassName <object_name> = new ClassName();

Inheritance:
 In Object Oriented Programming, Inheritance is a mechanism where the properties of one class can be
inherited by the other class.
 It helps to reuse the code and establish relationship between different classes.
 In Object Oriented Programming, there are two classes:
1. Parent class (Super class or Base class)
2. Child class (Sub class or Derived class )

 A class which inherits the properties is known as Child class & a class whose properties are inherited is known
as Parent class.

Types of inheritance.

Single inheritance: A
A single super class is inherited by single sub class.
class A{..}
class B extends A{..} B

Multilevel inheritance:
A
A super class is inherited by sub class, and this sub
class is inherited by another sub class.
class A{..}
class B extends A{..} B
class C extends B{..}

Multiple inheritance:

Multiple super classes inherited by single sub class. A B


Java does not support multiple inheritance of
classes, it support multiple inheritance of interfaces.
interface A{..}
interface B{..} C
class C implements A, B{..}

Object Oriented Programming using Java – Sudheer Kumar


Hierarchical inheritance:
5
Single super class is inherited by Multiple sub
A
classes.
class A{..}
class B extends A{..}
class C extends A{..} B C D
class D extends A{..}

Encapsulation:

 Encapsulation is an act of combining properties and methods.


 Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods)
together as a single unit.
 In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through
the methods of their current class. It is also known as data hiding.
 To implement encapsulation in java:
1) Declare the variables as private so that they cannot be accessed directly from outside the class.
2) Have getter and setter methods in the class to set and get the values of the fields.
Example:
class A{
private String empName;
public void setEmpName(String newValue){
empName = newValue;
}
public String getEmpName(){
return empName;
}
}
public class myClass{
public static void main(String args[]){
A obj = new A();
[Link]("SUDHEER");
[Link]("Employee Name: " + [Link]());
}
}

Output:
Employee Name: SUDHEER

Abstraction:

 Abstraction is selecting data from a larger pool to show only the relevant details to the object.
 It helps to reduce programming complexity and effort.
 In Java, abstraction is accomplished using Abstract classes and interfaces.
 In Object-oriented programming, abstraction is a process of hiding the implementation details, provide only
the functionality to the user.
 The user will have the information on what the object does instead of how it does it.

Object Oriented Programming using Java – Sudheer Kumar


Polymorphism:
6
 Polymorphism means one method with multiple implementation. Which implementation to be used is decided
at runtime depending upon the data type of the object.
 Polymorphism could be static and dynamic both. Method Overloading is static polymorphism and Method
Overriding is dynamic polymorphism.

Method overloading (compile time polymorphism):

 In java, method Overloading means creating more than one method with same name with different number
of parameters. Java identifies the methods by comparing their number of parameters.

Example:
class Overload_Ex{
static void sum(int x, int y){
int sum=x+y;
[Link]("sum = "+sum);
}
static void sum(int x, int y, int z){
int sum=x+y+z;
[Link]("sum = "+sum);
}
public static void main(String a[]){
sum(4,3);
sum(2,4,6); Output:
} sum = 7
} sum = 12

Method overriding (run time polymorphism):

 In java, method Overriding means creating a method in subclass with the same name and type signature as a
method in its superclass.

Example:
class A{
void calculate(int x, int y){
int res=x+y;
[Link]("Result: "+res);
}
}
class B extends A{
void calculate(int x, int y){
int res=x*y;
[Link]("Result: "+res);
}
public static void main(String a[]){
B obj = new B();
[Link](2,3); Output:
} Result: 6
}

Object Oriented Programming using Java – Sudheer Kumar


02. Write differences between Procedural & Object Oriented Programming concepts.
7
Procedural Programming:

 Procedural Programming can be defined as a programming model which is derived from


structured programming, based upon the concept of calling procedure.
 Procedures, also known as routines, subroutines or functions, simply consist of a series of
computational steps to be carried out.
 During a program’s execution, any given procedure might be called at any point, including by
other procedures or itself.
 Languages used in procedural programming: FORTRAN, COBOL, BASIC, Pascal & C.

Object Oriented Programming:

 Object-oriented programming can be defined as a programming model which is based upon


the concept of objects. Objects contain data in the form of attributes and code in the form of
methods.
 Object-oriented programming languages are various but the most popular ones are class-
based, meaning that objects are instances of classes.
 Languages used in Object Oriented Programming: C++, Java, Python, PHP.

 Following are some of the differences between Procedural & Object Oriented Programming.

[Link] Procedural Programming Object Oriented Programming

The program is divided into small parts The program is divided into small parts called
1
called functions. objects.

Procedural programming follows Top-


2 OOP follows Bottom-Up approach.
Down approach.
OOP has access specifiers like public, private,
3 No access specifiers.
protected etc.
Adding new data & functions is not
4 Adding new data & functions is easy.
easy.
Less secure as there is no proper way
5 More secure as OOP provides data hiding.
of hiding data.
6 Overloading is not possible. Overloading is possible.

7 There is no concept of inheritance. There is concept of inheritance.


In Procedural programming, function is In OOP, data is more important than
8
more important than data. function.

9 Based on unreal world. Based on real world.

Examples: FORTRAN, COBOL, BASIC,


10 Examples: C++, Java, Python, PHP.
Pascal & C.

Object Oriented Programming using Java – Sudheer Kumar


03. Write about data types in Java.
8
Data types in Java:

 Data types specify the different sizes and values that can be stored in the variable.
 There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays

Java Primitive Data Types (Basic data types):

 In Java language, primitive data types are the building blocks of data manipulation. These are the most basic
data types available in Java language.
 There are 8 types of primitive data types:

Data type Default Size


Boolean 1 bit
char 2 bytes
byte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
float 4 bytes
double 8 bytes

Java Non-primitive Data Types (Derived data types):

 The non-primitive Java data types are created by the programmer during the coding process.
 They are known as the “reference variables” as they refer to a location where data is stored.
 Following are the non-primitive datatypes in Java. String, Array, Class, Interface etc.

String:

 Strings are used to store text. A String variable contains a collection of characters surrounded by
 double quotes:
Example:
Create a variable of type String and assign it a value: String greeting = "Hello";

 There are number of methods in String class to manipulate strings in Java.


Example:
charAt() to return index of the character specified.
length() is used to return the length of the string.
concat() is used to concatenate to strings.

Array:
 Arrays are used to store multiple values in a single variable, instead of declaring separate variables
 for each value.
 To declare an array, define the variable type with square brackets: String cars[];
 To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly
braces: String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
 To create an array of integers, you could write: int[] myNum = {10, 20, 30, 40};

Object Oriented Programming using Java – Sudheer Kumar


Class:

 A class is user defined blueprint or prototype from which objects are created.
9
 It represents the set of properties or methods that are common to all objects of one type.
 There are various types of classes that are used in real time applications such as nested classes,
anonymous classes etc.
 In general, class declarations can include the following components:
Modifiers : A class can be public (or) default access.
Class name : The name should begin with initial letter (capitalized by convention).
Superclass(if any) : The name of the class’s parent (superclass), if any, preceded by the
keyword ‘extends’. A class can only extend (subclass) one parent.
Interfaces(if any) : A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword ‘implements’. A class can implement more than
one interface.
Body : The class body surrounded by curly braces, { }.

Interface:

 In Java, an interface is an abstract type that contains a collection of methods and constant variables.
 It is one of the core concepts in Java and is used to achieve abstraction, polymorphism and multiple
inheritances.
 We can implement an interface in a Java class by using the implements keyword.
 An interface is a completely "abstract class" that is used to group related methods with empty bodies.
 To access interface methods, the interface must be implemented by another class with the implements
keyword. The body of the interface method provided by the implement class.

Example:

interface Animal{
public void animalSound(); // method without body
public void run(); // method without body
}
class Pig implements Animal {
public void animalSound() {
[Link]("The pig says: wee wee");
}
public void sleep() {
[Link]("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
[Link]();
[Link]();
}
}

Output:

The pig says: wee wee


Zzz

Object Oriented Programming using Java – Sudheer Kumar


04. Explain Type conversion & Type casting.
10
Type Casting

 Assigning a value of one type to a variable of another type is known as Type Casting.
Example:
int x = 10;
byte y = (byte)x;

Implicit casting [or] Widening casting [or] Automatic type conversion:

 Automatic Type casting take place when, the two types are compatible & the target type is
larger than the source type.

Example:
public class Test{
public static void main(String[] args){
int a = 100;
long b = a; //no explicit type casting required
float c = b; //no explicit type casting required
[Link]("Int value "+a);
[Link]("Long value "+b);
[Link]("Float value "+c);
}
}

Output:
Int value 100
Long value 100
Float value 100.0

Explicit casting [or] Narrowing Casting:

 When a larger type value is assigned to a smaller type, then explicit type casting is required.

Example:
public class Test{
public static void main(String[] args){
double a = 100.04;
long b = (long)a; //explicit type casting required
[Link]("Double value "+a);
[Link]("Long value "+b);
}
}

Output:
Double value 100.04
Long value 100

Object Oriented Programming using Java – Sudheer Kumar


05. Scope of variables in Java.
11
Scope of variables:

 The scope of a variable defines the section of the code in which the variable is visible.
 The variables that are defined within a block are not accessible outside that block.
 The variables declared in the body of a method were different from those that were declared in the class
itself.
 There are there types of variables: instance variables (class level), local variables (method level) and loop
variables (block level).

instance variables (Class level)


These variables must be declared inside class (outside any function). They can be directly accessed anywhere
in class.
Example:
public class Test{
int a;
String str=”Hello”;
void method1() {....}
int method2() {....}
char ch;
}
Here, the variables a, str, ch are instance variables.

Local Variables (Method Level)


These variables are declared inside a method and can’t be accessed outside the method.
Example:
public class Test{
void method1() {
// Local variable (Method level scope)
int x;
}
}

Loop variables (Block Level)


A variable declared inside pair of brackets { and } in a method has scope within the brackets only.
Example:
class Test{
public static void main(String args[]){
for (int x = 0; x < 4; x++){
[Link](x);
}
[Link](x); // this will produce error
}
}

Object Oriented Programming using Java – Sudheer Kumar


06. Write about Operators in Java.
12
Operators:

Operators are used to combine literals, variables, method calls, and other expressions.
Java provides a rich set of operators environment. Java operators can be divided into following categories:

Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Other operators

Arithmetic operators:
Arithmetic operators are used in mathematical expression in the same way that are used in algebra.

Operator Description
+
adds two operands
-
subtract second operands from first
*
multiply two operand
/
divide numerator by denominator
%
remainder of division
++
Increment operator increases integer value by one
-- Decrement operator decreases integer value by one

Relational operators
The following table shows all relational operators supported by Java.

Operator Description

== Check if two operands are equal

!= Check if two operands are not equal

> Check if left operand is greater than right operand

< Check if left operand is smaller than right operand

>= Check if left operand is greater than or equal to right operand

<= Check if left operand is smaller than or equal to right operand

Object Oriented Programming using Java – Sudheer Kumar


Logical operators
13
Java supports following 3 logical operator. Suppose a=1 and b=0;

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

Bitwise operators

Java defines several bitwise operators that can be applied to the integer data types.

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the
right operand specifies the number of positions that the bits in the value are to be shifted. Both operands
have the same precedence.

Example:
a = 0001000
b=2
a<<b = 0100000
a>>b = 0000010

Object Oriented Programming using Java – Sudheer Kumar


Assignment Operators
Assignment operator supported by Java are as follows: 14
Operator Description Example

= assigns values from right side operands to left side operand a=b

+= adds right operand to the left operand and assign the result to left a+=b is same
as a=a+b

-= subtracts right operand from the left operand and assign the result to left a-=b is same
operand as a=a-b

*= multiply left operand with the right operand and assign the result to left a*=b is same
operand as a=a*b

/= divides left operand with the right operand and assign the result to left a/=b is same
operand as a=a/b

%= calculate modulus using two operands and assign the result to left operand a%=b is same
as a=a%b

Other operators:
There are few other operators supported by java language.

Conditional operator:
It is also known as ternary operator and used to evaluate Boolean expression.
expr1 ? expr2 : expr3
If expr1 Condition is true? Then value expr2 : Otherwise value expr3
instanceof operator:
This operator checks whether the object is of particular type (class type or interface type)
The instanceof operator is written as:
( Object reference variable ) instanceof (class/interface type)

Ex:
public class Test {
public static void main(String args[]) {
String name = "SUDHEER";
// following will return true because name is type of String
boolean result = name instanceof String;
[Link]( result );
}
}

Output:
true

Object Oriented Programming using Java – Sudheer Kumar


07. Write about decision control (or) conditional statements in Java.
15
Decision control (or) Conditional statements in Java:

 Decision making structures have one (or) more conditions to be tested by the program.
 If the condition is true, a statement or group of statements will be executed, and if the condition is false
other statements will be executed.
 The general form of a decision making structure will be as shown below:

 Java programming language provides following types of decision making statements.

[Link] Statement Description

consists of a boolean expression followed by


1 simple if statement
one or more statements.

An if statement can be followed by an


2 if else statement optional else statement, which executes
when the boolean expression is false.

3 Nested if statement multiple if statements

allows a variable to be tested for equality


4 switch statement
against a list of values.

Object Oriented Programming using Java – Sudheer Kumar


Simple if statement:
An if statement consists of a Boolean expression followed by one or more statements. 16
Syntax:

if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}

If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If
not, the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Flow Diagram

Example:

public class Test {


public static void main(String args[]) {
int x = 10;
if( x < 20 ) {
[Link]("This is if statement");
}
[Link]("This is the statement after if block.");
}
}
This will produce the following result −

Output:
This is if statement.
This is the statement after if block.

Object Oriented Programming using Java – Sudheer Kumar


if else statement:
An if statement can be followed by an optional else statement, which executes when the Boolean expression
17
is false.
Syntax

if(Boolean_expression) {
// Executes when the Boolean expression is true
} else {
// Executes when the Boolean expression is false
}
If the boolean expression evaluates to true, then the ‘if’ block of code will be executed, otherwise ‘else’ block
of code will be executed.
Flow Diagram:

Example:

public class Test {


public static void main(String args[]) {
int x = 30;
if( x < 20 ) {
[Link]("This is if statement");
}else {
[Link]("This is else statement");
}
}
}

Output
This is else statement

Object Oriented Programming using Java – Sudheer Kumar


nested if statement:
In this, we can use one if statement inside another if statement.
18
Syntax:

if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}

Example:
public class Test {
public static void main(String args[]) {
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
[Link]("X = 30 and Y = 10");
}
}
}
}

Output:
X = 30 and Y = 10

switch statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each case.
Syntax

switch(expression) {
case value :
// Statements
break;
case value :
// Statements
break;
..........
..........
..........
default : // Statements
}

Object Oriented Programming using Java – Sudheer Kumar


Flow Diagram
19

Example:

public class Test {


public static void main(String args[]) {
char grade = 'A';
switch(grade) {
case 'A' :
[Link]("Excellent!");
break;
case 'B' :
[Link]("Good!");
break;
case 'C' :
[Link]("You passed");
break;
default :
[Link]("Invalid grade");
}
[Link]("Your grade is " + grade);
}
}

Output
Excellent
Your grade is A

Object Oriented Programming using Java – Sudheer Kumar


08. Write about looping (or) iterative statements in Java.
20
Looping statements in Java:

 In programming languages, loops are used to execute a set of instructions repeatedly when some condition
become true. There are three types of loops in java.
for loop
while loop
do-while loop

for loop:

 The Java ‘for’ loop is used to iterate a part of the program several times. If the number of iteration is fixed, it
is recommended to use for loop.
 A simple for loop is same as C/C++. We can initialize the variable, check condition and increment/decrement
value. It consists of four parts:
 Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the
variable, or we can use an already initialized variable.
 Condition: It is executed each time to test the condition of the loop. It continues execution until the condition
is false. It must return boolean value either true or false.
 Statement: The statement of the loop is executed each time until the condition is false.
 Increment/Decrement: It increments or decrements the variable value.

Syntax:
for(initialization; condition; incr/decr){
//statements to be executed
}

Flowchart:

initialization

FALSE
condition

TRUE

statements

incr / decr

Object Oriented Programming using Java – Sudheer Kumar


Program to demonstrate for loop:
21
public class For_Loop_Ex {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
[Link](i);
}
}
}

Output:
1
2
3
4
5

while loop:

 The Java while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
Flow chart:

FALSE
condition

TRUE

statements

Object Oriented Programming using Java – Sudheer Kumar


Program to demonstrate while loop:
22
public class While_Loop_Ex { Output:
public static void main(String[] args) { 1
int i=1; 2
while(i<=5){ 3
[Link](i); 4
i++; 5
}
}
}

Java do-while Loop


 The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed and if you want to execute the loop at least once, it is recommended to use do-while loop.
Syntax:
do{
//code to be executed
}while(condition);

Flow chart:

do

statements

TRUE
condition

FALSE

Program to demonstrate do-while loop:

public class do_While_Ex { Output:


public static void main(String[] args) { 1
int i=1; 2
do{ 3
[Link](i); 4
i++; 5
} while(i<=5);
}
}

Object Oriented Programming using Java – Sudheer Kumar


09. Explain about accepting Input & displaying Output in Java.
23
Java Scanner Class

 Java Scanner class allows the user to take input from the console.
 It belongs to [Link] package.
 It is used to read the input of primitive types like int, double, long, short, float, and byte.
 It is the easiest way to read input in Java program.

Syntax
Scanner sc = new Scanner([Link]);

 The above statement creates a constructor of the Scanner class having [Link] as an argument. It means it
is going to read from the standard input stream of the program.
 The [Link] package should be imported while using Scanner class.
 It also converts the Bytes (from the input stream) into characters using the platform's default charset.

Methods of Java Scanner Class


Java Scanner class provides the following methods to read different primitives types:

Method Description

nextBoolean() Reads a boolean value from the user


nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

Example:
import [Link];
class main{
public static void main(String args[]) {
Scanner myObj = new Scanner([Link]);
[Link]("Enter user name");
String userName = [Link]();
[Link]("Hello " + userName);
}
}
Output:
Enter user name SUDHEER
Hello SUDHEER

Object Oriented Programming using Java – Sudheer Kumar


Display Output in Java:
24
In Java, we can use the following statements to send output to standard output (screen):
[Link](); (or) [Link](); (or) [Link]();
Here, System is a class, out is a public static field: it accepts output data.

Difference between println(), print() and printf()

print() - It prints string inside the quotes.


println() - It prints string inside the quotes similar like print() method. Then the cursor moves to the
beginning of the next line.
printf() - It provides string formatting. Ex: [Link]("Hello %s", "World");

Example 1:
class Test{
public static void main(String args[]) {
[Link]("Sudheer is ");
[Link]("Computer Science Lecturer");
}
}
Output:
Sudheer is Computer Science Lecturer

Example 2:
class Test{
public static void main(String args[]) {
[Link]("Sudheer is ");
[Link]("Computer Science Lecturer");
}
}
Output:
Sudheer is
Computer Science Lecturer

Example 3:
class Test{
public static void main(String args[]) {
String str = "Computer Science Lecturer";
[Link]("Sudheer is %s",str);
}
}
Output:
Sudheer is Computer Science Lecturer

Object Oriented Programming using Java – Sudheer Kumar


Unit 2 : Arrays, Strings, Classes & Objects, Inheritance, Polymorphism
25
01. What are the different types of Arrays in Java?

Java Arrays

 Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value.
 To declare an array, define the variable type with square brackets:
String cars[];
We have now declared a variable that holds an array of strings. To insert values to it, we can use an array
literal - place the values in a comma-separated list, inside curly braces:
String cars[] = {"Volvo", "BMW", "Ford", "Mazda"};

 To create an array of integers, you could write: int myNum[] = {10, 20, 30, 40};

Access the Elements of an Array

 We can access an array element by referring to the index number.


Example
String cars[] = {"Volvo", "BMW", "Ford", "Mazda"};
[Link](cars[0]);
Output:
Volvo

 Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element

 To change the value of a specific element, refer to the index number:


Example
cars[0] = "Opel";

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
[Link](cars[0]);
Output:
Opel

Loop Through an Array


 You can loop through the array elements with the for loop, and use the length property to specify how many
times the loop should run.
 The following example outputs all elements in the cars array:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < [Link]; i++) {
[Link](cars[i]+" ");
}
Output:
Volvo BMW Ford Mazda

Object Oriented Programming using Java – Sudheer Kumar


Multidimensional Arrays
 A multidimensional array is an array containing one or more arrays. 26
 To create a two-dimensional array, add each array within its own set of curly braces:

Example
int myNumbers[][] = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.


 To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the
element inside that array.

Example
public class MyClass{
public static void main(String args[]) {
int myNumbers[][] = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
[Link](x);
}
}
Output:
7

Reading elements for two dimensional array:


 We can also use a for loop inside another for loop to get the elements of a two-dimensional array.

Example
public class myClass{
public static void main(String args[]) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < [Link]; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j)
[Link](myNumbers[i][j]+" ");
[Link]();
} Output:
} 1 2 3 4
} 5 6 7

02. Explain command line arguments in Java.

Command line arguments in Java:


 The command line arguments are the arguments passed to a program at the time when you run it.
 The command-line arguments are stored as strings in args parameter of main() method.

Example:

class MyClass{ Output:


public static void main(String args[]){ F:\> javac [Link]
[Link](“Hello “ + args[0]); F:\> java MyClass Sudheer
} Hello Sudheer
}

Object Oriented Programming using Java – Sudheer Kumar


03. How to create strings? Explain methods in String class.
27
Java Strings

 Strings are used to store text.


 A String variable contains a collection of characters surrounded by double quotes:
Example
Create a variable of type String and assign it a value: String greeting = "Hello";

String Methods
Here is the list of methods supported by String class:

SNo Method & Description

1 char charAt(int index)


Returns the character at the specified index.
Ex:
public class Test {
public static void main(String args[]) {
String s = "Hello World";
char result = [Link](6);
[Link](result);
}
}
Output:
W

2 int compareTo(String anotherString)


Compares two strings
Ex:
public class Test {
public static void main(String args[]) {
String str1 = "Hello World";
String str2 = "Hello World";
int result = [Link]( str2 );
[Link](result);
}
}
Output:
0

3 String concat(String str)


Concatenates the specified string to the end of this string.
Ex:
public class Test {
public static void main(String args[]) {
String s = "This is ";
s = [Link](" Beautiful World");
[Link](s);
}
}
Output:
This is Beautiful World

Object Oriented Programming using Java – Sudheer Kumar


4 int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
28
Ex:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
[Link]([Link]( 'o' ));
}
}

Output:
4

5 int indexOf(String str)


Returns the index within this string of the first occurrence of the specified substring.
Ex:
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Computers");
String SubStr = new String("Computers");
[Link]("Found Index : " + [Link]( SubStr ));
}
}

Output:
11

6 int length()
Returns the length of this string.
Ex:
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Computers");
[Link]([Link]());
}
}

Output:
20

7 String replace(char oldChar, char newChar)


Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
Ex:
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Computers");
[Link]([Link]('o', 'T'));
}
}

Output:
WelcTme tT CTmputers

Object Oriented Programming using Java – Sudheer Kumar


8 String substring(int beginIndex)
Returns a new string that is a substring of this string.
29
Ex:
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Computers");
[Link]([Link](11) );
}
}

Output:
Computers

9 String toLowerCase()
Converts all of the characters in this String to lower case.
Ex:
public class Test {
public static void main(String args[]) {
String Str = new String("Sudheer Kumar");
[Link]([Link]());
}
}

Output:
sudheer kumar

10 String toUpperCase()
Converts all of the characters in this String to upper case.
Ex:
public class Test {
public static void main(String args[]) {
String Str = new String("Sudheer Kumar");
[Link]([Link]());
}
}

Output:
SUDHEER KUMAR

11 String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Ex:
public class Test {
public static void main(String args[]) {
String Str = new String(" Welcome to Computers ");
[Link]([Link]() );
}
}

Output:
Welcome to Computers

Object Oriented Programming using Java – Sudheer Kumar


04. Write about classes & objects in OOP.
30
Classes and Objects
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life
entities.
Class:
 A class is user defined blueprint or prototype from which objects are created.
 It represents the set of properties or methods that are common to all objects of one type.
 There are various types of classes that are used in real time applications such as nested classes, anonymous
classes etc.
 In general, class declarations can include the following components:
Modifiers : A class can be public (or) default access.
Class name : The name should begin with initial letter (capitalized by convention).
Superclass(if any) : The name of the class’s parent (superclass), if any, preceded by the
keyword ‘extends’. A class can only extend (subclass) one parent.
Interfaces(if any) : A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword ‘implements’. A class can implement more than
one interface.
Body : The class body surrounded by curly braces, { }.

object:

 It is a basic unit of Object Oriented Programming and represents the real life entities.
 Objects correspond to things found in the real world. For example, a graphics program may have objects such
as “circle” and “square”. An online shopping system might have objects such as “customer” and “product”.
 A Java program may create many objects. An object consists of :
State : It is represented by attributes of an object.
Behavior : It is represented by methods of an object.
Identity : It gives a unique name to an object and enables one object to interact with other.

 Example of an object : dog

Identity State Behavior

Name of the dog Age Bark


Color Sleep
Eat

Declaring Objects (Also called instantiating a class)

 When an object of a class is created, the class is said to be instantiated.


 All the instances share the attributes and the behavior of the class, but the values of those attributes, i.e. the
state are unique for each object.
 A single class may have any number of instances.

Object Oriented Programming using Java – Sudheer Kumar


Example :
31
Class Dog

Dog1 State
Age
Color
Dog2

Dog3 Behavior
Bark
Sleep
Dog4 Eat

Creating an object:
 In Java, we can create objects in many ways.
 Most commonly used way to create an object is by using ‘new’ keyword.
 in the following example, ‘dog1’ object is created for the class ‘Dog’.
Dog dog1 = new Dog();
 Similarly, we can create ‘employee1’ object for the class ‘Employee’ as follows.
Employee employee1 = new Employee();
 We can also use newInstance() method to create an object.
Employee employee1 = [Link]();

Example 1:
class A{
void add(int a, int b){
[Link]("Sum = "+(a+b));
}
public static void main(String args[]){
A obj = new A();
[Link](10, 20);
} Output:
} Sum = 30

Example 2:
class Employee{
String EName;
public static void main(String args[]) {
Employee Emp1 = new Employee();
[Link] = "SUDHEER";
[Link]("Employee Name = "+[Link]);
} Output:
} Employee Name = SUDHEER

Object Oriented Programming using Java – Sudheer Kumar


05. Inheritance in Java.
32
Inheritance in Java:

 Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object. It
is an important part of OOP (Object Oriented Programming).
 The idea behind inheritance in Java is that we can create new classes that are built upon existing classes. When
we inherit from an existing class, we can reuse methods and fields of the parent class. Moreover, we can add
new methods and fields in current class also.
 Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Terms used in Inheritance:

Class: A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended
class, or child class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a
base class or a parent class.

Reusability: we can reuse the fields and methods of the existing class when we create a new class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name{


//methods and fields
}
 The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.

Java Inheritance Example:


Employee

Salary : float

Programmer

Bonus : int

 As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship
between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

Object Oriented Programming using Java – Sudheer Kumar


Example:
class Employee{ 33
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is : " + [Link]);
[Link]("Bonus of Programmer is : " + [Link]);
}
}

Output:
Programmer salary is : 40000.0
Bonus of programmer is : 10000

Types of Inheritance

Single inheritance:
A
A single super class is inherited by single sub class.
class A{..}
class B extends A{..}
B
Example:

class Animal {
void eat(){
[Link]("eating...");}
}
class Dog extends Animal {
void bark() {
[Link]("barking...");
}
}
class A{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}
}

Output:
barking...
eating...

Object Oriented Programming using Java – Sudheer Kumar


Multilevel inheritance:
A 34
A super class is inherited by sub class, and this sub
class is inherited by another sub class.
class A{..}
class B extends A{..} B
class C extends B{..}

Example:
class Animal {
void eat(){
[Link]("eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("barking...");
}
}
class BabyDog extends Dog{
void weep() {
[Link]("weeping...");
}
}
class A{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}

Output:
weeping...
barking...
eating...

Multiple inheritance:

Multiple super classes inherited by single sub class. A B


Java does not support multiple inheritance of
classes, it support multiple inheritance of interfaces.

interface A{..} C
interface B{..}
class C implements A, B{..}

Object Oriented Programming using Java – Sudheer Kumar


Hierarchical inheritance: 35
Single super class is inherited by Multiple sub
A
classes.
class A{..}
class B extends A{..}
class C extends A{..} B C D
class D extends A{..}

Example:
class Animal {
void eat() {
[Link]("eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("barking...");
}
}
class Cat extends Animal {
void meow() {
[Link]("meowing...");
}
}
class A {
public static void main(String args[]) {
Cat c=new Cat();
[Link]();
[Link]();
}
}

Output:
meowing...
eating...

Object Oriented Programming using Java – Sudheer Kumar


06. Polymorphism in Java.
36
Polymorphism:
 Polymorphism means one method with multiple implementation. Which implementation to be used
is decided at runtime depending upon the data type of the object.
 Polymorphism could be static and dynamic both.
 Method Overloading is static polymorphism and Method Overriding is dynamic polymorphism.

Method overloading (compile time polymorphism):


 In java, method Overloading means creating more than one method with same method name with
different number of parameters or different data types.
 Java identifies the methods by comparing their number of parameters or data types.

Example 1 : (different number of parameters)

class Overload_Ex{
static void sum(int x, int y){
int sum=x+y;
[Link]("sum = "+sum);
}
static void sum(int x, int y, int z){
int sum=x+y+z;
[Link]("sum = "+sum);
}
public static void main(String a[]){
sum(4,3);
sum(2,4,6);
}
}

Output:
sum = 7
sum = 12

Example 2 : (different data types)

class Overload_Ex {
static void sum(int x, int y){
int sum=x+y;
[Link]("sum = "+sum);
}
static void sum(double x, double y){
double sum=x+y;
[Link]("sum = "+sum);
}
public static void main(String a[]){
sum(4,3);
sum(2.5,4.2);
}
}

Output:
sum = 7
sum = 6.7

Object Oriented Programming using Java – Sudheer Kumar


Method overriding (run time polymorphism):
37
 In java, method Overriding means creating a method in subclass with the same name and type
signature as a method in its superclass.
 Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
 Method overriding is used for runtime polymorphism.

Example:
Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could
provide 8%, 7%, and 9% rate of interest.

Java Program:

class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class MyClass{
public static void main(String args[]){
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS();
[Link]("SBI Rate of Interest : " + [Link]());
[Link]("ICICI Rate of Interest : " + [Link]());
[Link]("AXIS Rate of Interest : " + [Link]());
}
}

Output:

SBI Rate of Interest :8


ICICI Rate of Interest :7
AXIS Rate of Interest :9

Object Oriented Programming using Java – Sudheer Kumar


07. Dynamic binding in Java.
38
Dynamic binding in Java:
 Dynamic binding in Java refers to the process of determining the specific implementation of a method at
runtime, based on the actual type of the object.
 It is also known as late binding or runtime polymorphism.
 In Java, dynamic binding is primarily associated with method overriding, where a subclass provides its own
implementation of a method that is already defined in its superclass.
 The specific method implementation to be executed is determined dynamically based on the actual type of
the object at runtime.

Working of Dynamic binding:

 Take two classes A and B into consideration, where A is B’s superclass.


 Consider that B overrides a method that was previously implemented in its parent class.
 So, even if a method is called through a reference of the superclass type A, the implementation in the
subclass will be utilised when it is called on an object of the subclass type B.

Example:

class Shape {
public void draw() {
[Link]("Drawing a shape");
}
}

class Circle extends Shape {


public void draw() {
[Link]("Drawing a circle");
}
}

class Rectangle extends Shape {


public void draw() {
[Link]("Drawing a rectangle");
}
}

public class Test {


public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
[Link]();
[Link]();
}
}

Output:

Drawing a circle
Drawing a rectangle

 In this example, we have a super class Shape and two subclasses: Circle and Rectangle.
 Each subclass overrides the draw() method inherited from the Shape class.

 In the main method, we create two shape objects: shape1 of type Circle and shape2 of type Rectangle.

 Although the reference type is Shape, the actual objects being referred to are Circle and Rectangle.

 When we call the draw() method on shape1 and shape2, the JVM dynamically binds the appropriate
version of the draw() method at runtime based on the actual type of the object.

Object Oriented Programming using Java – Sudheer Kumar


08. Abstract Methods & Abstract Classes in Java.
39
Abstraction in Java

 Abstraction is a process of hiding the implementation details and showing only functionality to the user.
 Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the message
delivery.
 Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction


 There are two ways to achieve abstraction in java
Abstract class
Interface

Abstract Method in Java


 A method which is declared as abstract and does not have implementation is known as an abstract method.
Example:
abstract void printStatus();

Example of Abstract class that has an abstract method


 In this example, Bike is an abstract class that contains only one abstract method run().
 Its implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda extends Bike{
void run(){
[Link]("running safely");
}
public static void main(String args[]){
Bike obj = new Honda();
[Link]();
}
}

Output:
running safely

Abstract class in Java

 A class which is declared as abstract is known as an abstract class.


 An abstract class may have abstract and non-abstract methods.
 It needs to be extended and its method implemented. It cannot be instantiated.
 An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.

Object Oriented Programming using Java – Sudheer Kumar


Example:
40
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){
return 7;
}
}
class ICICI extends Bank{
int getRateOfInterest(){
return 8;
}
}
class myClass{
public static void main(String args[]){
Bank b = new SBI();
[Link]("Rate of Interest is : "+[Link]()+" %");
b = new ICICI();
[Link]("Rate of Interest is: "+[Link]()+" %");
}
}

Output:
Rate of Interest is : 7 %
Rate of Interest is : 8 %

Object Oriented Programming using Java – Sudheer Kumar


Unit 3 : Interfaces, Packages & Exception Handling
41
01. Write differences between Abstract classes & Interfaces.

Abstract class:
A class that contains an abstract keyword on the declaration is known as an abstract class. It is necessary for
an abstract class to have at least one abstract method. It is possible in an abstract class to contain multiple
concrete methods.

Interface:
An interface is a sketch that is useful to implement a class. The methods used in the interface are all abstract
methods. The interface does not have any concrete method.

Differences between Abstract classes & Interfaces:

 Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.
 But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods also.

2) Doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.

5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.

6) An abstract class can extend another Java class An interface can extend another Java interface
and implement multiple Java interfaces. only.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Shape{
public abstract void draw(); void draw();
} }

Object Oriented Programming using Java – Sudheer Kumar


Example:
In the below example, we used both abstract class & interface. 42

interface A{
void a();
void b();
}
abstract class B implements A{
public void a(){
[Link]("I am a");
}
}
class M extends B{
public void b(){
[Link]("I am b");
}
}
class Test5{
public static void main(String args[]){
A obj=new M();
obj.a();
obj.b();
}
}

Output:

I am a
I am b

Object Oriented Programming using Java – Sudheer Kumar


02. Write about ‘Interfaces’ in Java.
43
Interfaces in Java

 Like a class, an interface can have methods and variables, but the methods declared in interface are by
default abstract (only method signature, no body).
 Interfaces specify what a class must do and not how. It is the blueprint of the class.
 If a class implements an interface and does not provide method bodies for all functions specified in the
interface, then class must be declared abstract.

Syntax :
interface <interface_name> {
// declare constant fields
// declare methods that abstract by default.
}

 To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the
methods in interface are declared with empty body and are public and all fields are public, static and final by
default.
 A class that implement interface must implement all the methods declared in the interface. To implement
interface use implements keyword.

Java Interface Example

In this example, the printable interface has only one method print(), and its implementation is provided in
the ‘A’ class.

interface printable{
void print();
}
class A implements printable{
public void print(){
[Link]("Hello");
}
public static void main(String args[]){
A obj = new A();
[Link]();
}
}

Output:
Hello

Object Oriented Programming using Java – Sudheer Kumar


Multiple inheritance in Java:
44
 Multiple Inheritance is a feature of object oriented concept, where a class can inherit properties of more
than one parent class. The problem occurs when there exist methods with same signature in both the super
classes and subclass.
 On calling the method, the compiler cannot determine which class method to be called. So, Java does not
support multiple inheritance of classes, It supports multiple inheritance of interfaces.

Example:

interface A{
public void myMethod();
}
interface B{
public void myOtherMethod();
}
class C implements A,B{
public void myMethod() {
[Link]("Life is Beautiful");
}
public void myOtherMethod() {
[Link]("Knowledge is Divine");
}
}
class MyClass {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}
}

Output:
Life is Beautiful
Knowledge is Divine

Object Oriented Programming using Java – Sudheer Kumar


03. Write about ‘Packages’ in Java.
45
API Packages

 Java APl(Application Program Interface) provides a large numbers of classes grouped into different packages
according to their functionality.
 Most of the time we use the packages available with the Java API.
 Following figure shows the system packages that are frequently used in the programs.

java

lang util io applet net awt

Java System Packages and Their Classes

[Link] Language support classes. They include classes for primitive types, string, math functions,
thread and exceptions.

[Link] Language utility classes such as vectors, hash tables, random numbers, data, etc.

[Link] Input/output support classes. They provide facilities for the input and output of data.

[Link] Classes for creating and implementing applets.

[Link] Classes for networking. They include classes for communicating with local computers as well
as with internet servers.

[Link] Set of classes for implementing graphical user interface. They include classes for windows,
buttons, lists, menus and so on.

Object Oriented Programming using Java – Sudheer Kumar


Create Packages in Java:
46
 A Package is a collection of related classes.
 It helps organize your classes into a folder structure and make it easy to locate and use them.
 More importantly, it helps in improving re-usability.
 Each package in Java has its unique name and organizes its classes and interfaces into a separate namespace
(or) name group.
 Although interfaces and classes with the same name cannot appear in the same package, they can appear in
different packages. This is possible by assigning a separate namespace to each package.
 Syntax:
package nameOfPackage;

Example:
// Name of the package must be same as the directory under which this file is saved
package myPackage;
public class MyClass {
public void getNames(String s) {
[Link](s);
}
}

Now we can use the MyClass class in our program.

// import 'MyClass' class from ' myPackage’


import [Link];
public class PrintName {
public static void main(String args[]) {
String name = "SUDHEER KUMAR";
MyClass obj = new MyClass();
[Link](name);
}
}

Output:
SUDHEER KUMAR

Note : [Link] must be saved inside the myPackage directory since it is a part of the package.

Object Oriented Programming using Java – Sudheer Kumar


04. Write about ‘Exception Handling’ in Java.
47
Exception Handling in Java

 The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal
flow of the application can be maintained.
 In Java, an exception is runtime error.
 Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException etc.

Advantage of Exception Handling

 The main advantage of exception handling is to maintain the normal flow of the application.
 An exception normally disrupts the normal flow of the application that is why we use exception handling. Let's
take a scenario:

statement 1;
statement 2;
statement 3; // exception occurs
statement 4;
statement 5;

 Suppose there are 5 statements in our program and there occurs an exception at statement 3, the rest of the
code will not be executed i.e. statements 4 and 5 will not be executed.
 If we perform exception handling, these statements will be executed.

Java Exception Keywords:

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

Object Oriented Programming using Java – Sudheer Kumar


Java Exception Handling Example
48
Let's see an example of Java Exception Handling where we using a try-catch statement to handle the
exception.

public class JavaExceptionExample {


public static void main(String args[]) {
try {
int data=100/0;
} catch(ArithmeticException e) {
[Link](e);
}
[Link]("rest of the code...");
}
}

Output:
Exception in thread main [Link]: / by zero
rest of the code...

Handling Multiple Exceptions:

 Whenever we needed to handle more than one exception, we needed to write more than one catch block.

import [Link];
public class Test {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
try {
int n = [Link]([Link]());
if (36%n == 0)
[Link](n + " is a factor of 36");
}
catch (ArithmeticException ex) {
[Link]("Arithmetic Exception" + ex);
}
catch (NumberFormatException ex) {
[Link]("Number Format Exception " + ex);
}
}
}

Input 1:
Sudheer Kumar
Output 1:
[Link]: For input string: "Sudheer Kumar”

Input 2:
0
Output 2:
[Link]: / by zero

Object Oriented Programming using Java – Sudheer Kumar


Common Scenarios of Java Exceptions (Java Built-in Exceptions)
There are given some scenarios where exceptions may occur. They are as follows: 49

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

int a = 50/0; // ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

String s=null;
[Link]([Link]()); // NullPointerException

3) A scenario where NumberFormatException occurs


The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that
has characters, converting this variable into digit will occur NumberFormatException.

String s="abc";
int i=[Link](s); // NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If we are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException.

int a[]=new int[5];


a[10]=50; // ArrayIndexOutOfBoundsException

5) A scenario where FileNotFoundException occurs


This Exception is raised when a file is not accessible or does not open.

File file = new File("E://[Link]"); // FileNotFoundException

6) A scenario where ClassNotFoundException occurs


This exception is raised when JVM tries to load a particular class, which is not found.

A obj = new A(); // ClassNotFoundException occurs if class ‘A’ not found

7) A scenario where IOException occurs


This exception raised when we are trying to read/write a file and don’ have permission.

File fp = new File(“[Link]”);


FileInputStream fis = new FileInputStream(fp);
[Link](); // IOException if we don’t have permission to read data

8) A scenario where NoSuchMethodException occurs


This exception raised when a program tries to call a class method that doesn’t exist.

A obj = new A();


[Link](); // NoSuchMethodException if display() method not exist

Object Oriented Programming using Java – Sudheer Kumar


50

Object Oriented Programming using Java – Sudheer Kumar


Unit 4 : Threads & Streams
51
01. Write differences between Multiprocessing & Multithreading.

Multiprocessing & Multithreading:


 Both multiprocessing and multithreading are used in computers to increase its computing power.
 The fundamental difference between multiprocessing and multithreading is that multiprocessing makes the
use of two or more CPUs to increase the computing power of the system, while multithreading creates
multiple threads of a single process to be executed in parallel to increase the performance of the system.

Multiprocessing:
 In Multiprocessing, a task is divided into multiple processes that run on multiple processors.
 When the task is over, the results from all processors are combined together to provide the final output.
 Multiprocessing increases the computing power to a great extent.
 Symmetric multiprocessing and asymmetric multiprocessing are two types of multiprocessing.

What is Multithreading?

 Multithreading refers to multiple threads being executed by a single CPU in such a way that each thread is
executed in parallel fashion and CPU/processor is switched between them using context switch.
 Multithreading is a technique to increase the performance of a processor.
 In multithreading, accessing memory addresses is easy because all of the threads share the same parent
process.

 Following are the differences between multiprocessing & multithreading:

Factor Multiprocessing Multithreading

Concept Multiple processors are added to the system to Multiple threads are created of a
increase the power of the computer. process to be executed in a parallel.

Execution Multiple processes are executed at a time. Multiple threads are executed at a time.

Categories Multiprocessing can be classified into No such classification present for


symmetric and asymmetric multiprocessing. multithreading.

Time Process creation is time-consuming. Thread creation is easy and is time


saving.

Address In multiprocessing, a separate address space is In multithreading, a common address


space created for each process. space is used for all the threads.

Resources Multiprocessing requires a significant amount Multithreading requires less time and
of time and large number of resources. few resources to create.

Object Oriented Programming using Java – Sudheer Kumar


02. What are Threads? Write different states in ‘Thread Life Cycle’? Explain.
52
Threads in Java:

 A thread is the path followed when executing a program.


 All Java programs have at least one thread, known as the main thread, which is created by the Java Virtual
Machine (JVM) when the main() method is invoked.
 Every Java thread is created and controlled by the [Link] class.

Creating a thread:

There are two ways to create a thread:


 By extending Thread class
 By implementing Runnable interface.

Thread class:

 Thread class provide constructors and methods to create and perform operations on a [Link] class
extends Object class and implements Runnable interface.
 Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)

Commonly used methods of Thread class:

public void run() : is used to perform action for a thread.


public void start() : starts the execution of the thread.
public void sleep(long miliseconds) : currently executing thread to sleep
public int getPriority() : returns the priority of the thread.
public int setPriority(int priority) : changes the priority of the thread.
public String getName() : returns the name of the thread.
public void setName(String name) : changes the name of the thread.
public Thread currentThread() : returns the reference of currently executing thread.
public int getId() : returns the id of the thread.
public [Link] getState() : returns the state of the thread.
public boolean isAlive() : tests if the thread is alive.
public void resume() : is used to resume the suspended thread(deprecated).
public void stop() : is used to stop the thread(deprecated).

Object Oriented Programming using Java – Sudheer Kumar


Runnable interface:
53
 The Runnable interface should be implemented by any class whose instances are intended to be executed by
a thread.
 Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

Java Thread Example by extending Thread class

class A extends Thread{


public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
A t1=new A();
[Link]();
}
}

Output:
thread is running...

Java Thread Example by implementing Runnable interface

class A implements Runnable{


public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
A m1=new A();
Thread t1 =new Thread(m1);
[Link]();
}
}

Output:
thread is running...

Life cycle of a thread:

 A thread can be in one of the five states.


 According to the ‘sun micro systems’, there are only 4 states in thread life cycle:
new, runnable, non-runnable (blocked) and terminated.
 But for better understanding the threads, running state is also added.

Object Oriented Programming using Java – Sudheer Kumar


 The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
54
New
Runnable
Running
Non-Runnable (Blocked)
Terminated

New

Runnable Non Runnable


(Blocked)
Running

Terminated

New
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.

Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected
it to be the running thread.

Running
The thread is in running state if the thread scheduler has selected it.

Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.

Terminated
A thread is in terminated or dead state when its run() method exits.

Object Oriented Programming using Java – Sudheer Kumar


03. Explain about ‘Thread priority’ & ‘Thread Synchronization’.
55
Priority of a Thread (Thread Priority):

 Each thread have a priority. Priorities are represented by a number between 1 and 10.
 In most cases, thread scheduler schedules the threads according to their priority (known as preemptive
scheduling).
 But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
 There are 3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
 Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.

Example of priority of a Thread:

class A extends Thread{


public void run(){
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriority());
}
public static void main(String args[]){
A m1=new A();
A m2=new A();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}

Output:

running thread name is :Thread-0


running thread priority is :10
running thread name is :Thread-1
running thread priority is :1

Object Oriented Programming using Java – Sudheer Kumar


Synchronization in Java
56
 Synchronization is the capability to control the access of multiple threads to any shared resource.
 Java Synchronization is better option where we want to allow only one thread to access the shared resource.

 The synchronization is mainly used


To prevent thread interference.
To prevent consistency problem.

 There are two types of synchronization:


Process synchronization
Thread synchronization

Thread synchronization:

 There are two types of thread synchronization mutual exclusive and inter-thread communication.
 Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
 Cooperation (Inter-thread communication in java)

Synchronized method:

 If we declare any method as synchronized, it is known as synchronized method.


 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases
it when the thread completes its task.

Example:

class Table{
synchronized void printTable(int n){ // synchronized method
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
} catch(Exception e){
[Link](e);
}
}
}
}

Object Oriented Programming using Java – Sudheer Kumar


class MyThread1 extends Thread{
Table t; 57
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}

class MyThread2 extends Thread{


Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}

public class A{
public static void main(String args[]){
Table obj = new Table(); // only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}

Output:

5
10
15
20
25
100
200
300
400
500

Object Oriented Programming using Java – Sudheer Kumar


04. Write about ‘Inter Thread Communication’.
58
Inter-thread Communication in Java

 Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with
each other.
 Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executed.
 It is implemented by following methods of Object class: wait(), notify() & notifyAll()

wait():

 The wait() method causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
 The current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.

notify():

 The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of
the implementation.

notifyAll():

 Wakes up all threads that are waiting on this object's monitor.

Importance of ITC:

 When more than one threads are executing simultaneously, sometimes they need to communicate with
each other by exchanging information with each other.
 A thread exchanges information before or after it changes its state.
 There are several situations where communication between threads is important.
 For example, suppose that there are two threads A and B. Thread B uses data produced by Thread A and
performs its task.
 If Thread B waits for Thread A to produce data, it will waste many CPU cycles.
 But if threads A and B communicate with each other when they have completed their tasks, they do not have
to wait and check each other’s status every time.
 Thus, CPU cycles will not waste.
 This type of information exchanging between threads is called Inter Thread Communication in Java.

Object Oriented Programming using Java – Sudheer Kumar


05. Write about ‘Streams’ in Java. (or) Explain Byte Stream & Character Stream classes. 59

Streams in Java:
 In Java, Input and Output operations are performed through streams. A stream is a sequence of data which is
in the form of bytes.
 A stream is linked to a physical device (keyboard, monitor etc.) by the Java I/O system.
 The same I/O classes and methods can be applied to any type of I/O device. This means that an input stream
can be used for different kinds of input: from a disk file, a keyboard, or a network socket.
 Similarly an output stream may refer to the console, a disk file, or a network connection.
 The [Link] package contains all the classes required for input & output operations. So to use the stream
classes, we must import [Link].

Standard streams:
In Java, 3 streams are created automatically. All these streams are attached with the console.

1. [Link] : Standard output stream


Following is the code to print output to the console.
[Link](“Simple message”);

2. [Link] : Standard input stream


Following is the code to get input from the console. The ASCII code for the character will be read.
int i = [Link]();
[Link]((char)i);

3. [Link] : Standard error stream


Following is the code to print output to the console.
[Link](“Error message”);

Byte Streams and Character Streams:

 Java defines two types of streams: byte and character.


 Byte streams are used while reading and writing of bytes (1 byte).
 Character streams used to read & write Unicode characters (2 bytes). The character streams are more
efficient than byte streams.

Object Oriented Programming using Java – Sudheer Kumar


60

The Byte Stream Classes:


 Byte streams are defined by using two abstract classes: InputStream and OutputStream.
 These abstract classes define many methods to handle byte streams.
 Two of the most important methods are read( ) and write( ), which read and write bytes of data.
 Some of the important byte stream classes are shown in below Table.

The Character Stream Classes:


 Character streams are defined by using two abstract classes, Reader and Writer.
 These abstract classes define many methods to handle Unicode character streams.
 Two of the most important methods are read( ) and write( ), which read and write characters of data.
 Some of the important character stream classes are shown in below table.

Object Oriented Programming using Java – Sudheer Kumar


06. Explain Read data from a file using FileInputStream & create a file using
FileOutputStream. 61
Reading & Writing of files in Java using FileInputStream & FileOutputStream:

import [Link].*;
class CopyFile {
public static void main(String args[]) throws IOException{
FileInputStream fin = new FileInputStream(args[0]);
FileOutputStream fout = new FileOutputStream(args[1]);
int i = [Link]();
while(i!=-1){
[Link](i);
i = [Link]();
}
[Link]();
[Link]();
}
}

Save the above java file as [Link] & use the following command to compile.
C:\>javac [Link]
This command will compile the above java file & the class file ‘[Link]’ will be created.
Create a text file ‘[Link]’ with some data. Now we can use the following command to copy the contents in
‘[Link]’ to ‘[Link]’.
C:\>java CopyFile [Link] [Link]

07. Explain Read data from a file using FileReader & create a file using FileWriter.

Reading & Writing of files in Java using FileReader & FileWriter:

import [Link].*;
class CopyFile {
public static void main(String args[]) throws IOException{
FileReader fr= new FileReader(args[0]);
FileWriter fw = new FileWriter(args[1]);
int i = [Link]();
while(i!=-1){
[Link](i);
i = [Link]();
}
[Link]();
[Link]();
}
}
Save the above java file as [Link] & use the following command to compile.

C:\>javac [Link]
This command will compile the above java file & the class file ‘[Link]’ will be created.
Create a text file ‘[Link]’ with some data.
Now we can use the following command to copy the contents in ‘[Link]’ to ‘[Link]’.

C:\>java CopyFile [Link] [Link]

Object Oriented Programming using Java – Sudheer Kumar


08. Write about Serialization & Deserialization of objects.
62
Serialization & Deserialization of Objects:

- Java provides a mechanism, called object serialization where an object can be represented as a sequence
of bytes that includes the object's data as well as information about the object's type and the types of
data stored in the object.

- After a serialized object has been written into a file, it can be read from the file and deserialized that is,
the type information and bytes that represent the object and its data can be used to recreate the object
in memory.

- Most impressive is that the entire process is JVM independent, meaning an object can be serialized on
one platform and deserialized on an entirely different platform.

- Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods
for serializing and deserializing an object.

- The ObjectOutputStream class contains many write methods for writing various data types, following is
one of them:

- public final void writeObject(Object x) throws IOException

- The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object:

- public final Object readObject() throws IOException, ClassNotFoundException

- In the following example, obj is the object of class Save and i is the variable in class Save.

- In the main function obj.i is assigned the value of 20.

- Using serialization, the state of object obj is stored in text file [Link]. Using deserialization, this object
is assigned to another object obj1.

Points to remember

1. If a parent class has implemented Serializable interface then child class doesn’t need to implement it.
2. Only non-static data members are saved via Serialization process.
3. Static data members are not saved via Serialization process.
4. Constructor of object is never called when an object is deserialized.
5. Associated objects must be implementing Serializable interface.

Object Oriented Programming using Java – Sudheer Kumar


63
Example program to demonstrate Serialization & Deserialization:

import [Link].*;
public class SerialDemo{
public static void main(String args[]) throws Exception{
Save obj = new Save();
obj.i = 20;

File f = new File("[Link]");


FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](obj);

FileInputStream fis = new FileInputStream(f);


ObjectInputStream ois = new ObjectInputStream(fis);
Save obj1 = (Save)[Link]();

[Link]("Value of Obj1 : " + obj1.i);


}
}
class Save implements Serializable{
int i;
}

Output:

Value of obj1 : 20

Object Oriented Programming using Java – Sudheer Kumar


64

Object Oriented Programming using Java – Sudheer Kumar


Unit 5 : GUI Programming with Swing, Event Handling
65
01. Write differences between AWT & Swing.

Differences between AWT & Swing:


 Java is one of the most in-demand programming languages for developing a variety of applications.
 Java can be used to design customized applications that are light and fast and serve a variety of purposes
ranging from web services to android applications.
 There are multiple ways to develop GUI-based applications in java, some of them are AWT and Swing.

AWT:
 AWT stands for Abstract Window Toolkit.
 It is a platform-dependent API to develop GUI (Graphical User Interface).
 It was developed by Sun Microsystems In 1995.
 It is heavy-weight in use because it is generated by the system’s host operating system.
 It contains a large number of classes and methods, which are used for creating and managing GUI.

Swing:
 Swing is a lightweight Java graphical user interface (GUI) that is part of JFC.
 Swing has platform-independent components.
 It enables the user to create buttons and scroll bars.
 Swing includes packages for creating desktop applications in Java.

Following figure shows some of the differences between AWT & Swing:

[Link] AWT Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
1
applications in Java. and is used to create various applications.

AWT components are heavy


2 Swing components are light weighted.
weighted.

3 AWT has less functionality. Swing has more functionality.

4 Execution time is more than Swing. Execution time is less than AWT.

AWT components are platform Swing components are platform


5
dependent. independent.

6 AWT follows MVC. Swing follows MVC.

AWT provides less powerful Swing provides more powerful


7
components. components.
AWT components require [Link] Swing components require [Link]
8
package. package.

AWT stands for Abstract Windows Swing is also called as JFC (Java
9
Toolkit. Foundation Classes).

Using AWT, we have to implement a


10 Swing has them built in.
lot of things ourself.

Object Oriented Programming using Java – Sudheer Kumar


02. Explain MVC architecture in Java.
66
MVC architecture:
 The Model-View-Controller (MVC) is a well-known design pattern in the web development field.
 It is way to organize our code. It specifies that a program or application shall consist of data model,
presentation information and control information.
 The MVC pattern needs all these components to be separated as different objects.
 The block diagram of MVC architecture is shown below:

 The MVC pattern architecture consists of three layers:


 Model: It represents the business layer of application. It is an object to carry the data that can also
contain the logic to update controller if data is changed.
 View: It represents the presentation layer of application. It is used to visualize the data that the model
contains.
 Controller: It works on both the model and view. It is used to manage the flow of application, i.e. data
flow in the model object and to update the view whenever data is changed.

In Java Programming, the Model contains the simple Java classes, the View used to display the data and
the Controller contains the servlets. Due to this separation the user requests are processed as follows:

1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

Advantages of MVC Architecture

 MVC has the feature of scalability that in turn helps the growth of application.
 The components are easy to maintain because there is less dependency.
 A model can be reused by multiple views that provides reusability of code.
 The developers can work with the three layers (Model, View, and Controller) simultaneously.
 Using MVC, the application becomes more understandable.
 Using MVC, each layer is maintained separately therefore we do not require to deal with massive code.
 The extending and testing of application is easier.

Object Oriented Programming using Java – Sudheer Kumar


Java Program to demonstrate MVC Architecture:

Model Layer:
67

This layer acts as a data layer for the application.


The following java program consists getter and setter methods to the EmployeeModel class.

[Link]
public class EmployeeModel{
private int ENo;
private String EName;
public int getENo() {
return ENo;
}
public void setENo(int ENo) {
[Link] = ENo;
}
public String getEName() {
return EName;
}
public void setEName(String EName) {
[Link] = EName;
}
}

View Layer:

This layer represents the visualization of data retrieved from the model.
This layer sends the requested data to the client, that is fetched from model layer by controller.

[Link]
public class EmployeeView {
public void printEmployeeDetails (String EName, int ENo){
[Link]("Employee Name : " + EName);
[Link]("Employee Number: " + ENo);
}
}

Controller Layer:

This layer acts as interface between model & view.


This layer gets the user requests from view layer & processes them.
The requests are then sent to model for data processing.
Once they are processed, the data is sent back to the controller & then displayed on the view.

[Link]

public class EmployeeController {


private EmployeeModel model;
private EmployeeView view;
public EmployeeController(EmployeeModel model, EmployeeView view) {
[Link] = model;
[Link] = view;
}

Object Oriented Programming using Java – Sudheer Kumar


public void setEName(String EName){
[Link](EName); 68
}
public String getEName(){
return [Link]();
}
public void setENo(int ENo){
[Link](ENo);
}
public int getENo(){
return [Link]();
}
public void updateView() {
[Link]([Link](), [Link]());
}
}

Java Program which contains Main class:


Following is the java program to implement the MVC Architecture:

[Link]

public class MVCMain{


public static void main(String[] args) {
EmployeeModel model = retrieveEmployeeFromDatabase();
EmployeeView view = new EmployeeView();
EmployeeController controller = new EmployeeController(model, view);
[Link]("Employee Details Before updating: ");
[Link]();
[Link]("Kishore");
[Link](104);
[Link]("Employee Details after updating: ");
[Link]();
}
private static EmployeeModel retrieveEmployeeFromDatabase(){
EmployeeModel Employee = new EmployeeModel();
[Link]("Sudheer");
[Link](102);
return Employee;
}
}

Output:

D:\>java MVCMain
Employee Details Before updating:
Employee Name : Sudheer
Employee Number: 102
Employee Details after updating:
Employee Name : Kishore
Employee Number: 104

Object Oriented Programming using Java – Sudheer Kumar


03. Write about Layout Managers in Java.
69
Layout Managers:
 These are used inorder to arrange GUI controls in particular manner.
 The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
 There are mainly four types of layout managers: BorderLayout, GridLayout, FlowLayout & CardLayout.

Java BorderLayout Manager:

The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center.
Each region (area) may contain one component only. It is the default layout of a frame or window. The
BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Following are constructors of BorderLayout:


BorderLayout() : Creates a border layout with no gaps between components.

BorderLayout(int hgap, int vgap) : Creates a border layout with given horizontal & vertical gaps
between components.

Example:

[Link]

import [Link].*;
import [Link].*;
public class Border{
JFrame f;
Border(){
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH"); // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH"); // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST"); // the button will be labeled as EAST
JButton b4 = new JButton("WEST"); // the button will be labeled as WEST
JButton b5 = new JButton("CENTER"); // the button will be labeled as CENTER
[Link](b1, [Link]); // b1 will be placed in the North Direction
[Link](b2, [Link]); // b2 will be placed in the South Direction
[Link](b3, [Link]); // b2 will be placed in the East Direction
[Link](b4, [Link]); // b2 will be placed in the West Direction
[Link](b5, [Link]); // b2 will be placed in the Center
[Link](400, 400);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}

Object Oriented Programming using Java – Sudheer Kumar


Output:
70

Java GridLayout Manager:

The Java GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.

Constructors of GridLayout class:

GridLayout() : creates a grid layout with one column per component in a row.

GridLayout(int rows, int creates a grid layout with the given rows and columns but no gaps
columns) : between the components.
GridLayout(int rows, int creates a grid layout with the given rows and columns along with
columns, int hgap, int vgap): given horizontal and vertical gaps.

Example:

[Link]

import [Link].*;
import [Link].*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
[Link](b1); [Link](b2);
[Link](b3); [Link](b4);
[Link](new GridLayout(2,2));
[Link](200,200);
[Link](true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}

Output:

Object Oriented Programming using Java – Sudheer Kumar


Java FlowLayout Manager:
The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow). It is 71
the default layout of the applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class:


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical
gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor


[Link]

import [Link].*;
import [Link].*;
public class FlowLayoutExample{
JFrame frameObj;
FlowLayoutExample(){
frameObj = new JFrame();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
// adding the buttons to frame
[Link](b1); [Link](b2);
[Link](b3); [Link](b4);
[Link](new FlowLayout());
[Link](300, 300);
[Link](true);
}
public static void main(String argvs[]){
new FlowLayoutExample();
}
}

Output:

Object Oriented Programming using Java – Sudheer Kumar


Java CardLayout Manager:

The Java CardLayout class manages the components in such a manner that only one component is visible at 72
a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout Class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class:

 public void next(Container parent): is used to flip to the next card of the given container.
 public void previous(Container parent): is used to flip to the previous card of the given container.
 public void first(Container parent): is used to flip to the first card of the given container.
 public void last(Container parent): is used to flip to the last card of the given container.
 public void show(Container parent, String name): is used to flip to the specified card with the given
name.

Example:
[Link]

import [Link].*;
import [Link].*;
import [Link].*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout crd;
JButton btn1, btn2;
Container cPane;
CardLayoutExample(){
cPane = getContentPane();
crd = new CardLayout();
[Link](crd);
btn1 = new JButton("Sudheer");
btn2 = new JButton("Kumar");
[Link](this);
[Link](this);
[Link]("a", btn1); // first card is the button btn1
[Link]("b", btn2); // first card is the button btn2
}
public void actionPerformed(ActionEvent e){
[Link](cPane);
}
public static void main(String argvs[]){
CardLayoutExample crd = new CardLayoutExample();
[Link](300, 300);
[Link](true);
[Link](EXIT_ON_CLOSE);
}
}

Object Oriented Programming using Java – Sudheer Kumar


Output:
73

When we click on the button ‘sudheer’, then the following window will be displayed with the button
‘kumar’.

Object Oriented Programming using Java – Sudheer Kumar


04. Write about ‘Event Handling’ in Java. (or) Explain ‘The Delegation event model’.
74
Event Handling (Event classes & Listener interfaces):
 Changing the state of an object is known as an event. For example, click on button, dragging mouse etc.
 The [Link] package provides many event classes and Listener interfaces for event handling.

Event Classes Listener Interfaces


ActionEvent ActionListener
MouseListener &
MouseEvent
MouseMotionListener
MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling:

Step 1: Register the component with the Listener.

To register the component, many classes provide the registration methods. For example:

o Button : public void addActionListener(ActionListener a){}

o MenuItem : public void addActionListener(ActionListener a){}

o TextField : public void addActionListener(ActionListener a){}

public void addTextListener(TextListener a){}

o TextArea : public void addTextListener(TextListener a){}

o Checkbox : public void addItemListener(ItemListener a){}

o Choice : public void addItemListener(ItemListener a){}

o List : public void addActionListener(ActionListener a){}

public void addItemListener(ItemListener a){}

Step 2: Put the Event Handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class

Object Oriented Programming using Java – Sudheer Kumar


Example: [Link]
75
import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
[Link](this);//passing current instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Sudheer Kumar");
}
public static void main(String args[]){
new AEvent();
}
}

Note: setBounds(int xaxis, int yaxis, int width, int height) method used in the above example that sets the
position of the component it may be button, textfield etc.

Output:

Delegation Event Model:

 In Java, events are a fundamental part of creating interactive applications. Events can range from mouse
clicks to keyboard inputs, and even to changes in data.
 The Delegation Event Model in Java is a way to handle events in Java, providing a way to decouple the event
source from the event listener.
 The Delegation Event Model in Java is based on a hierarchy of objects, with one object acting as the
source of the event and other objects acting as listeners that respond to those events.
 When an event occurs, the source object generates an event object and passes it to all the registered
listeners. Each listener then has the opportunity to process the event and respond accordingly.

Object Oriented Programming using Java – Sudheer Kumar


Components of Delegation Event Model:
 Event source: This is the object that generates the event. When an event occurs, the event source creates
76
an event object and passes it to all registered event listeners. Examples of event sources can be a button, a
text field, or any other component of the user interface.

 Event object: This is a Java object that encapsulates information about the event that occurred. It contains
details such as the type of event, the source of the event, and any additional data that may be relevant to
the event. The event object is passed to all registered event listeners, allowing them to respond to the event
appropriately.

 Event listener: This is an interface that defines methods for responding to events. To handle an event, an
object must implement the appropriate event listener interface and register itself with the event source.
When the event occurs, the event source calls the appropriate method on each registered event listener,
passing in the event object.

Benefits of using Delegation Event Model:

 Decoupling: The Delegation Event Model in Java decouples the event source from the event listener, which
allows you can make changes to one part of the code without affecting other parts, making your code easier
to maintain and update.

 Customization: The Delegation Event Model in Java allows for easy customization of event handling code.
You can create your own event listeners and register them with the event source.

 Scalability: Because the Delegation Event Model in Java is hierarchical, it can handle events at different
levels of abstraction. This means that you can use the same event handling code for a variety of different
components, making your code more scalable and easier to reuse.

 Flexibility: The Delegation Event Model in Java allows for event delegation, which means that events can be
handled by higher-level objects rather than the specific object that generated the event.

 Modularity: The Delegation Event Model in Java allows for a high degree of modularity in your code. You can
create separate classes for event handling code, which makes it easier to test and debug your code.

Object Oriented Programming using Java – Sudheer Kumar


05. How to handle Mouse events in Java?
77
Mouse Events:
 Mouse events are of two types.
 MouseListener handles the events when the mouse is not in motion. While MouseMotionListener handles
the events when mouse is in motion.
 MouseListener and MouseMotionListener interfaces are in [Link] package.

MouseListener Events:
 There are five types of events that MouseListener can generate.

 void mouseReleased(MouseEvent e) : Mouse key is released


 void mouseClicked(MouseEvent e) : Mouse key is pressed/released
 void mouseExited(MouseEvent e) : Mouse exited the component
 void mouseEntered(MouseEvent e) : Mouse entered the component
 void mousepressed(MouseEvent e) : Mouse key is pressed

Example: [Link]

import [Link].*;
import [Link].*;
public class MouseListenerExample extends Frame implements MouseListener{
Label label1;
MouseListenerExample(){
addMouseListener(this);
label1=new Label();
[Link](20,50,100,20);
add(label1);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

Output:

Object Oriented Programming using Java – Sudheer Kumar


MouseMotionListener Events:
 There are two types of events that MouseMotionListener can generate. 78
 Following are two abstract functions that represent these two events:

 void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the


component and dragged. Events are passed until the user releases the mouse button.
 void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point
to another within the component, without pressing any mouse buttons.

Example: [Link]

import [Link].*;
import [Link].*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
Label label1;
MouseMotionListenerExample(){
addMouseMotionListener(this);
label1=new Label();
[Link](20,50,100,20);
add(label1);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
[Link]("Mouse is dragged");
}
public void mouseMoved(MouseEvent e) {
[Link]("Mouse is moved");
}
public static void main(String[] args) {
new MouseMotionListenerExample();
}
}

Output:

Object Oriented Programming using Java – Sudheer Kumar


06. How to handle Keyboard events in Java?
79
Keyboard Events:
 The Java KeyListener is notified whenever you change the state of key.
 The KeyListener interface is found in [Link] package and it has three methods.

 void keyPressed(KeyEvent e) : Invoked when key is pressed


 void keyReleased(KeyEvent e) : Invoked when key is released
 void keyTyped(KeyEvent e) : Invoked when key has been typed

Example: [Link]
import [Link].*;
import [Link].*;
public class KeyListenerExample extends Frame implements KeyListener {
Label label1;
TextArea area;
KeyListenerExample() {
label1 = new Label();
[Link] (20, 50, 100, 20);
area = new TextArea();
[Link] (20, 80, 300, 300);
[Link](this);
add(label1);
add(area);
setSize (400, 400);
setLayout (null);
setVisible (true);
}
public void keyPressed (KeyEvent e) {
[Link] ("Key Pressed");
}
public void keyReleased (KeyEvent e) {
[Link] ("Key Released");
}
public void keyTyped (KeyEvent e) {
[Link] ("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}

Output:

Object Oriented Programming using Java – Sudheer Kumar


80

[Link] (Honours) Computer Science


(Examination at the end of Third Semester)
Object Oriented Programming using Java
(Regulation : 2023-24) – Model paper 1

Time : Three hours Maximum : 70 marks

SECTION A – (5 x 4 = 20 marks)
Answer any FIVE of the following questions.

1. Type conversion & Type casting.


2. Scope of variable.
3. Command line arguments.
4. Dynamic binding.
5. Differences between Abstract classes &
Interfaces.
6. Inter Thread Communication.
7. Serialization of objects in Java.
8. GridLayout in Java.

SECTION B – (5 x 10 = 50 marks)
Answer following questions.

UNIT 1 UNIT IV

9. a) Write differences between procedural & 12. a) Differences between Multiprocessing &
OOP concepts. Multithreading.
(or) (or)
b) Write about iterative statements in Java. b) Explain Byte Stream & Character Stream
classes.

UNIT II
UNIT V
10. a) Explain string functions in Java.
(or) 13. a) Explain MVC architecture in Java.
b) Inheritance in Java. (or)
b) How to handle Mouse & Keyboard events?

UNIT III

11. a) Interfaces in Java.


(or)
b) Write about ‘Packages’ in Java.

Object Oriented Programming using Java – Sudheer Kumar


81

[Link] (Honours) Computer Science


(Examination at the end of Third Semester)
Object Oriented Programming using Java
(Regulation : 2023-24) – Model paper 2

Time : Three hours Maximum : 70 marks

SECTION A – (5 x 4 = 20 marks)
Answer any FIVE of the following questions.

1. Switch – case statement in java.


2. Scanner class.
3. Write about arrays.
4. Overloading.
5. Built-in packages.
6. Thread priority.
7. Thread Synchronization.
8. Write differences between AWT & Swing.

SECTION B – (5 x 10 = 50 marks)
Answer following questions.

UNIT 1 UNIT IV

9. a) OOP concepts. 12. a) Thread Life Cycle.


(or) (or)
b) Operators used in Java program. b) Streams in Java.

UNIT V
UNIT II
13. a) Write about Layout Managers in Java.
10. a) Write about classes & objects. (or)
(or) b) Write about ‘Event Handling’ in Java.
b) Abstract methods & Abstract classes.

UNIT III

11. a) Write about Exception handling..


(or)
b) How to create packages in Java?

Object Oriented Programming using Java – Sudheer Kumar

You might also like