[go: up one dir, main page]

0% found this document useful (0 votes)
20 views118 pages

Oop CH 5-8

Uploaded by

makkakuldip
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)
20 views118 pages

Oop CH 5-8

Uploaded by

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

Object Oriented Programming -I B.E.

4th

Chapter 5 : Object Oriented Thinking

 Class abstraction

As per dictionary, abstraction is the quality of dealing with ideas rather than events. For
example, when you consider the case of e-mail, complex details such as what happens as
soon as you send an e-mail, the protocol your e-mail server uses are hidden from the user.
Therefore, to send an e-mail you just need to type the content, mention the address of the
receiver, and click send.

Java Abstraction

 Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user. In other words, the user will have the
information on what the object does instead of how it does it. In Java programming,
abstraction is achieved using Abstract classes and interfaces.
 Java Abstract Classes
 A java class which contains the abstract keyword in its declaration is known as abstract
class.
 Java abstract classes may or may not contain abstract methods, i.e., methods without body
( public void get(); )
 But, if a class has at least one abstract method, then the class must be declared abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.
 Example :

/* File name : Employee.java */


public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;

SREZ
Page 1
Object Oriented Programming -I B.E.4th

}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

Java Abstract Methods

 If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the parent
class as an abstract.
 abstract keyword is used to declare the method as abstract.
 You have to place the abstract keyword before the method name in the method
declaration.
 An abstract method contains a method signature, but no method body.
 Instead of curly braces, an abstract method will have a semi colon (;) at the end.

Implementing Abstract Method in Java


public abstract class Employee {
private String name;
private String address;
private int number;

public abstract double computePay();


// Remainder of class definition
}

SREZ
Page 2
Object Oriented Programming -I B.E.4th

Declaring a method as abstract has two consequences −

1. The class containing it must be declared as abstract.


2. Any class inheriting the current class must either override the abstract method or
declare itself as abstract.
 Note − Eventually, a descendant class has to implement the abstract method; otherwise,
you would have a hierarchy of abstract classes that cannot be instantiated.
 Suppose Salary class inherits the Employee class, then it should implement
the computePay() method as shown below −

/* File name : Salary.java */


public class Salary extends Employee {
private double salary; // Annual salary

public double computePay() {


System.out.println("Computing salary pay for " + getName());
return salary/52;
}
// Remainder of class definition
}

 Encapsulation

 Encapsulation is one of the four fundamental OOP concepts. The other three
are inheritance, polymorphism , and abstraction.
 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. Therefore, it is also known as data hiding.
 To achieve encapsulation in Java −
 Declare the variables of a class as private.
 Provide public setter and getter methods to modify and view the variables values.

Example :

/* File name : EncapTest.java */


public class EncapTest
{
private String name;
private String idNum;
private int age;

public int getAge()


{
return age;

SREZ
Page 3
Object Oriented Programming -I B.E.4th

}
public String getName()
{
return name;
}
public String getIdNum(
{
return idNum;
}
public void setAge( int newAge
{
age = newAge;
}

public void setName(String newName)


{
name = newName;
}
public void setIdNum( String newId)
{
idNum = newId;
}
}

 The public setXXX() and getXXX() methods are the access points of the instance
variables of the EncapTest class. Normally, these methods are referred as getters and
setters. Therefore, any class that wants to access the variables should access them through
these getters and setters.
 The variables of the EncapTest class can be accessed using the following program −

/* File name : RunEncap.java */

public class RunEncap


{
public static void main(String args[])
{
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());


}
}
public class EncapTest
{
private String name;
private String idNum;
private int age;

SREZ
Page 4
Object Oriented Programming -I B.E.4th

public int getAge()


{
return age;
}
public String getName()
{
return name;
}
public String getIdNum()
{
return idNum;
}
public void setAge( int newAge)
{
age = newAge;
}
public void setName(String newName)
{
name = newName;
}
public void setIdNum( String newId)
{
idNum = newId;
}
}

Output:
Name : James Age : 20

Benefits of Encapsulation -
 The fields of a class can be made read-only or write-only.
 A class can have total control over what is stored in its fields.

Java Encapsulation: Read-Only Class


 A read-only class can have only getter methods to get the values of the attributes, there
should not be any setter method.
 Creating Read-Only Class
In this example, we defined a class Person with two getter methods getName() and getAge().
These methods can be used to get the values of attributes declared as private in the class.
// Class "Person"

class Person {
private String name = "Robert";
private int age = 21;

SREZ
Page 5
Object Oriented Programming -I B.E.4th

// Getter methods
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
public class Main {
public static void main(String args[]) {
// Object to Person class
Person per = new Person();
// Getting and printing the values
System.out.println("Name of the person is: " + per.getName());
System.out.println("Age of the person is: " + per.getAge());
}

Output
Name of the person is: Robert
Age of the person is: 21

Java Encapsulation: Write-Only Class


 A write-only class can have only setter methods to set the values of the attributes, there
should not be any getter method.
 Creating Write-Only Class
In this example, we defined a class Person with two setter methods setName() and setAge().
These methods can be used to set the values of attributes declared as private in the class.

// Class "Person"
class Person {
private String name;
private int age;
// Setter Methods
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
public class Main {
public static void main(String args[]) {
// Object to Person class
Person per = new Person();
// Setting the values

SREZ
Page 6
Object Oriented Programming -I B.E.4th

per.setName("Robert");
per.setAge(21);

 Thinking In Objects And Class Relationships

Thinking in objects and class relationships is fundamental to object-oriented programming


(OOP), a programming paradigm that revolves around the concept of "objects." In OOP,
objects are instances of classes, which encapsulate data and behavior related to a certain
entity or concept.

1. Identify real-world entities: Start by identifying the real-world entities or concepts that
your program needs to model. These could be tangible objects like cars, employees, or
buildings, or abstract concepts like transactions, accounts, or messages.

2. Define classes: Once you've identified the entities, create classes to represent them. A class
is a blueprint for creating objects, defining their properties (attributes) and behaviors
(methods).

3. Encapsulation: Encapsulate related data and behavior within classes. This means that the
internal workings of an object should be hidden from the outside world, and only a well-
defined interface (public methods) should be exposed for interacting with the object.

4. Inheritance: Use inheritance to create a hierarchy of classes where more specialized classes
(subclasses) inherit attributes and behaviors from more general classes (superclasses). This
promotes code reuse and allows for modeling of "is-a" relationships.

5. Polymorphism: Utilize polymorphism, which allows objects of different classes to be


treated as objects of a common superclass. This enables flexibility and extensibility in your
code by allowing different subclasses to implement methods differently while still adhering
to a common interface.

6. Association: Model relationships between classes using association, where objects of one
class are connected to objects of another class. Associations can be one-to-one, one-to-many,
or many-to-many.

7. Aggregation and Composition: Understand the concepts of aggregation and composition


for representing "has-a" relationships between classes. Aggregation represents a relationship
where one class contains another class as a part (loose coupling), while composition
represents a stronger form of ownership where one class is composed of other classes (strong
coupling)

8. Dependency: Manage dependencies between classes by minimizing coupling, which refers


to the degree of interdependence between classes. Aim for low coupling and high cohesion to
make your code more modular, flexible, and easier to maintain.
SREZ
Page 7
Object Oriented Programming -I B.E.4th

By thinking in terms of objects and class relationships, you can design more modular,
reusable, and maintainable software systems that closely model real-world entities and their
interactions. This approach facilitates better organization, understanding, and scalability of
your codebase.

 Java Inheritance

 Inheritance is a process where one class acquires the properties (methods and attributes)
of another. With the use of inheritance, the information is made manageable in a
hierarchical order.
 The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).

Need of Java Inheritance


 Code Reusability: The basic need of an inheritance is to reuse the features. If you have
defined some functionality once, by using the inheritance you can easily use them in other
classes and packages.
 Extensibility: The inheritance helps to extend the functionalities of a class. If you have a
base class with some functionalities, you can extend them by using the inheritance in the
derived class.
 Implantation of Method Overriding: Inheritance is required to achieve one of the concepts
of Polymorphism which is Method overriding.
 Achieving Abstraction: Another concept of OOPs that is abstraction also needs
inheritance.

implementation of Java Inheritance

To implement (use) inheritance in Java, the extends keyword is used. It inherits the properties
(attributes or/and methods) of the base class to the derived class. The word "extends" means
to extend functionalities i.e., the extensibility of the features.
Syntax to implement inheritance

class Super {

.....

.....

class Sub extends Super {

.....

.....

SREZ
Page 8
Object Oriented Programming -I B.E.4th

Example

Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.

class Calculation {

int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

 In the given program, when an object to My_Calculation class is created, a copy of the
contents of the superclass is made within it. That is why, using the object of the subclass
you can access the members of a superclass.
 The Superclass reference variable can hold the subclass object, but using that variable you
can access only the members of the superclass, so to access the members of both classes it
is recommended to always create reference variable to the subclass.
 If you consider the above program, you can instantiate the class as given below. But using
the superclass reference variable ( cal in this case) you cannot call the
method multiplication(), which belongs to the subclass My_Calculation.

The super Keyword :

SREZ
Page 9
Object Oriented Programming -I B.E.4th

The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.

 It is used to differentiate the members of superclass from the members of subclass, if they
have same names.
 It is used to invoke the superclass constructor from subclass.

Differentiating the Members

If a class is inheriting the properties of another class. And if the members of the superclass
have the names same as the sub class, to differentiate these variables we use super keyword
as shown below.

super.variable
super.method();

Invoking Superclass Constructor

If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the superclass. But if you want to call a parameterized constructor of
the superclass, you need to use the super keyword as shown below.
super(values);
Example :
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String args[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}

instanceof keyword is used to check whether an object belongs to a particular class or its
subclass. It's a binary operator that returns true if the object is an instance of the specified
class, or false otherwise.

class Animal {}

SREZ
Page 10
Object Oriented Programming -I B.E.4th

class Dog extends Animal {}

let animal = new Animal();


let dog = new Dog();
console.log(animal instanceof Animal); // Output: true
console.log(dog instanceof Animal); // Output: true
console.log(dog instanceof Dog); // Output: true
console.log(animal instanceof Dog); // Output: false

In this example, we have two classes: Animal and Dog, where Dog is a subclass of Animal.
We create instances of both classes (animal and dog), and then we use the instanceof operator
to check their types.

 Types of Java Inheritance

In Java, there are mainly three types of inheritances Single, Multilevel, and Hierarchical.
Java does not support Multiple and Hybrid inheritance.

SREZ
Page 11
Object Oriented Programming -I B.E.4th

A very important fact to remember is that Java does not support multiple and hybrid
inheritances. This means that a class cannot extend more than one class. Therefore following
is illegal −

1. Java Single Inheritance

The inheritance in which there is only one base class and one derived class is known as single
inheritance. The single (or, single-level) inheritance inherits data from only one base class to
only one derived class.

Example
class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}

public class Main extends One {


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

// Calling method
obj.printOne();
}
}

Output
printOne() method of One class.

2. Java Multilevel Inheritance

The inheritance in which a base class is inherited to a derived class and that derived class is
further inherited to another derived class is known as multi-level inheritance. Multilevel
inheritance involves multiple base classes.

Example
class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}
class Two extends One {
public void printTwo() {
System.out.println("printTwo() method of Two class.");

SREZ
Page 12
Object Oriented Programming -I B.E.4th

public class Main extends Two {


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

// Calling methods
obj.printOne();
obj.printTwo();
}
}

Output
printOne() method of One class.
printTwo() method of Two class.

3. Java Hierarchical Inheritance

The inheritance in which only one base class and multiple derived classes is known as
hierarchical inheritance.

Example
// Base class
class One {
public void printOne() {
System.out.println("printOne() Method of Class One");
}
}

// Derived class 1
class Two extends One {
public void printTwo() {
System.out.println("Two() Method of Class Two");
}
}

// Derived class 2
class Three extends One {
public void printThree() {
System.out.println("printThree() Method of Class Three");
}
}
SREZ
Page 13
Object Oriented Programming -I B.E.4th

// Testing CLass
public class Main {
public static void main(String args[]) {
Two obj1 = new Two();
Three obj2 = new Three();

//All classes can access the method of class One


obj1.printOne();
obj2.printOne();
}
}

Output
printOne() Method of Class One
printOne() Method of Class One

 Aggregation :

An aggregation is a relationship between two classes where one class contains an instance of
another class. For example, when an object A contains a reference to another object B or we
can say Object A has a HAS-A relationship with Object B, then it is termed as Aggregation in
Java Programming.

Use of Java Aggregation

Aggregation in Java helps in reusing the code. Object B can have utility methods and which
can be utilized by multiple objects. Whichever class has object B then it can utilize its
methods.

Example

In this example, we're creating few classes like Vehicle, Speed. A Van class is defined which
extends Vehicle class and has a Speed class object. Van class inherits properties from Vehicle
class and Speed being its property, we're passing it from caller object. In output, we're
printing the details of Van object.

package com.tutorialspoint;
class Vehicle{
private String vin;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;

SREZ
Page 14
Object Oriented Programming -I B.E.4th

}
class Speed{
private double max;
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
}
class Van extends Vehicle {
private Speed speed;
public Speed getSpeed() {
return speed;
}
public void setSpeed(Speed speed) {
this.speed = speed;
}
public void print() {
System.out.println("Vin: " +this.getVin() + ", Max Speed: " + speed.getMax() );
}
}
public class Tester {
public static void main(String[] args) {
Speed speed = new Speed();
speed.setMax(120);
Van van = new Van();
van.setVin("abcd1233");
van.setSpeed(speed);
van.print();
}
}

Output
Vin: abcd1233, Max Speed: 120.0

 Polymorphism
Polymorphism is the ability of an object to take on many forms. Polymorphism is an
important feature of Java OOP concepts and it allows us to perform multiple operations by
using the single name of any method (interface). Any Java object that can pass more than one
IS-A test is considered to be polymorphic. In Java, all java objects are polymorphic since any
object will pass the IS-A test for its own type and for the class Object.

Use of Polymorphism in Java

 The most common use of polymorphism in OOP occurs when a parent class reference is
used to refer to a child class object.

SREZ
Page 15
Object Oriented Programming -I B.E.4th

 It is important to know that the only possible way to access an object is through
a reference variable. A reference variable can be of only one type. Once declared, the type
of a reference variable cannot be changed.
 The reference variable can be reassigned to other objects provided that it is not declared
final. The type of the reference variable would determine the methods that it can invoke
on the object.
 A reference variable can refer to any object of its declared type or any subtype of its
declared type. A reference variable can be declared as a class or interface type.

Example :

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above examples −

 A Deer IS-A Animal


 A Deer IS-A Vegetarian
 A Deer IS-A Deer
 A Deer IS-A Object

Polymorphism Implementation
interface Vegetarian{}
class Animal{}
public class Deer extends Animal implements Vegetarian{
public static void main(String[] args) {
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
System.out.println(d instanceof Deer);
System.out.println(a instanceof Deer);
System.out.println(v instanceof Deer);
System.out.println(o instanceof Deer);
}
}
Output
true
true
true
true

Types of Java Polymorphism


There are two types of polymorphism in Java:
1. Compile Time Polymorphism
2. Run Time Polymorphism

SREZ
Page 16
Object Oriented Programming -I B.E.4th

Compile Time Polymorphism in Java :

Compile-time polymorphism is also known as static polymorphism and it is implemented


by method overloading

Example:

// Java Example: Compile Time Polymorphism


public class Main {
// method to add two integers
public int addition(int x, int y) {
return x + y;
}
// method to add three integers
public int addition(int x, int y, int z) {
return x + y + z;
}
// method to add two doubles
public double addition(double x, double y) {
return x + y;
}
// Main method
public static void main(String[] args) {
// Creating an object of the Main method
Main number = new Main();
// calling the overloaded methods
int res1 = number.addition(444, 555);
System.out.println("Addition of two integers: " + res1);
int res2 = number.addition(333, 444, 555);
System.out.println("Addition of three integers: " + res2);
double res3 = number.addition(10.15, 20.22);
System.out.println("Addition of two doubles: " + res3);
}
}
Output
Addition of two integers: 999
Addition of three integers: 1332
Addition of two doubles: 30.369999999999997

Run Time Polymorphism in Java :

Run time polymorphism is also known as dynamic method dispatch and it is implemented by
the method overloading

Example:

// Java Example: Run Time Polymorphism


SREZ
Page 17
Object Oriented Programming -I B.E.4th

class Vehicle {
public void displayInfo() {
System.out.println("Some vehicles are there.");
}
}

class Car extends Vehicle {


// Method overriding
@Override
public void displayInfo() {
System.out.println("I have a Car.");
}
}

class Bike extends Vehicle {


// Method overriding
@Override
public void displayInfo() {
System.out.println("I have a Bike.");
}
}

public class Main {


public static void main(String[] args) {
Vehicle v1 = new Car(); // Upcasting
Vehicle v2 = new Bike(); // Upcasting

// Calling the overridden displayInfo() method of Car class


v1.displayInfo();

// Calling the overridden displayInfo() method of Bike class


v2.displayInfo();
}
}

Output
I have a Car.
I have a Bike.

 Aggregation

An aggregation is a relationship between two classes where one class contains an instance of
another class. For example, when an object A contains a reference to another object B or we
can say Object A has a HAS-A relationship with Object B, then it is termed as Aggregation in
Java Programming.

Use of Java Aggregation -

SREZ
Page 18
Object Oriented Programming -I B.E.4th

Aggregation in Java helps in reusing the code. Object B can have utility methods and
which can be utilized by multiple objects. Whichever class has object B then it can
utilize its methods.

 Primitive Data Types And Wrapper Classes

1. Primitive Data Types:

 Primitive data types are the most basic data types provided by a programming language.
 They are predefined by the language and typically represent simple values such as
integers, floating-point numbers, characters, and boolean values.
 Examples of primitive data types in Java include:
- `int`: Represents integer numbers.
- `double`: Represents floating-point numbers.
- `char`: Represents a single character.
- `boolean`: Represents true or false values.
 Primitive data types are not objects and do not have methods or properties associated with
them.
 They are used to store simple values directly in memory.

2. Wrapper Classes:

 Wrapper classes in Java are classes that provide a way to use primitive data types as
objects.
 Each primitive data type in Java has a corresponding wrapper class that allows you to
perform various operations on the primitive data type as if it were an object.
 Wrapper classes are part of the `java.lang` package and are used to convert primitive data
types into objects.
 Examples of wrapper classes in Java include:
- `Integer`: Wraps an `int` value.
- `Double`: Wraps a `double` value.
- `Character`: Wraps a `char` value.
- `Boolean`: Wraps a `boolean` value.
 Wrapper classes provide methods to perform conversions, comparisons, and other
operations on primitive data types.
 They are often used in scenarios where objects are required, such as collections like
`ArrayList` or when working with libraries that expect objects rather than primitives.
 Wrapper classes are useful when you need to treat primitive data types as objects, such as
when using collections like `ArrayList` or when passing values to methods that expect
objects. They provide additional functionality and flexibility compared to primitive data
types alone.

 Big integer and Big decimal class

`BigInteger` and `BigDecimal` are classes in Java that belong to the `java.math` package and
are used for handling large numbers and arbitrary-precision arithmetic, which means they can
handle numbers with more digits than primitive data types like `int` or `double` can represent.

SREZ
Page 19
Object Oriented Programming -I B.E.4th

1. BigInteger:

 The `BigInteger` class is used to represent arbitrary-precision integers.


 It allows you to perform arithmetic operations (addition, subtraction, multiplication,
division) on integers of any size.
 BigInteger objects are immutable, meaning their values cannot be changed once they are
created.
 This class is useful when dealing with extremely large integer values that cannot be
represented using primitive data types like `int` or `long`.
 Example :

```java

import java.math.BigInteger;

public class Main {

public static void main(String[] args) {

BigInteger bigInteger1 = new BigInteger("123456789012345678901234567890");

BigInteger bigInteger2 = new BigInteger("987654321098765432109876543210");

BigInteger result = bigInteger1.add(bigInteger2);

System.out.println(result); // Prints: 1111111110111111111011111111100

2. BigDecimal :

 The `BigDecimal` class is used to represent arbitrary-precision decimal numbers.


 It allows you to perform arithmetic operations (addition, subtraction, multiplication,
division) with arbitrary precision.
 BigDecimal` objects are immutable, similar to `BigInteger`.
 This class is useful when dealing with precise decimal calculations where floating-point
arithmetic may introduce rounding errors
 Example usage:

```java

import java.math.BigDecimal;

public class Main {

SREZ
Page 20
Object Oriented Programming -I B.E.4th

public static void main(String[] args) {

BigDecimal bigDecimal1 = new BigDecimal("123.456");

BigDecimal bigDecimal2 = new BigDecimal("987.654");

BigDecimal result = bigDecimal1.add(bigDecimal2);

System.out.println(result); // Prints: 1111.11

Both `BigInteger` and `BigDecimal` provide methods for various mathematical operations
and comparisons, allowing precise manipulation of large integer and decimal values without
losing accuracy due to limitations of primitive data types.

 String Class

 Strings are a sequence of characters. In Java programming language, strings are treated
as objects.
 The Java platform provides the String class to create and manipulate strings.
 Creating Strings
 The most direct way to create a string is to write −
String greeting = "Hello world!";
 Whenever it encounters a string literal in your code, the compiler creates a String object
with its value in this case, "Hello world".
 As with any other object, you can create String objects by using the new keyword and
a constructor. The String class has 11 constructors that allow you to provide the initial
value of the string using different sources, such as an array of characters.
 Example
public class StringDemo
{
public static void main(String args[])
{
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
Output :
Hello

String Length :

SREZ
Page 21
Object Oriented Programming -I B.E.4th

 Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the
number of characters contained in the string object.
 The following program is an example of length(), method String class.
 Example
public class StringDemo
{
public static void main(String args[])
{
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}

Output
String Length is : 17

Concatenating Strings
 The String class includes a method for concatenating two strings −
string1.concat(string2);
 This returns a new string that is string1 with string2 added to it at the end. You can also
use the concat() method with string literals, as in −
"My name is ".concat("Zara");
 Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
 which results in −
"Hello, world!"
 Example

public class StringDemo


{
public static void main(String args[])
{
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}

Output
Dot saw i was Tod

Creating Format Strings

 You have printf() and format() methods to print output with formatted numbers. The
String class has an equivalent class method, format(), that returns a String object rather
than a PrintStream object.

SREZ
Page 22
Object Oriented Programming -I B.E.4th

 Using String's static format() method allows you to create a formatted string that you can
reuse, as opposed to a one-time print statement. For example, instead of −
 Example to Create Formatted Strings in Java

System.out.printf("The value of the float variable is " +


"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);

You can write −

String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);

String Comparison

String comparison in Java is a fundamental operation used to determine the equality or


ordering of strings. There are several ways to compare strings in Java:

1. Using `equals()` method:


 The `equals()` method of the `String` class compares the content of two strings for
equality.
 It returns `true` if the two strings have the same characters in the same order, otherwise it
returns `false`.
 Example:

String str1 = "hello";


String str2 = "world";
String str3 = "hello";

System.out.println(str1.equals(str2)); // Outputs: false


System.out.println(str1.equals(str3)); // Outputs: true

2. Using `compareTo()` method:


 The `compareTo()` method of the `String` class compares two strings lexicographically
(based on the Unicode values of their characters).
 It returns a negative integer if the first string is lexicographically less than the second
string, zero if the two strings are equal, and a positive integer if the first string is
lexicographically greater than the second string.
 Example:

String str1 = "apple";

SREZ
Page 23
Object Oriented Programming -I B.E.4th

String str2 = "banana";

System.out.println(str1.compareTo(str2)); // Outputs: -1
System.out.println(str2.compareTo(str1)); // Outputs: 1

3. Using `equalsIgnoreCase()` method:


 The `equalsIgnoreCase()` method of the `String` class compares two strings ignoring their
case (uppercase/lowercase).
 It returns `true` if the two strings are equal, ignoring case, otherwise it returns `false`.
 Example:

String str1 = "HELLO";


String str2 = "hello";

System.out.println(str1.equalsIgnoreCase(str2)); // Outputs: true

4. Using `==` operator:


 The `==` operator compares the memory addresses of two string objects, not their
content.
 When comparing strings with `==`, you are checking whether they refer to the same
object in memory, not whether their content is the same.
 Example:

String str1 = "hello";


String str2 = "hello";

System.out.println(str1 == str2); // Outputs: true

It's important to choose the appropriate method based on the specific requirements of your
comparison (e.g., content equality, lexicographical ordering, case-insensitive equality).

String Upper and lowercase

In Java, there are methods available in the `String` class to convert the case of strings to
uppercase or lowercase. These methods are useful for manipulating strings and performing
case-insensitive comparisons. Here are the methods:

1. toUpperCase():

 This method converts all of the characters in the invoking `String` object to uppercase
using the rules of the default locale.
 Syntax:
String upperCaseString = originalString.toUpperCase();
Example:

String originalString = "Hello, World!";


String upperCaseString = originalString.toUpperCase();

SREZ
Page 24
Object Oriented Programming -I B.E.4th

System.out.println(upperCaseString); // Output: HELLO, WORLD!

2.toLowerCase():
 This method converts all of the characters in the invoking `String` object to lowercase
using the rules of the default locale.
 Syntax:
String lowerCaseString = originalString.toLowerCase();
Example:

String originalString = "Hello, World!";


String lowerCaseString = originalString.toLowerCase();
System.out.println(lowerCaseString); // Output: hello, world!

These methods return a new `String` object with the characters converted to uppercase or
lowercase, leaving the original `String` object unchanged, as `String` objects in Java are
immutable.

Searching Strings

In Java, you can perform searching operations on strings using various methods provided by
the `String` class. Here are some commonly used methods for searching strings:

1. indexOf():
 This method returns the index of the first occurrence of a specified substring within the
string. If the substring is not found, it returns -1.
 Syntax:
int index = str.indexOf(substring);
Example:

String str = "Hello, World!";


int index = str.indexOf("World");
System.out.println(index); // Output: 7

2. lastIndexOf():
 This method returns the index of the last occurrence of a specified substring within the
string. If the substring is not found, it returns -1.
 Syntax:
int lastIndex = str.lastIndexOf(substring);
Example:

String str = "Hello, World!";


int lastIndex = str.lastIndexOf("o");
System.out.println(lastIndex); // Output: 8

3. startsWith():

SREZ
Page 25
Object Oriented Programming -I B.E.4th

 This method checks whether the string starts with a specified prefix.
 Syntax:
boolean startsWith = str.startsWith(prefix);
Example:

String str = "Hello, World!";


boolean startsWithHello = str.startsWith("Hello");
System.out.println(startsWithHello); // Output: true

4. endsWith():
 This method checks whether the string ends with a specified suffix.
 Syntax:
boolean endsWith = str.endsWith(suffix);
- Example:

String str = "Hello, World!";


boolean endsWithWorld = str.endsWith("World!");
System.out.println(endsWithWorld); // Output: true

 String Buffer and String Builder Classes

 The StringBuffer and StringBuilder classes are used when there is necessity
to make a lot of modifications to Strings of characters.
 Unlike Strings, objects of type StringBuffer and String builder can be modified
over and over again without leaving behind a lot of new unused objects.
 The StringBuilder class was introduced as of Java 5 and the main difference
between the StringBuffer and StringBuilder is that StringBuilders methods are
not thread safe (not synchronised).
 It is recommended to use StringBuilder whenever possible because it is faster
than StringBuffer. However, if the thread safety is necessary, the best option is
StringBuffer objects.
 Example

public class Test


{
public static void main(String args[])
{
StringBuffer sBuffer = new StringBuffer("test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
}
}

Output
test String Buffer

StringBuffer Methods

SREZ
Page 26
Object Oriented Programming -I B.E.4th

 Methods overloading

When a class has two or more methods by the same name but different parameters, at the
time of calling based on the parameters passed respective method is called (or respective
method body will be bonded with the calling line dynamically). This mechanism is known as
method overloading.
Advantage of Method Overloading
 Method overloading improves the code readability and reduces code redundancy.
Method overloading also helps to achieve compile-time polymorphism.
Example
 If you observe the following example, Here we have created a class named Tester this
class has two methods with same name (add) and return type, the only difference is
the parameters they accept (one method accepts two integer variables and other
accepts three integer variables).

class Calculator
{
public static int add(int a, int b)
{
return a + b;
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}

SREZ
Page 27
Object Oriented Programming -I B.E.4th

When you invoke the add() method based on the parameters you pass respective method body
gets executed.

int result = Calculator.add(1,2); // returns 3;


result = Calculator.add(1,2,3); // returns 6;

Different Ways of Java Method Overloading


 Method overloading can be achieved using following ways while having same name
methods in a class.
o Use different number of arguments
o Use different type of arguments

Invalid Ways of Java Method Overloading

 Method overloading cannot be achieved using following ways while having same
name methods in a class. Compiler will complain of duplicate method presence.
o Using different return type
o Using static and non-static methods

Method Overloading: Different Number of Arguments


You can implement method overloading based on the different number of arguments.

Example: Different Number of Arguments (Static Methods)

In this example, we've created a Calculator class having two static methods with same name
but different arguments to add two and three int values respectively. In main() method, we're
calling these methods and printing the result. Based on the type of arguments passed,
compiler decides the method to be called and result is printed accordingly.

package com.tutorialspoint;
class Calculator
{
public static int add(int a, int b)
{
return a + b;
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}

public class Tester


{
public static void main(String args[])
{
System.out.println(Calculator.add(20, 40));
System.out.println(Calculator.add(40, 50, 60));
}

SREZ
Page 28
Object Oriented Programming -I B.E.4th

Output
60
150

 Method Overriding

 Method overriding allows us to achieve run-time polymorphism and is used for writing
specific definitions of a subclass method that is already defined in the superclass.
 The method is superclass and overridden method in the subclass should have the same
declaration signature such as parameters list, type, and return type.

Usage of Java Method Overriding


 Method overriding is used for achieving run-time polymorphism.
 Method overriding is used for writing specific definition of a subclass method (this
method is known as the overridden method).
 Example

class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}

class Dog extends Animal


{
public void move()
{
System.out.println("Dogs can walk and run");
}
}

public class TestDog


{
public static void main(String args[])
{
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run

SREZ
Page 29
Object Oriented Programming -I B.E.4th

 In the above example, you can see that even though b is a type of Animal it runs the move
method in the Dog class.
 The reason for this is: In compile time, the check is made on the reference type. However,
in the runtime, JVM figures out the object type and would run the method that belongs to
that particular object.
 Therefore, in the above example, the program will compile properly since Animal class
has the method move. Then, at the runtime, it runs the method specific for that object.

Consider the following example −


class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}

class Dog extends Animal


{
public void move()
{
System.out.println("Dogs can walk and run");
}
public void bark()
{
System.out.println("Dogs can bark");
}
}
public class TestDog
{
public static void main(String args[])
{
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
b.bark();
}
}
Output
TestDog.java:26: error: cannot find symbol
b.bark();
^
symbol: method bark()

location: variable b of type Animal

SREZ
Page 30
Object Oriented Programming -I B.E.4th

1 error

This program will throw a compile time error since b's reference type Animal doesn't have a
method by the name of bark.

Rules for Method Overriding


 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the
sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public
or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not.
 However, the overriding method should not throw checked exceptions that are new or
broader than the ones declared by the overridden method.
 The overriding method can throw narrower or fewer exceptions than the overridden
method.
 Constructors cannot be overridden.

Java Method and Constructor Overriding


In Java, each class has a different name and the constructor's name is the same as the class
name. Thus, we cannot override a constructor as they cannot have the same name.

Java Method Overriding: Using the super Keyword


When invoking a superclass version of an overridden method the super keyword is used.

Example: Using the super Keyword

class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
public void move()
{
super.move(); // invokes the super class method
SREZ
Page 31
Object Oriented Programming -I B.E.4th

System.out.println("Dogs can walk and run");


}
}

public class TestDog


{
public static void main(String args[])
{
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}

Output
Animals can move
Dogs can walk and run

 Dynamic Binding

 Dynamic binding refers to the process in which linking between method call and method
implementation is resolved at run time (or, a process of calling an overridden method at
run time).
 Dynamic binding is also known as run-time polymorphism or late binding. Dynamic
binding uses objects to resolve binding.
 Characteristics of Java Dynamic Binding
 Linking − Linking between method call and method implementation is resolved at run
time.
 Resolve mechanism − Dynamic binding uses object type to resolve binding.
 Example − Method overriding is the example of Dynamic binding.
 Type of Methods − Virtual methods use dynamic binding.

Example
In this example, we've created two classes Animal and Dog where Dog class extends Animal
class. In main() method, we're using Animal class reference and assign it an object of Dog
class to check Dynamic binding effect.

package com.tutorialspoint;

class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}

class Dog extends Animal


{
public void move()
SREZ
Page 32
Object Oriented Programming -I B.E.4th

{
System.out.println("Dogs can walk and run");
}
}

public class Tester


{
public static void main(String args[])
{
Animal a = new Animal(); // Animal reference and object
// Dynamic Binding
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}
Output

Animals can move


Dogs can walk and run

 In the above example, you can see that even though b is a type of Animal it runs the move
method in the Dog class.
 The reason for this is: In compile time, the check is made on the reference type. However,
in the runtime, JVM figures out the object type and would run the method that belongs to
that particular object.
 Therefore, in the above example, the program will compile properly since Animal class
has the method move. Then, at the runtime, it runs the method specific for that object.

Java Dynamic Binding: Using the super Keyword

 When invoking a superclass version of an overridden method the super keyword is used
so that we can utilize parent class method while using dynamic binding.

Example

In this example, we've created two classes Animal and Dog where Dog class extends Animal
class. Dog class overrides the move method of its super class Animal. But it calls parent
move() method using super keyword so that both move methods are called when child
method is called due to dynamic binding. In main() method, we're using Animal class
reference and assign it an object of Dog class to check Dynamic binding effect.

class Animal
{
public void move()
{
System.out.println("Animals can move");
}

SREZ
Page 33
Object Oriented Programming -I B.E.4th

}
class Dog extends Animal
{
public void move()
{
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog
{
public static void main(String args[])
{
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}

Output
Animals can move
Dogs can walk and run

 Java Static Binding


 Static binding refers to the process in which linking between method call and method
implementation is resolved at compile time. Static binding is also known as compile-time
binding or early binding.

Characteristics of Java Static Binding


 Linking − Linking between method call and method implementation is resolved at
compile time.
 Resolve mechanism − Static binding uses type of the class and fields to resolve binding.
 Example − Method overloading is the example of Static binding.
 Type of Methods − private, final and static methods and variables uses static binding.

Example of Java Static Binding

In this example, we've created a Calculator class having two static methods with same name
but different arguments to add two and three int values respectively. In main() method, we're
calling these methods and printing the result. Based on the number of arguments passed,
compiler decides the method using static binding which method is to be called and result is
printed accordingly.

package com.tutorialspoint;

class Calculator
{
public static int add(int a, int b)
{
return a + b;

SREZ
Page 34
Object Oriented Programming -I B.E.4th

}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}

public class Tester


{
public static void main(String args[])
{
System.out.println(Calculator.add(20, 40));
System.out.println(Calculator.add(40, 50, 60));
}
}

Output
60
150

 java instanceof operator]

 The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
 The instanceof in java is also known as type comparison operator because it compares
the instance with type. It returns either true or false. If we apply the instanceof operator
with any variable that has null value, it returns false.

Example
class Simple
{
public static void main(String args[])
{
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}

Output
true

 Casting Objects

 A cast, instructs the compiler to change the existing type of an object reference to another
type.
 In Java, all casting will be checked both during compilation and during execution to
ensure that they are legitimate.

SREZ
Page 35
Object Oriented Programming -I B.E.4th

 An attempt to cast an object to an incompatible object at runtime will results in


ClassCastException.
 A cast can be used to narrow or downcast the type of a reference to make it more specific

 The ArrayList Class

• The ArrayList class is part of the java.util package


• An ArrayList is like an array, but it automatically grows and shrinks as elements are
added or deleted (so, there are never ANY empty elements in an ArrayList)
• Items can be inserted or removed with a single method call
• It stores references to the Object class, which allows it to store ANY kind of object –
so, you can store different types in the same array
• However, this means that you cannot store primitive types (int, double, char, boolean)
in an ArrayList. Instead, you would store their Wrapper Class equivalents:
• Integer
• Double
• Character
• Boolean
• Syntax
• Import java.util.ArrayList
• ArrayList is a class, so you must instantiate an object of it
• If you want to add an object (such as a String) to an ArrayList, there is no special
syntax. However, if you want to add a “primitive type” (such as int, double, char), you
must add using a wrapper class. Commonly used ArrayList methods:
• add (obj) // adds obj at the end of the list
• add (index, obj) // adds obj at the specified index
• set (index, obj) // replaces the value at the specified index with obj
• get (index) // returns the object at the specified index
• indexOf(obj) // finds the index of the specified obj
• remove (index) // deletes the object at the specified index
• size ( ) // returns the size of the ArrayList
• Demo: ArrayListDemo

Methods of the `ArrayList` class in Java:

1. `add(E element)`: Adds the specified element to the end of the list.

```java
ArrayList<String> list = new ArrayList<>();
list.add("apple");
```

2. `add(int index, E element)`: Inserts the specified element at the specified position in
the list.

```java
list.add(1, "banana");
```

SREZ
Page 36
Object Oriented Programming -I B.E.4th

3. `remove(Object obj)`: Removes the first occurrence of the specified element from
the list.

```java
list.remove("apple");
```

4. `remove(int index)`: Removes the element at the specified position in the list.

```java
list.remove(0);
```

5. `get(int index)`: Returns the element at the specified position in the list.

```java
String fruit = list.get(0);
```

6. `set(int index, E element)`: Replaces the element at the specified position in the list
with the specified element.

```java
list.set(0, "orange");
```

7. `size()`: Returns the number of elements in the list.

```java
int size = list.size();
```

8. `clear()`: Removes all of the elements from the list.

```java
list.clear();
```

9. `isEmpty()`: Returns true if the list contains no elements.

```java
boolean empty = list.isEmpty();
```

10. `contains(Object obj)`: Returns true if the list contains the specified element.

```java
boolean contains = list.contains("apple");

SREZ
Page 37
Object Oriented Programming -I B.E.4th

```

11. `indexOf(Object obj)`: Returns the index of the first occurrence of the specified
element in the list, or -1 if the list does not contain the element.

```java
int index = list.indexOf("banana");
```

12. `lastIndexOf(Object obj)`: Returns the index of the last occurrence of the specified
element in the list, or -1 if the list does not contain the element.

```java
int lastIndex = list.lastIndexOf("banana");
```

These are some of the most commonly used methods of the `ArrayList` class in Java.
There are other methods available as well for various purposes.

 The protected data and methods.

 In Java, `protected` is one of the four access modifiers used to control the visibility of
classes, methods, and variables.
 When a member (field or method) is declared `protected`, it can be accessed by classes in
the same package and by subclasses (regardless of whether they are in the same package
or different packages).

1. Protected Data (Fields):


 A `protected` field can be accessed within the same package and by subclasses, even if
they are in different packages.
 Other classes outside the package (which are not subclasses) cannot access the `protected`
field directly.

```java
package com.example.package1;

public class Parent {


protected int protectedField;
}
```

```java
package com.example.package2;

import com.example.package1.Parent;

public class Child extends Parent {


void accessProtectedField() {

SREZ
Page 38
Object Oriented Programming -I B.E.4th

// Accessing protectedField from the Parent class


int value = protectedField;
}
}

2. Protected Methods:
 A `protected` method can be accessed within the same package and by subclasses, even if
they are in different packages.
 Other classes outside the package (which are not subclasses) cannot access the `protected`
method directly.

```java
package com.example.package1;

public class Parent {


protected void protectedMethod() {
// Method implementation
}
}

```java
package com.example.package2;

import com.example.package1.Parent;

public class Child extends Parent {


void callProtectedMethod() {
// Accessing protectedMethod from the Parent class
protectedMethod();
}
}

In summary, `protected` allows access to members within the same package and by
subclasses, enabling a level of encapsulation while still allowing for inheritance and
extension of functionality.

SREZ
Page 39
Object Oriented Programming -I B.E. 4th

Chapter 6 : Exception Handling, I/O, Abstract Classes And


Interfaces

 CONCEPT OF EXCEPTION

 WHAT IS AN EXCEPTION?
o An exception is an unwanted or unexpected event, which occurs
o during the execution of a program i.e at run time, that disrupts
o the normal flow of the program’s instructions.
 WHY AN EXCEPTION OCCURS?
o There can be several reasons that can cause a program to throw
o exception. For example: Opening a non-existing file in your
o program, Network connection problem, bad input data provided by user etc .
 EXCEPTION HANDLED BY 5 KEYWORDS:
1. TRY
2. CATCH
3. THROW
4. THROWS
5. FINALLY

 EXAMPLE OF EXCEPTION:

class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
} catch (ArithmeticException e)
{
System.out.println("ArithmeticException => " + e.getMessage());s
}
}
}

EXCEPTION AND ERROR


 Exceptions are events that occurs in the code. A programmer can handle such
conditions
 and take necessary corrective actions
 Errors indicate that something severe enough has gone wrong, the application should
 crash rather than try to handle the error.
 There are two types of errors:
1.Compile time error
2.Run time error.

SREZ Page 1
Object Oriented Programming -I B.E. 4th

1. Compile time error


 The errors that are detected by the java compiler during the compile time are called
the compile time errors.
 When compile time errors occurred it will not generate .class file.

1. Missing Semicolon
2. Wrong Spelling of keywords and identifiers
3. Missing brackets of class and methods
4. Missing double quotes in the string
5. Use of undeclared Variables.
6. Use of = instead of ==
7. Incompatible types in assignment statements
8. Illegal references to the object

2. Run time error


 Sometimes the program is free from the compile time errors and creates a .class file
 It is basically the logic errors,that get caused due to the wrong logic.

1. Accessing the array element which is out of the index.


2. In an expression,divided by zero.
3. Trying to store a value into an array of incompatible type.
4. Passing the parameters that is not in valid in range
5. Converting invalid string to numbers
6. Trying to illegally change the state of thread.

 TRY-CATCH BLOCK
syntax:
try
{
//Exception gets generated here
}
catch (ExceptionType name)
{
//Exception is handled here
}

SREZ Page 2
Object Oriented Programming -I B.E. 4th

Example

public class TryCatchExample


{
public static void main(String[] args)
{
try {
// Code that may throw an exception
int result = divide(10, 0);
System.out.println("Result: " + result); // This line won't be executed if an exception
occurs
} catch (ArithmeticException e) {
// Catching and handling the ArithmeticException
System.out.println("An arithmetic exception occurred: " + e.getMessage());
}
}

public static int divide(int dividend, int divisor) {


// Method that may throw an ArithmeticException if the divisor is zero
return dividend / divisor;
}
}
Output
An arithmetic exception occurred: / by zero

 Nested Try Statements


 The try block within a try block is known as nested try block in java.
 Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested.

Syntax
try
{
statement;
try
{
statement ;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}

Example

public class NestedTryExample {

SREZ Page 3
Object Oriented Programming -I B.E. 4th

public static void main(String[] args) {


try {
// Outer try block
int[] numbers = {1, 2, 3};
int result;

try {
// Inner try block
result = numbers[4]; // Accessing an index out of bounds
} catch (ArrayIndexOutOfBoundsException innerException) {
// Catching and handling ArrayIndexOutOfBoundsException
System.out.println("Inner catch block: Index out of bounds.");
result = numbers[numbers.length - 1]; // Assigning a safe value
}

System.out.println("Result: " + result); // This line will execute if no exceptions occur


} catch (Exception outerException) {
// Outer catch block
System.out.println("Outer catch block: An exception occurred.");
}
}
}
Output
Inner catch block: Index out of bounds.
Result: 3

 Multiple Catch Blocks With Java Try

Syntax

try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}

Example

package com.tutorialspoint;

public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];

SREZ Page 4
Object Oriented Programming -I B.E. 4th

int b = 0;
int c = 1/b;
System.out.println("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException thrown :" + e);
}catch (Exception e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Output
Exception thrown :java.lang.ArithmeticException: / by zero
Out of the block

 Using Throws

 According to the Java Compiler - "we mus teither catch checked exceptions by
providing appropriate try-catch block or we should declare them, using throws."
 Hence, when a method doesn't want to catch/handle one or more checked exceptions by
providing an appropriate try-catch block within, it must use throws keyword in its
method signature to declare that it does not handle but only throws such checked
exceptions.
 Syntax

1)
//Declaring one checked exception using throws keyword

public void method1() throws


IOException //method signature{}

2)
method_name(parameter_list)throws
exception_list
{}

Example

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{

SREZ Page 5
Object Oriented Programming -I B.E. 4th

n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output
exception handled
normal flow...

 Using throw
 you may use the throw keyword when you explicitly want to throw an exception.
 The keyword throw is followed by an object of the exception class that you want to
throw.
 Using throw keyword, an exception can be explicitly thrown from within the
 two places in a Java program -
o try block or
o catch blcok.

Throw in Try Block


To throw an exception out of try block, keyword throw is followed by creating a new object
of exception class that we wish to throw.
For example -
try
{
// An object of IOException exception
class is created using "new" keyword.
throw new IOException();

}
Throw in Catch Block
To throw an exception out of catch block, keyword throw is followed by object reference of
the exception class that was caught by catch block.
For example -
catch(IOException io)
{
throw io; // An existing exception
class object referenced by "io" of type
"IOException", is thrown.

SREZ Page 6
Object Oriented Programming -I B.E. 4th

Finally Clause

➔ Java finally block is a block that is used to execute important


code such as closing connection, stream etc.
➔ Java finally block is always executed whether exception is
handled or not.
➔ Java finally block follows try or catch block
➔ Finally block in java can be used to put "cleanup" code such as
closing a file, closing connection etc.

Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}

Points To Remember While Using Finally Block


 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.
 finally block is not executed in case exit() method is called before finally block or a fatal
error occurs in program execution.
 finally block is executed even method returns a value before finally block.

SREZ Page 7
Object Oriented Programming -I B.E. 4th

Why Java Finally Block Used?


 Java finally block can be used for clean-up (closing) the connections, files opened,
streams, etc. those must be closed before exiting the program.
 It can also be used to print some final information.

Example

package com.tutorialspoint;

public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

 Build In Exceptions

 Java defines several exception classes inside the standard package java.lang.
 The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available.

Types of Java Built-in Exceptions


1. Checked Exceptions
2. Unchecked Exceptions.

Checked Exceptions: The checked exceptions are handled by the programmer during
writing the code, they can be handled using the try-catch block. These exceptions are checked
at compile-time.

Unchecked Exceptions: The unchecked exceptions are not handled by the programmer.
These exceptions are thrown on run-time. Some of the unchecked exceptions are
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc.

SREZ Page 8
Object Oriented Programming -I B.E. 4th

SREZ Page 9
Object Oriented Programming -I B.E. 4th

 Throwable Class
 The java.lang.Throwable class is the superclass of all errors and exceptions in the Java
language.
 Only objects that are instances of this class (or one of its subclasses) are thrown by the
Java Virtual Machine or can be thrown by the Java throw statement.
 Class Declaration
public class Throwable
extends Object
implements Serializable

 Re-throwing Exception:

 An exception can be rethrown in a catch block. This action will cause the exception to be
passed to the calling method.
 If the rethrow operation occurs in the main method then the exception is passed to the
JVM and displayed on the console.
 The purpose of the rethrow operation is to get the attention of the outside world that an
exception has occurred and at the same time perform any contingency logic (such as
logging) in the catch block.
 Example

public class ReThrowExample {


public static void main(String[] args) {
try {
someMethod();
} catch (Exception e) {

SREZ Page 10
Object Oriented Programming -I B.E. 4th

System.out.println("Caught in main: " + e.getMessage());


}
}

public static void someMethod() throws Exception {


try {
// Simulating an exception occurring
int result = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught in someMethod: " + e.getMessage());

// Re-throwing the caught exception


throw e;
}
}
}
Output
Caught in someMethod: / by zero
Caught in main: / by zero

 Chained Exception

➔ Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
➔ For example, consider a situation division operation a/b in which a b is 0 which
throws an ArithmeticException because of an attempt to divide by zero but the actual
cause of exception was an I/O error (bcz wrong input value to variable b)which
caused the divisor to be zero. The method will throw only ArithmeticException to the
caller. So the caller would not come to know about the actual cause of exception.
Chained Exception is used in such type of situations.

The throwable class supports chained exception using the following methods:
Constructors
1. Throwable(Throwable cause) - the cause is the current exception.
2. Throwable(String msg, Throwable cause) - msg is the exception message, the
cause is the current exception.

Methods
1. getCause - returns actual cause.
2. initCause(Throwable cause) - sets the cause for calling an exception.

Example

public class ChainedExceptionExample {


public static void main(String[] args) {
try {
someMethod();
} catch (Exception e) {
e.printStackTrace();
}

SREZ Page 11
Object Oriented Programming -I B.E. 4th

public static void someMethod() {


try {
// Simulating an exception occurring
int result = 5 / 0;
} catch (ArithmeticException e) {
// Creating a new exception and chaining the caught exception
throw new RuntimeException("An error occurred in someMethod()", e);
}
}
}
Output
java.lang.RuntimeException: An error occurred in someMethod()
at ChainedExceptionExample.someMethod(ChainedExceptionExample.java:12)
at ChainedExceptionExample.main(ChainedExceptionExample.java:5)
Caused by: java.lang.ArithmeticException: / by zero
at ChainedExceptionExample.someMethod(ChainedExceptionExample.java:10)
... 1 more

 Defining Custom Exception Classes


➔ Java provides us facility to create our own exceptions which are basically derived
classes of Exception. For example MyException in below code extends the Exception
class.
➔ We pass the string to the constructor of the super class- Exception which is obtained
using “getMessage()” function on the object created.

 IO

 File Class and its Input and Output


➔The java.io package contains nearly every class you might ever need to perform input and
output
(I/O) in Java. All these streams represent an input source and an output destination
➔ The File class contains several methods for working with the path name, deleting and
renaming
files, creating new directories, listing the contents of a directory, and determining several
common attributes of files and directories.
➔ A pathname, whether abstract or in string form can be either absolute or relative. The
parent of
an abstract pathname may be obtained by invoking the getParent() method of this class.
➔ First of all, we should create the File class object by passing the filename or directory
name to it.
➔ A file system may implement restrictions to certain operations on the actual file-system
object, such as reading, writing, and executing. These restrictions are collectively known as
access permissions.

SREZ Page 12
Object Oriented Programming -I B.E. 4th

 How to create a File Object?

➔ A File object is created by passing in a String that represents the name of a file, or a
String or another File object. For example,
File a = new File("/usr/local/bin/geeks");
➔ defines an abstract file name for the geeks file in directory /usr/local/bin. This is an
absolute abstract file name.

 Absolute Path

➔ Simply, a path is absolute if it starts with the root element of the file system. In
windows, the root element is a drive e.g. C:\\, D:\\, while in unix it is denoted by “/”
character.
➔ An absolute path is complete in that no other information is required to locate the file,
it usually holds the complete directory list starting from the root node of the file
system till reaching the file or directory it denotes.
➔ Since absolute path is static and platform dependent, it is a bad practice to locate a file
using absolute path inside your program, since you will lose the ability to reuse your
program on different machines and platforms.

File absoluteFile = new File("D:\\sample-documents\\pdf-sample.pdf");

 Relative Path

➔ A relative path is a path which doesn’t start with the root element of the file system. It
is simply the path needed in order to locate the file from within the current directory
of your program. It is not complete and needs to be combined with the current
directory path in order to reach the requested file.
➔ In order to construct a rigid and platform independent program, it is a common
convention to use a relative path when locating a file inside your program.

File relativeFile = new File("/sample-documents/pdf-sample.pdf");

 Constructor:

➔ File(File parent, String child) : Creates a new File instance from a parent
abstract pathname and a child pathname string.

➔ File(String pathname) : Creates a new File instance by converting the given


pathname string into an abstract pathname.

➔ File(String parent, String child) : Creates a new File instance from a parent
pathname string and a child pathname string.

➔ File(URI uri) : Creates a new File instance by converting the given file: URI into
an abstract pathname.

 Methods:

SREZ Page 13
Object Oriented Programming -I B.E. 4th

1. String getName() : Returns the name of the file or directory denoted by this abstract
pathname.
2. String getParent() : Returns the pathname string of this abstract pathname’s parent.
3. File getParentFile() : Returns the abstract pathname of this abstract pathname’s parent.
4. String getPath() : Converts this abstract pathname into a pathname string.
5. boolean isDirectory() : Tests whether the file denoted by this pathname is a directory.
6. boolean isFile() : Tests whether the file denoted by this abstract pathname is a normal file.
7. boolean canExecute() : Tests whether the application can execute the file denoted by this
abstract pathname.
8. boolean canRead() : Tests whether the application can read the file denoted by this
abstract pathname.
9. boolean canWrite() : Tests whether the application can modify the file denoted by this
abstract pathname.

Output

SREZ Page 14
Object Oriented Programming -I B.E. 4th

 Reading Data From Web


 As many of you must be knowing that Uniform Resource Locator-URL is a string of text
that identifies all the resources on Internet, telling us the address of the resource, how to
communicate with it and retrieve something from it.
 A Simple URL looks like:

The URL class displays the following information of the URL:

Protocol: A protocol defines the set of rules for communication. In the above URL, the https
is a protocol.

Server name or IP Address: Server name or domain name or IP address is the particular
address of a Host. In the above example, www.javatpoint.com is the server name.

Port Number: The port number is an optional attribute.

Example

package com.javatpoint;
import java.net.*;
public class URLExample {
public static void main(String[] args){
try{
URL url=new URL("https://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());// Using getProtocol() method of the
URL class
System.out.println("Host Name: "+url.getHost()); // Using getHost() method
System.out.println("Port Number: "+url.getPort()); // Using getPort() method
System.out.println("File Name: "+url.getFile()); //Using getFile() method
}
catch(Exception e)
{
System.out.println(e);}
}
}
Output:

Protocol: https
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

Constructor in URL

SREZ Page 15
Object Oriented Programming -I B.E. 4th

➔ URL(String protocol, String host, String file): Creates a URL object from the specified
protcol, host, and file name.

➔ URL(String protocol, String host, int port, String file): Creates a URL object from
protocol, host, port and file name.

➔ URL(URL context, String spec): Creates a URL object by parsing the given spec in the
given context.

➔ URL(String protocol, String host, int port, String file, URLStreamHandler handler):-
Creates a URL object from the specified protocol, host, port number, file, and handler.

➔ URL(URL context, String spec, URLStreamHandler handler):- Creates a URL by


parsing the given spec with the specified handler within a specified context.

Methods in URL

➔ public String getHost(): return the hostname of the URL in IPv6 format.
➔ public String getFile(): returns the file name.
➔ public int getPort(): returns the port associated with the protocol specified by the URL.
➔ public int getDefaultPort: returns the default port used.
➔ public String getProtocol(): returns the protocol used by the URL.
➔ public String toString(): As in any class, toString() returns the string representation of the
given URL object.
➔ public String getAuthority(): returns the authority part of URL or null if empty.
➔ public String getPath(): returns the path of the URL, or null if empty.

URL Connection Class

➔ The Java URLConnection class represents a communication link between the URL
and the application. This class can be used to read and write data to the specified
resource referred by the URL.
➔ How to get the object of URLConnection class
➔ The openConnection() method of URL class returns the object of URLConnection
class. Syntax:
public URLConnection openConnection()throws IOException{}

SREZ Page 16
Object Oriented Programming -I B.E. 4th

 Abstract Classes:
 A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods.
 It needs to be extended and its method implemented. It cannot be instantiated.
 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.

Points to Remember:
 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.

Example
abstract class A{}

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();

SREZ Page 17
Object Oriented Programming -I B.E. 4th

Example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output
running safely

Abstract Class v/s Concrete Class

SREZ Page 18
Object Oriented Programming -I B.E. 4th

 Interfaces

 An interface in Java is a blueprint of a class. It has static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction.
 There can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
 There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.

Syntax:

interface <interface_name>{

// declare constant fields

// declare methods that abstract

// by default.

public void method1(); /


public void method2();

The relationship between classes and interfaces

syntax:

acess_modifier interface name_of_interface


{
return_type method_name1(parameter1,parameter2,......,parametern);
return_type method_name2(parameter1,parameter2,......,parametern);
type static final variable_name=value;
}

SREZ Page 19
Object Oriented Programming -I B.E. 4th

Example

interface printable{

void print();

class A6 implements printable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){

A6 obj = new A6();

obj.print();

Output:

Hello

Extending Interfaces

An interface can extend another interface in the same way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits
the methods of the parent interface.
Syntax:
Interface Interface_name2 extends Interface_name1
{
//body of interface
}

Example:
Interface A
{
Int val=10;
}
Interface B extends A
{
Void print_val();
}
Interface A
{
Int val=10;
}
Interface B extends A

SREZ Page 20
Object Oriented Programming -I B.E. 4th

{
Void print_val();
}
interfaces C extends A,B{
…...
}

Comparable Interface

 Java Comparable interface is used to order the objects of the user-defined class. This
interface is found in java.lang package and contains only one method named
compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the
elements on the basis of single data member only. For example, it may be rollno, name,
age or anything else.
 If we use Arrays and List objects then these objects can be sorted automatically by
Collection.sort method which is basically implements comparable interfaces.

compareTo(Object obj) method

public int compareTo(Object obj): It is used to compare the current object with the
specified object. It returns

● positive integer, if the current object is greater than the specified object.
● negative integer, if the current object is less than the specified object.
● zero, if the current object is equal to the specified object.

Cloneable Interface

 The object cloning is a way to create exact copy of an object. The clone() method of
Object class is used to clone an object.

SREZ Page 21
Object Oriented Programming -I B.E. 4th

 The java.lang.Cloneable interface must be implemented by the class whose object clone
we want to create. If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.

What if we don’t implement Cloneable interface?

The program would throw CloneNotSupportedException if we don’t implement the


Cloneable interface. A class implements the Cloneable interface to indicate to the
Object.clone() method that it is legal for that method to make a field-for-field copy of
instances of that class.

Does clone object and original object point to the same location in memory

The answer is no. The clone object has its own space in the memory where it copies the
content of the original object. That’s why when we change the content of original object
after cloning, the changes does not reflect in the clone object. Lets see this with the help of
an example.

Example
// Implementing Cloneable interface
class MyClass implements Cloneable {
private int number;
private String text;

// Constructor
public MyClass(int number, String text) {
this.number = number;
this.text = text;
}

// Getter and setter methods

public int getNumber() {


return number;
}

public void setNumber(int number) {


this.number = number;
}

public String getText() {


return text;
}

public void setText(String text) {


this.text = text;
}

// Overriding clone method


@Override

SREZ Page 22
Object Oriented Programming -I B.E. 4th

public Object clone() throws CloneNotSupportedException {


return super.clone();
}
}

public class CloneableExample {


public static void main(String[] args) {
try {
// Creating an object of MyClass
MyClass original = new MyClass(10, "Original");

// Cloning the object


MyClass cloned = (MyClass) original.clone();

// Modifying the cloned object


cloned.setNumber(20);
cloned.setText("Cloned");

// Output
System.out.println("Original: Number=" + original.getNumber() + ", Text=" +
original.getText());
System.out.println("Cloned: Number=" + cloned.getNumber() + ", Text=" +
cloned.getText());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
Output
Original: Number=10, Text=Original
Cloned: Number=20, Text=Cloned

Abstract class v/s Interface in java

NEXT PAGE.

SREZ Page 23
Object Oriented Programming -I B.E. 4th

SREZ Page 24
Object Oriented Programming -I B.E. 4th

Chapter 7 : JAVAFX Basics And Event-Driven Programming


And Animations

 What is JavaFX?
 JavaFX is a Java library used to develop Desktop applications as well as Rich Internet
Applications (RIA). The applications built in JavaFX, can run on multiple platforms
including Web, Mobile and Desktops.
 JavaFX is intended to replace swing in Java applications as a GUI framework.
However, It provides more functionalities than swing. Like Swing, JavaFX also
provides its own components and doesn't depend upon the operating system. It is
lightweight and hardware accelerated. It supports various operating systems including
Windows, Linux and Mac OS.

 Basic structure of JAVAFX program

 JavaFX application is divided hierarchically into three main components known as Stage,
Scene and nodes.
 We need to import javafx.application.Application class in every JavaFX application.
This provides the
 following life cycle methods for JavaFX application.
o public void init()
o public abstract void start(Stage primaryStage)
o public void stop()
 in order to create a basic JavaFX application, we need to:
1. Import javafx.application.Application into our code.
2. Inherit Application into our class.
3. Override start() method of Application class.

Stage

 Stage in a JavaFX application is similar to the Frame in a Swing Application. It acts like
a container for all the JavaFX objects.
 Primary Stage is created internally by the platform. Other stages can further be created by
the application. The object of primary stage is passed to start method.
 We need to call show method on the primary stage object in order to show our primary
stage. Initially, the primary Stage looks like following.

SREZ Page 1
Object Oriented Programming -I B.E. 4th

Scene

 Scene actually holds all the physical contents (nodes) of a JavaFX application.
Javafx.scene.Scene class provides all the methods to deal with a scene object.
 Creating scene is necessary in order to visualize the contents on the stage.
 At one instance, the scene object can only be added to one stage. In order to implement
Scene in our JavaFX application, we must import javafx.scene package in our code. The
Scene can be created by creating the Scene class object and passing the layout object into
the Scene class constructor. We will discuss Scene class and its method later in detail.

Scene Graph

 Scene Graph exists at the lowest level of the hierarchy. It can be seen as the collection of
various nodes. A node is the element which is visualized on the stage. It can be any
button, text box, layout, image, radio button, check box, etc.
 The nodes are implemented in a tree kind of structure. There is always one root in the
scene graph. This will act as a parent node for all the other nodes present in the scene
graph. However, this node may be any of the layouts available in the JavaFX system.
 The leaf nodes exist at the lowest level in the tree hierarchy. Each of the node present in
the scene graphs represents classes of javafx.scene package therefore we need to import
the package into our application in order to create a full featured javafx application.

Creating a JavaFX Application

To create a JavaFX application, you need to instantiate the Application class and implement
its abstract method start(). In this method, we will write the code for the JavaFX Application.

Application Class

The Application class of the package javafx.application is the entry point of the application in
JavaFX. To create a JavaFX application, you need to inherit this class and implement its

SREZ Page 2
Object Oriented Programming -I B.E. 4th

abstract method start(). In this method, you need to write the entire code for the JavaFX
graphics

In the main method, you have to launch the application using the launch() method. This
method internally calls the start() method of the Application class as shown in the following
program.

public class JavafxSample extends Application {


@Override
public void start(Stage primaryStage) throws Exception {
/*
Code for JavaFX application.
(Stage, scene, scene graph)
*/
}
public static void main(String args[]){
launch(args);
}
}

Within the start() method, in order to create a typical JavaFX application, you need to follow
the steps given below −

 Prepare a scene graph with the required nodes.


 Prepare a Scene with the required dimensions and add the scene graph (root node of the
scene graph) to it.
 Prepare a stage and add the scene to the stage and display the contents of the stage.

Example
The following program generates an empty JavaFX window. Save this code in a file with the
name JavafxSample.java

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class JavafxSample extends Application {


@Override
public void start(Stage primaryStage) throws Exception {
//creating a Group object
Group group = new Group();

//Creating a Scene by passing the group object, height and width


Scene scene = new Scene(group ,600, 300);

//setting color to the scene


scene.setFill(Color.BROWN);

SREZ Page 3
Object Oriented Programming -I B.E. 4th

//Setting the title to Stage.


primaryStage.setTitle("Sample Application");

//Adding the scene to Stage


primaryStage.setScene(scene);

//Displaying the contents of the stage


primaryStage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following
commands.

javac JavafxSample.java
java JavafxSample

 Panes,UI Control and Shapes


 Pane is a container class using which the UI components can be placed at any desired
location with any desired size.
 Node is any visual component such as UI Controls,Shapes,or a image view.
 UI Controls refer to label,button,checkbox,radio button and so on.
 Shapes refer to lines,rectangle,circle and so on.
 A Scene can be displayed in a stage.

import javafx.application.Application;

SREZ Page 4
Object Oriented Programming -I B.E. 4th

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.StackPane;

import javafx.scene.shape.Circle;

import javafx.stage.Stage;

public class SimpleExample extends Application {

@Override

public void start(Stage primaryStage) {

// Creating a StackPane (a type of pane) to hold UI controls and shapes

StackPane stackPane = new StackPane();

// Creating a Button (a UI control)

Button button = new Button("Click Me!");

// Creating a Circle shape

Circle circle = new Circle(50);

circle.setStyle("-fx-fill: skyblue;");

// Adding the button and circle to the StackPane

stackPane.getChildren().addAll(circle, button);

// Creating a Scene with the StackPane as its root node

Scene scene = new Scene(stackPane, 200, 200);

// Setting the Scene to the Stage

primaryStage.setScene(scene);

// Setting the title of the Stage

primaryStage.setTitle("Simple Example");

// Showing the Stage

primaryStage.show();

SREZ Page 5
Object Oriented Programming -I B.E. 4th

public static void main(String[] args) {


launch(args);
}

Property Binding
 JAVAFX introduces a new concept called property binding that enables a target object to
be bound to a source object.
 The target object is simply called a binding object or a binding property.
 Method:
target.bind(source)

 The bind method defines in javafx.beans.property.Property


 A binding property(target) is an instance of javafx.beans.property.Property
 A source object is an instance of the javafx.beans.value.ObservableValue

 The Color and the Font Class

 In JavaFX, we can fill the shapes with the colors. We have the flexibility to create our
own color using the several methods and pass that as a Paint object into the setFill()
method. Let's discuss the several methods of creating color in JavaFX.
 RGB Color
 RGB color system is the most popular method to create a color in graphics. It consists of
three components named as RED → R, GREEN → G and BLUE → B. Each component
uses 8 Bits that means every component can have the integer value from 0

SREZ Page 6
Object Oriented Programming -I B.E. 4th

to 22^8 - 1=255.
 The computer screen can be seen as the collection of pixels. The set (R,G,B) actually
represents the emission of their respective LEDs on the screen.

 If the value of RED is set to 0 then it means that the Red LED is turned off while the
value 255 indicates that the full emission of LED is being there. The combination of
(0,0,0) represents the black color while (255,255,255) represents the white color. The
middle values in that range can represent different colors.
 Using the superimposition of RGB, we can represent 255*255*255 different colors.
In JavaFX, the class javafx.scene.paint.Color class represents colors.
 There is a static method named as rgb() of Color class. It accepts three integer
arguments as Red, Green, Blue and one optional double argument called alpha. The
value of alpha is proportional to the opacity of the color. The alpha value 0 means that
the color is completely transparent while the value 1 means that the color is
completely opaque.

Example

package application;

import javafx.application.Application;

import javafx.scene.Group;

import javafx.scene.Scene;

import javafx.scene.effect.DropShadow;

import javafx.scene.effect.Shadow;

import javafx.scene.paint.Color;

import javafx.scene.shape.Rectangle;

import javafx.stage.Stage;

public class Shape_Example extends Application {

@Override

public void start(Stage primarystage) {

Group root = new Group();

primarystage.setTitle("Color Example");

Rectangle rect = new Rectangle();

rect.setX(50);

rect.setY(20);

SREZ Page 7
Object Oriented Programming -I B.E. 4th

rect.setWidth(100);

rect.setHeight(150);

int red=20;

int green=125;

int blue=10;

rect.setFill(Color.rgb(red, green, blue,0.63));

root.getChildren().add(rect);

Scene scene = new Scene(root,200,200);

primarystage.setScene(scene);

primarystage.show();

public static void main(String[] args) {

launch(args);

} Output

 The font class/text class:

we need to provide the text based information on the interface of our application. JavaFX
library provides a class named javafx.scene.text.Text for this purpose. This class provides
various methods to alter various properties of the text. We just need to instantiate this class to
implement text in our application.

SREZ Page 8
Object Oriented Programming -I B.E. 4th

Example

package application;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.layout.StackPane;

import javafx.scene.text.Text;

import javafx.stage.Stage;

public class TextExample extends Application{

@Override

public void start(Stage primaryStage) throws Exception {

// TODO Auto-generated method stub

Text text = new Text();

text.setText("Hello !! Welcome to JavaTPoint");

StackPane root = new StackPane();

SREZ Page 9
Object Oriented Programming -I B.E. 4th

Scene scene = new Scene(root,300,400);

root.getChildren().add(text);

primaryStage.setScene(scene);

primaryStage.setTitle("Text Example");

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output

Font and position of the text

 JavaFX enables us to apply various fonts to the text nodes. We just need to set the
property font of the Text class by using the setter method setFont(). This method
accepts the object of Font class.
 The class Font belongs the package javafx.scene.text. It contains a static method
named font(). This returns an object of Font type which will be passed as an argument
into the setFont() method of Text class. The method Font.font() accepts the following
parameters.

 Family: it represents the family of the font. It is of string type and should be an
appropriate font family present in the system.
 Weight: this Font class property is for the weight of the font. There are 9 values which
can be used as the font weight. The values are FontWeight. BLACK, BOLD,
EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD,
THIN.

SREZ Page 10
Object Oriented Programming -I B.E. 4th

 Posture: this Font class property represents the posture of the font. It can be either
FontPosture.ITALIC or FontPosture.REGULAR.
 Size: this is a double type property. It is used to set the size of the font. The Syntax of the
method setFont() is given below.
<text_object>.setFont(Font.font(<String font_family>, <FontWeight>, <FontPosture>,
<FontSize>)

Example
package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextExample extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Text text = new Text();

text.setX(100);
text.setY(20);
text.setFont(Font.font("Abyssinica SIL",FontWeight.BOLD,FontPosture.REGULAR,20));
text.setText("Welcome to Java");
Group root = new Group();
Scene scene = new Scene(root,500,200);
root.getChildren().add(text);
primaryStage.setScene(scene);
primaryStage.setTitle("Text Example");
primaryStage.show();
}
publicstaticvoid main(String[] args) {
launch(args);

}
}
Output

SREZ Page 11
Object Oriented Programming -I B.E. 4th

The image and image-view class:

 You can load and modify images using the classes provided by JavaFX in the package
javafx.scene.image. JavaFX supports the image formats like Bmp, Gif, Jpeg, Png.
Loading an Image
 You can load an image in JavaFX by instantiating the class named Image of the
package javafx.scene.image.
 To the constructor of the class, you have to pass either of the following −
● An InputStream object of the image to be loaded or,
● A string variable holding the URL for the image.

 //Passing FileInputStream object as a parameter

FileInputStream inputstream = new FileInputStream("C:\\images\\image.jpg");

Image image = new Image(inputstream);

 //Loading image from URL


//Image image = new Image(new FileInputStream("url for the image));

After loading the image, you can set the view for the image by instantiating the
ImageView class and passing the image to its constructor as follows −

ImageView imageView = new ImageView(image);

Example

SREZ Page 12
Object Oriented Programming -I B.E. 4th

 Layout Panes and Shapes

Layout Panes:

 Layouts are the top level container classes that define the UI styles for scene graph
objects. Layout can be seen as the parent node to all the other nodes. JavaFX provides
various layout panes that support different styles of layouts.
 In JavaFX, Layout defines the way in which the components are to be seen on the stage.
It basically organizes the scene-graph nodes. We have several built-in layout panes in
JavaFX that are HBox, VBox, StackPane, FlowBox, AnchorPane, etc.
 Each Built-in layout is represented by a separate class which needs to be instantiated in
order to implement that particular layout pane.
 All these classes belong to javafx.scene.layout package. javafx.scene.layout.Pane class
is the base class for all the built-in layout classes in JavaFX.

Layout Classes:
 javafx.scene.layout Package provides various classes that represents the layouts. The
classes are described in the table below.

SREZ Page 13
Object Oriented Programming -I B.E. 4th

Steps to create Layout

In order to create the layouts, we need to follow the following steps.


1. Instantiate the respective layout class, for example, HBox root = new HBox();
2. Setting the properties for the layout, for example, root.setSpacing(20);
3. Adding nodes to the layout object, for example,
root.getChildren().addAll(<NodeObjects>);

HBox

 HBox layout pane arranges the nodes in a single row. It is represented by


javafx.scene.layout.HBox class. We just need to instantiate HBox class in order to create
HBox layout.

HBox Constructor:

The HBox class contains two constructors that are given below.
1. new HBox() : create HBox layout with 0 spacing
2. new Hbox(Double spacing) : create HBox layout with a spacing value

Example

SREZ Page 14
Object Oriented Programming -I B.E. 4th

VBox

 Instead of arranging the nodes in horizontal row, Vbox Layout Pane arranges the nodes in
a single vertical column.
 It is represented by javafx.scene.layout.VBox class which provides all the methods to
deal with the styling and the distance among the nodes.
 This class needs to be instantiated in order to implement VBox layout in our application.

VBox Constructors:

1. VBox() : creates layout with 0 spacing


2. Vbox(Double spacing) : creates layout with a spacing value of double type
3. Vbox(Double spacing, Node? children) : creates a layout with the specified spacing
among the specified child nodes
4. Vbox(Node? children) : creates a layout with the specified nodes having 0 spacing
among them

Example

SREZ Page 15
Object Oriented Programming -I B.E. 4th

JavaFX StackPane

 The StackPane layout pane places all the nodes into a single stack where every new node
gets placed on the top of the previous node. It is represented by
javafx.scene.layout.StackPane class. We just need to instantiate this class to implement
StackPane layout into our application
 The class contains two constructors that are given below.
1. StackPane()
2. StackPane(Node? Children)
.

Example

GridPane:

 GridPane Layout pane allows us to add the multiple nodes in multiple rows and
columns. It is seen as a flexible grid of rows and columns where nodes can be placed
in any cell of the grid. It is represented by javafx.scence.layout.GridPane class. We
just need to instantiate this class to implement GridPane.
 The class contains only one constructor that is given below
Public GridPane(): creates a gridpane with 0 hgap/vgap.

SREZ Page 16
Object Oriented Programming -I B.E. 4th

Example

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Label_Test extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
Label first_name=new Label("First Name");
Label last_name=new Label("Last Name");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button Submit=new Button ("Submit");
GridPane root=new GridPane();
Scene scene = new Scene(root,400,200);
root.addRow(0, first_name,tf1);
root.addRow(1, last_name,tf2);
root.addRow(2, Submit);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output

SREZ Page 17
Object Oriented Programming -I B.E. 4th

JavaFX FlowPane

 FlowPane layout pane organizes the nodes in a flow that are wrapped at the flowpane's
boundary.
 The horizontal flowpane arranges the nodes in a row and wrap them according to the
flowpane's width.
 The vertical flowpane arranges the nodes in a column and wrap them according to the
flowpane's heigh FlowPane layout is represented by javafx.scene.layout.FlowPane class.
We just need to instantiate this class to create the flowpane layout.

Constructors
There are 8 constructors in the class that are given below.
1. FlowPane()
2. FlowPane(Double Hgap, Double Vgap)
3. FlowPane(Double Hgap, Double Vgap, Node? children)
4. FlowPane(Node... Children)
5. FlowPane(Orientation orientation)
6. FlowPane(Orientation orientation, double Hgap, Double Vgap)
7. FlowPane(Orientation orientation, double Hgap, Double Vgap, Node? children )
8. FlowPane(Orientation orientation, Node... Children)

Example

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class FlowPaneTest extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("FlowPane Example");

SREZ Page 18
Object Oriented Programming -I B.E. 4th

FlowPane root = new FlowPane();


root.setVgap(6);
root.setHgap(5);
root.setPrefWrapLength(250);
root.getChildren().add(new Button("Start"));
root.getChildren().add(new Button("Stop"));
root.getChildren().add(new Button("Reset"));
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:

BorderPane

 BorderPane arranges the nodes at the left, right, centre, top and bottom of the screen.
 It is represented by javafx.scene.layout.BorderPane class. This class provides
various methods like setRight(), setLeft(), setCenter(), setBottom() and setTop()
which are used to set the position for the specified nodes
We need to instantiate BorderPane class to create the BorderPane layout.
 There are the following constructors in the class.
○ BorderPane() : create the empty layout
○ BorderPane(Node Center) : create the layout with the center node
○ BorderPane(Node Center, Node top, Node right, Node bottom, Node left) :
create the layout with all the nodes
Properties

SREZ Page 19
Object Oriented Programming -I B.E. 4th

Constructors
There are the following constructors in the class.
1. BorderPane() : create the empty layout
2. BorderPane(Node Center) : create the layout with the center node
3. BorderPane(Node Center, Node top, Node right, Node bottom, Node left) : create the
layout with all the nodes

Example

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output

SREZ Page 20
Object Oriented Programming -I B.E. 4th

Shapes

 In some of the applications, we need to show two dimensional shapes to the user.
However, JavaFX provides the flexibility to create our own 2D shapes on the screen .
 There are various classes which can be used to implement 2D shapes in our
application. All these classes resides in javafx.scene.shape package.
 This package contains the classes which represents different types of 2D shapes.
There are several methods in the classes which deals with the coordinates regarding
2D shape creation.

Line:

 In general, Line can be defined as the geometrical structure which joins two points
(X1,Y1) and (X2,Y2) in a X-Y coordinate plane. JavaFX allows the developers to
create the line on the GUI of a JavaFX application. JavaFX library provides the class
Line which is the part of javafx.scene.shape package.
 How to create a Line?
 Follow the following instructions to create a Line.
o Instantiate the class javafx.scene.shape.Line.
o set the required properties of the class object.
o Add class object to the group
Properties:

Example

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class LineDrawingExamples extends Application{

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Line line = new Line(); //instantiating Line class
line.setStartX(0); //setting starting X point of Line
line.setStartY(0); //setting starting Y point of Line
line.setEndX(100); //setting ending X point of Line
line.setEndY(200); //setting ending Y point of Line

SREZ Page 21
Object Oriented Programming -I B.E. 4th

Group root = new Group(); //Creating a Group


root.getChildren().add(line); //adding the class object //to the group
Scene scene = new Scene(root,300,300);
primaryStage.setScene(scene);
primaryStage.setTitle("Line Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}

}
Output:

Rectangle:

 In general, Rectangles can be defined as the geometrical figure consists of four sides, out
of which, the opposite sides are always equal and the angle between the two adjacent
sides is 90 degree. A Rectangle with four equal sides is called square.
 JavaFX library allows the developers to create a rectangle by instantiating
javafx.scene.shape.Rectangle class

Example
package application;
import javafx.application.Application;
import javafx.scene.Group;

SREZ Page 22
Object Oriented Programming -I B.E. 4th

import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Shape_Example extends Application{

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Rectangle Example");
Group group = new Group(); //creating Group
Rectangle rect=new Rectangle(); //instantiating Rectangle
rect.setX(20); //setting the X coordinate of upper left //corner of rectangle
rect.setY(20); //setting the Y coordinate of upper left //corner of rectangle
rect.setWidth(100); //setting the width of rectangle
rect.setHeight(100); // setting the height of rectangle
group.getChildren().addAll(rect); //adding rectangle to the //group
Scene scene = new Scene(group,200,300,Color.GRAY);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}

}
Output:

Circle:

A circle is a special type of ellipse with both of the focal points at the same position. Its
horizontal radius is equal to its vertical radius. JavaFX allows us to create Circle on the GUI
of any application by just instantiating javafx.scene.shape.Circle class. Just set the class
properties by using the instance setter methods and add the class object to the Group.

SREZ Page 23
Object Oriented Programming -I B.E. 4th

package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Shape_Example extends Application{

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Circle Example");
Group group = new Group();
Circle circle = new Circle();
circle.setCenterX(200);
circle.setCenterY(200);
circle.setRadius(100);
circle.setFill(Color.RED);
group.getChildren().addAll(circle);
Scene scene = new Scene(group,400,500,Color.GRAY);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output

SREZ Page 24
Object Oriented Programming -I B.E. 4th

Ellipse :

 In general, ellipse can be defined as the geometrical structure with the two focal points.
The focal points in the ellipse are chosen so that the sum of the distance to the focal
points is constant from every point of the ellipse.
 In JavaFX, the class javafx.scene.shape.Ellipse represents Ellipse. This class needs to be
instantiated in order to create ellipse. This class contains various properties which needs
to be set in order to render ellipse on a XY place.

How to create Ellipse?


There are the three main steps which needs to be followed in order to create ellipse
1. Instantiate Ellipse class.
2. Set the requires properties for the class.
3. Add the class object to the group.

Example

package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;
public class Shape_Example extends Application{

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Ellipse Example");
Group group = new Group();
Ellipse elipse = new Ellipse();
elipse.setCenterX(100);
elipse.setCenterY(100);
elipse.setRadiusX(50);
elipse.setRadiusY(80);
group.getChildren().addAll(elipse);
Scene scene = new Scene(group,200,300,Color.GRAY);
primaryStage.setScene(scene);
primaryStage.show();

SREZ Page 25
Object Oriented Programming -I B.E. 4th

}
public static void main(String[] args) {
launch(args);
}
}
Output:

Arc

In general, Arc is the part of the circumference of a circle or ellipse. It needs to be created in
some of the JavaFX applications wherever required. JavaFX allows us to create the Arc on
GUI by just instantiating javafx.scene.shape.Arc class. Just set the properties of the class to
the appropriate values to show arc as required by the Application.

Example
package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.stage.Stage;
public class Shape_Example extends Application{

SREZ Page 26
Object Oriented Programming -I B.E. 4th

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Arc Example");
Group group = new Group();
Arc arc = new Arc();
arc.setCenterX(100);
arc.setCenterY(100);
arc.setRadiusX(50);
arc.setRadiusY(80);
arc.setStartAngle(30);
arc.setLength(70);
arc.setType(ArcType.ROUND);
arc.setFill(Color.RED);
group.getChildren().addAll(arc);
Scene scene = new Scene(group,200,300,Color.GRAY);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}

}
Output:

Polygons:

 Polygon can be defined as a plain figure with at least three straight sides forming a loop.
In the case of polygons, we mainly considers the length of its sides and the interior
angles. Triangles, squares, Pentagons, Hexagons,etc are all polygons.
 In JavaFX, Polygon can be created by instantiating javafx.scene.shape.Polygon class.
We need to pass a Double array into the class constructor representing X-Y coordinates of
all the points of the polygon.
 The syntax is given below.
Polygon poly = new Polygon(DoubleArray);
 We can also create polygon by anonymously calling addAll() method on the reference
returned by calling getPoints() method which is an instance method of Polygon class.
However, we need to pass the double array into this method, which represents X-Y
coordinates of the polygon. The syntax is given below.
Pollygon polygon_object = new Pollygon();
Pollygon_Object.getPoints().addAll(Double_Array);

SREZ Page 27
Object Oriented Programming -I B.E. 4th

Example

Event Driven Programming

 Events and Events Sources:


Event: Event means any activity that interrupts the current ongoing
activity .
For Example: When user clicks button then it generates an event. To
respond to button click we need to write the code to process the button
clicking action.

Event Source Object: The object generates the event is called event source
object .
For Example: if the event gets generated on clicking the button, then
button is the event source object.

Event Handler: The event handling code written to process the generated
event is called event handler.

Event Listener: The task of handling an event is carried out by event


listener. When an event occurs ,first of all an event object of the appropriate
type is created. This object is then passed to a Listener. A listener must
implement the interface that has the method for event handling.

Types of Events
1. Foreground Events
Foreground events are mainly occur due to direct interaction of the user with the GUI of the
application.

SREZ Page 28
Object Oriented Programming -I B.E. 4th

. Such as clicking the button, pressing a key, selecting an item from the list, scrolling the
page, etc.

2. Background Events
Background events doesn't require the user's interaction with the application. These events
are mainly occurred to the operating system interrupts, failure, operation completion, etc.

SREZ Page 29
Object Oriented Programming -I B.E. 4th

Example

Inner Classes:

 Java inner class or nested class is a class which is declared inside the class or interface.
 We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
 Additionally, it can access all the members of outer class including private data members
and methods.
 Syntax:
Acess_modifier class Java_Outer_class
{
//code
Acess_modifier class Java_Inner_class
{
//code
}
}

SREZ Page 30
Object Oriented Programming -I B.E. 4th

Static Member Class

 A static class i.e. created inside a class is called static nested class in java. It cannot access
non-static data members and methods. It can be accessed by outer class name.
 It can access static data members of outer class including private.
 Static nested class cannot access non-static (instance) data member or method.

class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}

Member Inner Classes

A non-static class that is created inside a class but outside a method is called
member inner class.
Syntax:
class Outer{
//code
}
class Inner{
/ /code
}

Local Inner Classes

A class i.e. created inside a method is called local inner class in java. If
you want to invoke the methods of local inner class, you must instantiate
this class inside the method.

SREZ Page 31
Object Oriented Programming -I B.E. 4th

public class localInner1{


private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}

Anonymous Inner Class

A class that have no name is known as anonymous inner class in java. It should
be used if you have to override method of class or interface. Java Anonymous
inner class can be created by two ways:
1. Class (may be abstract or concrete).
2. Interface

abstract class Person{


abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

Anonymous Inner Class Handlers

 Anonymous inner class is an inner class without a name.It combines two


things-defining an inner class and creating an instance of the class into
one step.
 Syntax:
new superclassName_OR_InterfaceName()
{

//overriding method in superclass or Interface

SREZ Page 32
Object Oriented Programming -I B.E. 4th

Lamda Method
Anonymous inner class event handler

ok_button.setOnAction{
new EventHandler <ActionEvent>(){
@override
Public void handle(ActionEvent event)
{
System.out.println(“OK Button is clicked!!!”);

SREZ Page 33
Object Oriented Programming -I B.E. 4th

}
});

Lamda expression event handler

ok_button.setOnAction((ActionEvent e)->
{
System.out.println(“OK Button is clicked!!!”);
}

Mouse and Key Events:


User Source Event Event Registration Method
Action Object Type
Fired
Mouse setOnMousePressed(EventHandler<MouseEve
Pressed nt>)
Mouse setOnMouseReleased(EventHandler<MouseEven
Released ny>)
Mouse Node,Scene Mouse setOnMouseClicked(EventHandler<MouseEven
Clicked event t>)
Mouse setOnMouseMoved(EventHandler<MouseEven
Moved t>)
Mouse setOnMouseDragged(EventHandler<MouseEve
Dragged nt>)
Mouse setOnMouseEntered(EventHandler<MouseEve
entered nt>)
Mouse setOnMouseExited(EventHandler<MouseEven
exited t>)

MouseEvent Class
Method Description
MouseButton getButton It represent which mount button is pressed
int getClickCount() It returns the number of mouse clicks.
double getX() It returns the x-coordinates of the mouse
point in the event
source node.
double getY() It returns the y-coordinates of the mouse
point in the event
source node.
double getSceneX() It returns the x-coordinates of the mouse
point in the Scene
double getSceneY() It returns the y-coordinates of the mouse
point in the Scene
double getscreenX() It returns the x-coordinates of the mouse
point in the Screen
double getscreenY() It returns the y-coordinates of the mouse

SREZ Page 34
Object Oriented Programming -I B.E. 4th

point in the Screen


boolean isAltDown() It checks if the ALT Key is pressed or not.
boolean isControlDown() It checks if the Control Key is pressed or
not.
boolean isShiftDown() It checks if the shift key is pressed or not.

Keyboard Events:
When any key on the keyboard is pressed,released,or typed on a node then the
keyboard event
occurs.

SREZ Page 35
Object Oriented Programming -I B.E. 4th

KeyEvent Class

Example

SREZ Page 36
Object Oriented Programming -I B.E. 4th

Listeners for Observable Objects

 A listener can be added to process a value change in an observable


object.
 Observable Object is basically an instance of class Observable.
 Using the addListener (InvalidationListener listener)method we
can add the Listener.
 The Method public void invalidated(Observable) is an overriding
method, that helps to note the change in value.

package javafxapplicationobservable;

import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;

public class JavaFXApplicationObservable extends Application


{
public static void main(String[] args)
{
IntgerProperty count= new SimpleIntegerProperty();
count.addListner((Observable ov)->{
System.out.println("The new value is"+count.intValue());
});
count.set(100);}}

Animation

 In general, the animation can be defined as the transition which creates the myth
of motion for an object. It is the set of transformations applied on an object over
the specified duration sequentially so that the object can be shown as it is in
motion.
 This can be done by the rapid display of frames. In JavaFX, the package
javafx.animation contains all the classes to apply the animations onto the nodes.
All the classes of this package extend the class javafx.animation.Animation.
 JavaFX provides the classes for the transitions like RotateTransition,
ScaleTransition, TranslateTransition, FadeTransition, FillTransition,
StrokeTransition, etc.

SREZ Page 37
Object Oriented Programming -I B.E. 4th

Path Transition

 It allows the node to animate through a specified path over the specified
duration. In JavaFX, the path is defined by instantiating the class
javafx.scene.shape.Path.
 The translation along this path is done by updating the x and y coordinate
of the node at the regular intervals. The rotation can only be done in the
case when the orientation is set to be
OrientationType.ORTHOGONAL_TO_TANGENT.
 In JavaFX, the class javafx.animation.PathTransition represents the
path transition. We need to instantiate this class in order to create an
appropriate path transition.

SREZ Page 38
Object Oriented Programming -I B.E. 4th

Constructor:

There are three constructors in the class.

1. public PathTransition() : Creates the instance of the Path Transition


with the default parameters

2. public PathTransition(Duration duration, Shape path) : Creates the


instance of path transition with the specified duration and path

3. public PathTransition(Duration duration, Shape path, Node node) :


Creates the instance of the PathTransition with the specified duration,
path and the node.

SREZ Page 39
Object Oriented Programming -I B.E. 4th

SREZ Page 40
Object Oriented Programming -I B.E. 4th

Fade Transition

 It animates the opacity of the node so that the fill color of the node becomes dull. This
can be done by keep decreasing the opacity of the fill color over a specified duration in
order to reach a target opacity value.
 In JavaFX, the class javafx.animation.FadeTransition represents Fade Transition. We
need to instantiate this class in order to create the appropriate Fade Transition.

Constructor:

The class contains three Constructors.

1. public TranslateTransition() : creates the new instance of


TranslateTransition with the default parameters.

2. public TranslateTransition(Duration duration) : creates the new


instance of TranslateTransition with the specified duration
.
3. public TranslateTransition(Duration duration, Node node) : creates the
new instance of Translate Transition with the specified duration and node.

Timeline :

 An animation is driven by its associated properties, such as size, location, and color etc.
Timeline provides the capability to update the property values along the progression of
time. JavaFX supports key frame animation.
 In key frame animation, the animated state transitions of the graphical scene are declared
by start and end snapshots (key frames) of the state of the scene at certain times. The
system can automatically perform the animation. It can stop, pause, resume, reverse, or
repeat movement when requested.

SREZ Page 41
Object Oriented Programming -I B.E. 4th

Chapter 8 : JAVAFX UI Controls And Multimedia

 Introduction to UI Control

 This part of the tutorial provides you the in-depth knowledge of JavaFX UI controls. The
graphical user interface of every desktop application mainly considers UI elements,
layouts and behaviour.
 The UI elements are the one which are actually shown to the user for interaction or
information exchange. Layout defines the organization of the UI elements on the screen.
Behaviour is the reaction of the UI element when some event is occurred on it.
 However, the package javafx.scene.control provides all the necessary classes for the UI
components like Button, Label, etc. Every class represents a specific UI control and
defines some methods for their styling.

Control Description
Label Label is a component that is used to define a
simple text on the screen. Typically, a label is
placed with the node, it describes.
RadioButton Button is a component that controls the function
of the application. Button class is used to create a
labelled button.
RadioButton The Radio Button is used to provide various
options to the user. The user can only choose one
option among all. A radio button is either selected
or deselected.
CheckBox Check Box is used to get the kind of information
from the user which contains various choices.
User marked the checkbox either on (true) or
off(false).
TextField Text Field is basically used to get the input from
the user in the form of text.
javafx.scene.control.TextField represents
TextField
Textarea This control allows the user to enter multiple
line text.
ComboBox This control display the list of items out of
which user can select at most one item.
ListView This control displays the list of items out of
which user can select one or multiple items
from the list.
Slider This control is used to display a continuous or
discrete range of valid numeric choices and

SREZ Page 1
Object Oriented Programming -I B.E. 4th

 Labeled and Label

 javafx.scene.control.Label class represents label control. As the name


suggests, the label is the component that is used to place any text information
on the screen. It is mainly used to describe the purpose of the other
components to the user. You can not set a focus on the label using the Tab
key.
 Package: javafx.scene.control

 Constructors:
1. Label(): creates an empty Label
2. Label(String text): creates Label with the supplied text
3. Label(String text, Node graphics): creates Label with the supplied text and
graphics

Implementation of label

package application;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class LabelTest extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label my_label=new Label("This is an example of Label");
StackPane root = new StackPane();
Scene scene=new Scene(root,300,300);
root.getChildren().add(my_label);
primaryStage.setScene(scene);
primaryStage.setTitle("Label Class Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}
}

SREZ Page 2
Object Oriented Programming -I B.E. 4th

Output:

 Button

 JavaFX button control is represented by javafx.scene.control.Button class.


 A button is a component that can control the behaviour of the Application. An event is
generated whenever the button gets clicked.
 How to create a Button?
Button can be created by instantiating Button class. Use the following line to
create button object.
 Syntax :
Button btn = new Button("My Button");

Implementation of button

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ButtonTest extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub

StackPane root = new StackPane();


Button btn=new Button("This is a button");
Scene scene=new Scene(root,300,300);
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.setTitle("Button Class Example");
primaryStage.show();

}
public static void main(String[] args) {

SREZ Page 3
Object Oriented Programming -I B.E. 4th

launch(args);
}
}
Output:

Setting the Text of the Button

 There are two ways of setting the text on the button.


1. Passing the text into the class constructor
2. By calling setText("text") method

Wrapping Button Text

 We can wrap the text of the button into multiple lines if the text to be displayed is too
long.
 This can be done by calling a setter method setWrapText(boolean) on the instance of
Button class. Pass the boolean value true in the method wherever required.
Btn.setWrapText(true);

 CheckBox

 The Check Box is used to provide more than one choices to the user. It can be used in a
scenario where the user is prompted to select more than one option or the user wants to
select multiple options.
 It is different from the radiobutton in the sense that, we can select more than one
checkboxes in a scenerio.
 Instantiate javafx.scene.control.CheckBox class to implement CheckBox.
 Use the following line in the code to create a blank CheckBox.
CheckBox checkbox = new CheckBox();

 Use the following line to attach a label with the checkbox.

CheckBox checkbox = new CheckBox("Label Name");

 We can change the CheckBox Label at any time by calling an instance method
setText("text"). We can make it selected by calling setSelected("true")

SREZ Page 4
Object Oriented Programming -I B.E. 4th

Implementation of chechkbox

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class CheckBoxTest extends Application {

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label l = new Label("What do you listen: ");
CheckBox c1 = new CheckBox("Radio one");
CheckBox c2 = new CheckBox("Radio Mirchi");
CheckBox c3 = new CheckBox("Red FM");
CheckBox c4 = new CheckBox("FM GOLD");
HBox root = new HBox();
root.getChildren().addAll(l,c1,c2,c3,c4);
root.setSpacing(5);
Scene scene=new Scene(root,800,200);
primaryStage.setScene(scene);
primaryStage.setTitle("CheckBox Example");
primaryStage.show();
}
}
Output:

 RadioButton

 The Radio Button is used to provide various options to the user. The user can only choose
one option among all. A radio button is either selected or deselected.
 It can be used in a scenario of multiple choice questions in the quiz where only one option
needs to be chosen by the student.
 We can group JAVAFX RadioButton instances into a ToggleGroup.A ToggleGroup
allows at most one RadioButton to be selected at any time.

SREZ Page 5
Object Oriented Programming -I B.E. 4th

Implementation of RadioButton

 TextField

 Text Field is basically used to get the input from the user in the form of text.
 javafx.scene.control.TextField represents TextField. It provides various methods to deal
with textfields in JavaFX.
 TextField can be created by instantiating TextField class.

Implementation of TextField

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class TextFieldTest extends Application {

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {

SREZ Page 6
Object Oriented Programming -I B.E. 4th

// TODO Auto-generated method stub


Label user_id=new Label("User ID");
Label password = new Label("Password");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button b = new Button("Submit");
GridPane root = new GridPane();
root.addRow(0, user_id, tf1);
root.addRow(1, password, tf2);
root.addRow(2, b);
Scene scene=new Scene(root,800,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Text Field Example");
primaryStage.show();
}
}
Output:

 TextArea
 The TextARea control allows to enter multiline text.
 The control is represented by the class javafx.scene.control.TextArea.
 SYNTAX:
TextArea ta=new TextArea()
 We can set the size of the TextArea using setPrefHeight() and setPrefWidth() functions.

SREZ Page 7
Object Oriented Programming -I B.E. 4th

 Combo Box

 The JavaFX ComboBox control enables users to choose an option from a predefined list
of choices, or type in another value if none of the predefined choices matches what the
user want to select.
 The JavaFX ComboBox control is represented by the class
javafx.scene.control.ComboBox .
 This JavaFX ComboBox tutorial will explain how to use the ComboBox class.
 SYNTAX:
ComboBox comboBox = new ComboBox();

Adding Choices to a ComboBox

 You can add choices to a ComboBox by obtaining its item collection and add items to it.
 Here is an example that adds choices to a JavaFX ComboBox :
cb.getItems().add("Choice 1");
cb.getItems().add("Choice 2");
cb.getItems().add("Choice 3");

Implementation of ComboBox

SREZ Page 8
Object Oriented Programming -I B.E. 4th

 ListView

 The JavaFX ListView control enables users to choose one or more options from a
predefined list of choices.
 The JavaFX ListView control is represented by the class javafx.scene.control.ListView .
This JavaFX ListView tutorial will explain how to use the ListView class.
 SYNTAX:
ListView listView = new ListView();

Adding Items to a ListView

 You can add items (options) to a ListView by obtaining its item collection and add items
to it.
 Here is an example that adds items to a JavaFX ListView :
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");

Implementation of ListView

SREZ Page 9
Object Oriented Programming -I B.E. 4th

 Scrollbar

JavaFX Scroll Bar is used to provide a scroll bar to the user so that the user can scroll down
the application pages. It can be created by instantiating
javafx.scene.control.ScrollBar class.

implementation of scrollbar

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ScrollBar extends Application{

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
ScrollBar s = new ScrollBar();
StackPane root = new StackPane();
root.getChildren().add(s);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("ScrollBar Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}

SREZ Page 10
Object Oriented Programming -I B.E. 4th

}
Output:

 Slider

 JavaFX slider is used to provide a pane of option to the user in a graphical form where the
user needs to move a slider over the range of values to select one of them. Slider can be
created by instantiating javafx.scene.control.Slider class.
 The constructor accepts three arguments: the minimum value, the maximum value, and the initial
value of the slider.

Implementation of Slider

package application;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class SliderTest extends Application{

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Slider slider = new Slider(1,100,20);
StackPane root = new StackPane();
root.getChildren().add(slider);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Slider Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}

SREZ Page 11
Object Oriented Programming -I B.E. 4th

Output:

 Video

 Playing video in JavaFX is quite simple. We need to use the same API as we have used in
the case of playing Audio files. In the case of playing video, we need to use the
MediaView node to display the video onto the scene.
 For this purpose, we need to instantiate the MediaView class by passing the Mediaplayer
object into its constructor. Due to the fact that, MediaView is a JavaFX node, we will be
able to apply effects to it.
 In this part of the tutorial, we will discuss the steps involved in playing video media files
and some examples regarding this
 Steps to play video files in JavaFX

1. Instantiate the javafx.scene.media.Media class by passing the location of the audio


file in its constructor. Use the following line of code for this purpose.
Media media = new Media("http://path/file_name.mp3");

2. Pass the Media class object to the new instance of javafx.scene.media.MediaPlayer


object.
Mediaplayer mediaPlayer = new MediaPlayer(media);

3. Invoke the MediaPlayer object's play() method when onReady event is triggered.
mediaPlayer.setAutoPlay(true);

4. Instantiate MediaView class and pass Mediaplayer object into its constructor.
MediaView mediaView = new MediaView (mediaPlayer)

5. Add the MediaView Node to the Group and configure Scene.


Group root = new Group();
root.getChildren().add(mediaView)
Scene scene = new Scene(root,600,400);
primaryStage.setTitle("Playing Video");
primaryStage.show();

Example

package application;
import java.io.File;

import javafx.application.Application;

SREZ Page 12
Object Oriented Programming -I B.E. 4th

import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
public class JavaFX_Media Example extends Application
{

@Override
publicvoid start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
//Initialising path of the media file, replace this with your file path
String path = "/home/javatpoint/Downloads/test.mp4";

//Instantiating Media class


Media media = new Media(new File(path).toURI().toString());

//Instantiating MediaPlayer class


MediaPlayer mediaPlayer = new MediaPlayer(media);

//Instantiating MediaView class


MediaView mediaView = new MediaView(mediaPlayer);

//by setting this property to true, the Video will be played


mediaPlayer.setAutoPlay(true);

//setting group and scene


Group root = new Group();
root.getChildren().add(mediaView);
Scene scene = new Scene(root,500,400);
primaryStage.setScene(scene);
primaryStage.setTitle("Playing video");
primaryStage.show();
}
publicstaticvoid main(String[] args) {
launch(args);
}
}

 Audio

 We can load the audio files with extensions like .mp3,.wav and .aifff by using JavaFX
Media API. We can also play the audio in HTTP live streaming format. It is the new
feature introduced in JavaFX 8 which is also known as HLS.
 Playing audio files in JavaFX is simple. For this purpose, we need to instantiat
javafx.scene.media.Media class by passing the audio file path in its constructor. The
steps required to be followed in order to play audio files are described below.

SREZ Page 13
Object Oriented Programming -I B.E. 4th

1. Instantiate the javafx.scene.media.Media class by passing the location of the audio file in
its constructor.
Use the following line of code for this purpose.
1. Media media = new
Media("http://path/file_name.mp3");
2. Pass the Media class object to the new instance of javafx.scene.media.MediaPlayer
object.
1. Mediaplayer mediaPlayer = new
MediaPlayer(media);
3. Invoke the MediaPlayer object's play() method when onReady event is triggered.
1. MediaPlayer.setAutoPlay(true);

 The Media File can be located on a web server or on the local file system. SetAutoPlay()
method is the short-cut for setting the setOnReady() event handler with the lambda
expression to handle the event.

Example

package application;
import java.io.File;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
public class JavaFX_Media Example extends Application
{

@Override
public void start (Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
//Initialising path of the media file, replace this with your file path
String path = "/home/javatpoint/Downloads/test.mp3";

//Instantiating Media class


Media media = new Media(new File(path).toURI().toString());

//Instantiating MediaPlayer class


MediaPlayer mediaPlayer = new MediaPlayer(media);

//by setting this property to true, the audio will be played


mediaPlayer.setAutoPlay(true);
primaryStage.setTitle("Playing Audio");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

SREZ Page 14

You might also like