BSC 3rdsem Course5 Java
BSC 3rdsem Course5 Java
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(){
}
}
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:
Encapsulation:
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.
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
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
}
Following are some of the differences between Procedural & Object Oriented Programming.
The program is divided into small parts The program is divided into small parts called
1
called functions. objects.
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
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:
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";
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};
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:
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;
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
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
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).
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
|| Logical OR (a || b) is true
Bitwise operators
Java defines several bitwise operators that can be applied to the integer data types.
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
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
= 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
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:
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:
Output:
This is if statement.
This is the statement after if block.
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:
Output
This is else statement
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
}
Example:
Output
Excellent
Your grade is A
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
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
Flow chart:
do
statements
TRUE
condition
FALSE
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.
Method Description
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
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
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};
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
[Link](cars[0]);
Output:
Opel
Example
int myNumbers[][] = { {1, 2, 3, 4}, {5, 6, 7} };
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
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
Example:
String Methods
Here is the list of methods supported by String class:
Output:
4
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
Output:
WelcTme tT CTmputers
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:
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.
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
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.
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.
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.
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...
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:
interface A{..} C
interface B{..}
class C implements A, B{..}
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...
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
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
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:
Example:
class Shape {
public void draw() {
[Link]("Drawing a shape");
}
}
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.
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.
Output:
running safely
Output:
Rate of Interest is : 7 %
Rate of Interest is : 8 %
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.
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.
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.
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();
} }
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
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.
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
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
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
[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 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.
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);
}
}
Output:
SUDHEER KUMAR
Note : [Link] must be saved inside the myPackage directory since it is a part of the package.
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.
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.
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.
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.
Output:
Exception in thread main [Link]: / by zero
rest of the code...
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
String s=null;
[Link]([Link]()); // NullPointerException
String s="abc";
int i=[Link](s); // NumberFormatException
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.
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.
Resources Multiprocessing requires a significant amount Multithreading requires less time and
of time and large number of resources. few resources to create.
Creating a thread:
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)
Output:
thread is running...
Output:
thread is running...
New
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.
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.
Output:
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:
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);
}
}
}
}
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
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():
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.
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.
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.
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]’.
- 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:
- 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:
- In the following example, obj is the object of class Save and i is the variable in class Save.
- 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.
import [Link].*;
public class SerialDemo{
public static void main(String args[]) throws Exception{
Save obj = new Save();
obj.i = 20;
Output:
Value of obj1 : 20
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:
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.
4 Execution time is more than Swing. Execution time is less than AWT.
AWT stands for Abstract Windows Swing is also called as JFC (Java
9
Toolkit. Foundation Classes).
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.
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.
Model Layer:
67
[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:
[Link]
[Link]
Output:
D:\>java MVCMain
Employee Details Before updating:
Employee Name : Sudheer
Employee Number: 102
Employee Details after updating:
Employee Name : Kishore
Employee Number: 104
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:
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();
}
}
The Java GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.
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:
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:
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.
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);
}
}
When we click on the button ‘sudheer’, then the following window will be displayed with the button
‘kumar’.
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
To register the component, many classes provide the registration methods. For example:
Step 2: Put the Event Handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
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:
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.
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.
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.
MouseListener Events:
There are five types of events that MouseListener can generate.
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:
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:
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:
SECTION A – (5 x 4 = 20 marks)
Answer any FIVE of the following questions.
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
SECTION A – (5 x 4 = 20 marks)
Answer any FIVE of the following questions.
SECTION B – (5 x 10 = 50 marks)
Answer following questions.
UNIT 1 UNIT IV
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