0% found this document useful (0 votes)
19 views30 pages

OOP-I Lab Manual

Uploaded by

gajjarsoham179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views30 pages

OOP-I Lab Manual

Uploaded by

gajjarsoham179
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/ 30

SAL Institute of Technology& Engineering Research

CE & CSE Department

Object Oriented Programming- I (3140705)

Laboratory Manual
Year: 2024-2025
INDEX

Sr.No Experiment Page No. Date Marks Signature

From To

1. Basics of java

2. Methods and Arrays

3. Constructors

4. String Builder and String Buffer

5. Inheritance and Polymorphism

6. Exception Handling

7. Abstract classes

8. Interfaces

9. JAVAFX and UI controls

10. Binary I/O, Recursion and Generics

Page 2 of 30
EXPERIMENT NO: 1 DATE: / /

TITLE: Introduction to java.

OBJECTIVES: On completion of this experiment student will able to…


 Understand the concept of java
 Create simple programs using Control statement and looping

THEORY:

What is Java:
Java is a programming language and a platform. Java is a high level, robust, secured and object- oriented
programming language. Any hardware or software environment in which a program runs, is known as a platform.
Since Java has its own runtime environment (JRE) and API, it is called platform

What is JVM
1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an
instance of JVM is created.
The JVM loads code, verifies code, executes code and provides runtime environment. It provides definitions for
the memory area , class file format, register set, garbage-collected heap, fatal error reporting etc.

Page 3 of 30
Internal Architecture of JVM

Creating Simple.java file

class Simple{ To Compile: javac Simple.java


public static void main(String args[]){
System.out.println("Hello Java"); To Execute: java Simple
}
}

EXERCISE:
1. Write a program to display “Welcome To Java World”.

2. Write a program to find whether the number is prime or not.


3. Write a program to find a greater number among given three numbers using a) ternary operator and b) nested if.
4. Write a program to print the Fibonacci series.

REVIEW QUESTIONS:
1. Explain features of Java briefly
2. JVM is platform independent. Justify.
3. List out and explain three main principles of object-oriented programming.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date:

Page 4 of 30
.
EXPERIMENT NO: 2 DATE: / /

TITLE: Introduction to Methods and Arrays

OBJECTIVES: On completion of this experiment student will able to…


 Define and invoke a method
 Declare and initialize an array

THEORY:

Methods can be used to define reusable code and organize and simplify coding. A method definition consists
of its method name, parameters, return value type, and body. To execute the method, you have to call or invoke
it.

Array Normally, array is a collection of similar type of elements that have contiguous memory location

It is an object that contains elements of similar data type. It is a data structure where we store similar elements.
We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array


• Code Optimization: we can retrieve or sort the data easily.
• Random access: We can get any data located at any index position.
Disadvantage of Java Array

Page 5 of 30
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in java.

Types of Array in java

Single Dimensional Array in java

Syntax to Declare an Array in java


dataType[] arr; (or) dataType []arr; (or) dataType arr[];

Instantiation of an Array in java


arrayRefVar=new datatype[size];

Declaration, Instantiation and Initialization of Java Array int


a[]={33,3,4,5};//declaration, instantiation and initialization

Multidimensional array in java

Syntax to Declare Multidimensional Array in java dataType[][] arrayRefVar; (or) dataType


[][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataTy pe []arrayRefVar[];

Example to instantiate Multidimensional Array in java int[][]


arr=new int[3][3];//3 row and 3 column

EXERCISES:
1. Write a method to enter two integers and compute the gcd of two integers.
2. Write a program that creates a Random object with seed 1000 and displays the first 100 random integers between
1 and 49 using the NextInt (49) method.

3. Write a test program that prompts the user to enter ten numbers, invoke a method to reverse the numbers, display
the numbers.

REVIEW QUESTIONS:
1. Explain array implementation in Java.

2. Explain method overriding with example.

EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date:

Page 6 of 30
EXPERIMENT NO: 3 DATE: / /

TITLE: Introduction to Constructors.

OBJECTIVES: On completion of this experiment student will able to… 


know the concept of class, object and constructor.

THEORY:

An object has three characteristics:

• state: represents data (value) of an object.


• behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
• identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the
external user. But, it is used internally by the JVM to identify each object uniquely.

Object Definitions:
• Object is a real world entity.
• Object is a run time entity.
• Object is an entity which has state and behavior.
• Object is an instance of a class

Class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which objects are
created. It is a logical entity. It can't be physical. A class in Java can contain fields, methods, constructors, blocks,
nested class and interface.

Syntax to declare a class:


3. class <class_name>{
4. field;
5. method;
6. }

Constructor
In Java, constructor is a block of codes similar to method. It is called when an instance of object is created and
memory is allocated for the object. It is a special type of method which is used to initialize the object.

When a constructor is called


Every time an object is created using new() keyword, at least one constructor is called. It is called a default
constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have
any.
Rules for creating java constructor

Page 7 of 30
There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors in java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

EXCERCISE:

1. Write a program that declares a class named Person. It should have instance variables to record name, age and
salary. Use new operator to create a Person object. Set and display its instance variables. Add a constructor to the
Person class developed above.

2. The employee list for a company contains employee code, name, designation and basic pay. The employee is
given HRA of 10% of the basic and DA of 45% of the basic pay. The total pay of the employee is calculated as
Basic pay+HRA+ DA. Write a class to define the details of the employee. Write a constructor to assign the required
initial values. Add a method to calculate HRA, DA and Total pay and print them out. Write another class with a
main method. Create objects for three different employees and calculate the HRA, DA and total pay.

REVIEW QUESTIONS:
1. What is a constructor in JAVA? How many types of constructors are there in JAVA? Explain with examples.
2. Justify:
i) Why we declare main() method as public and static member.
ii) Why we generally declare constructor as public member.
iii) Why there is no destructor in java.

EVALUATION:

Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)

Signature with date:

Page 8 of 30
EXPERIMENT NO: 4 DATE: / /

TITLE: Introduction to String class, StringBuilder Class and StringBuffer class.

OBJECTIVES: On completion of this experiment student will able to…


 Perform String Operations.
THEORY:

What is String in java


Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The
java.lang.String class is used to create string object.

How to create String object?


There are two ways to create an object

1) String Literal
Java String literal is created by using double quotes. For Example: String
s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the
pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created
and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance

2) Using new keyword


1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be
placed in the string constant pool. The variable s will refer to the object in heap(non pool).
Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(),
length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

Consider below code with three concatenation functions with three different types of parameters, String, StringBuffer
and StringBuilder.
// Java program to demonstrate difference between String, StringBuilder and StringBuffer class

Stringclasses

Page 9 of 30
{
public static void main(String[] args)
{
String s1 = "Ahmedabad"; concat1(s1);
// s1 is not changed
System.out.println("String: " + s1);

StringBuilder s2 = new StringBuilder("Ahmedabad");


concat2(s2); // s2 is changed
System.out.println("StringBuilder: " + s2);

StringBuffer s3 = new StringBuffer("Ahmedabad");


concat3(s3); // s3 is changed
System.out.println("StringBuffer: " + s3);
}

public static void concat1(String s1)


{ s1 = s1 + "Institute";
}
public static void concat2(StringBuilder s2)
{ s2.append("Institute");
}
public static void concat3(StringBuffer s3)
{ s3.append("University ");
}
}
Output:
String: Ahmedabad

StringBuilder: AhmedabadInstitute
StringBuffer: AhmedabadUniversity

Explanation:
1. Concat1 : In this method, we pass a string “Ahmedabad” and perform “s1 = s1 + ”Institute”. The string passed
from main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates
another object and s1 in concat1() stores reference of new string. References s1 in main() and cocat1() refer to
different strings.
2. Concat2 : In this method, we pass a string “Ahmedabad” and perform “s2.append(“Institute”)” which changes
the actual value of the string (in main) to “AhmedabadInstitute”. This is due to the simple fact that StringBuilder is
mutable and hence changes its value.

Page 10 of 30
2. Concat3 : StringBuffer is similar to StringBuilder except one difference that StringBuffer is thread safe, i.e., multiple
threads can use it without any issue. The thread safety brings a penalty of performance.

When to use which one :


• If a string is going to remain constant throughout the program, then use String class object because a String object
is immutable.
• If a string can change (example: lots of logic and operations in the construction of the string) and will only be
accessed from a single thread, using a StringBuilder is good enough.
• If a string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is
synchronous so you have thread-safety.

EXCERCISES:

1. Write a Java Program to Count Number of Words in Given String


2. Write a Java Program to Count the Occurrences of Each Character in String
3. Write a Java program to count number of occurrence of substring in given string.

REVIEW QUESTIONS:
1. State difference between String Class and StringBuffer Class.

EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)

Signature with date:

Page 11 of 30
EXPERIMENT NO: 5 DATE: / /

TITLE: Inheritance and Polymorphism

OBJECTIVES: On completion of this experiment student will able to…


 know the concept of Inheritance
 know the concept of Polymorphism
 know the difference between method overloading and overriding
THEORY:

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent
object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in
java is that you can create new classes that are built upon existing classes. When you inherit from an existing
class, you can reuse methods and fields of parent class. Moreover, you can add new methods and fields in your
current class also.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java
programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces
later.

Multiple inheritance is not supported in java through class.

Why use inheritance in java:


• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.

Terms used in Inheritance:


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

Page 12 of 30
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class,
or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base
class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods
of the existing class when you create a new class. You can use the same fields and methods already defined in the
previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name{ //methods
and fields
}

Polymorphism in java is ‘a state of having many shapes’ or ‘the capacity to take on different forms’. When
applied to object-oriented programming languages like Java, it describes a language’s ability to process objects
of various types and classes through a single, uniform interface.

Types of polymorphism in java


Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism
(dynamic binding). Method overloading is an example of static polymorphism, while method overriding is an
example of dynamic polymorphism.

Method Overloading

Method overloading enables you to define the methods with the same name as long as their signatures are different.
Following program creates three methods. The first finds the maximum integer, the second finds the maximum
double, and the third finds the maximum among three double values. All three methods are named max.

public class TestMethodOverloading {


/** Main method */
public static void main(String[] args) {
// Invoke the max method with int parameters System.out.println("The maximum of 3 and 4 is "+ max(3,
4));
// Invoke the max method with the double parameters System.out.println("The maximum of 3.0 and 5.4 is " +
max(3.0, 5.4)); }
/** Return the max of two int values */ public static int max(int num1,
int num2) { if (num1 > num2) return num1; else return num2;
}
public static double max(double num1, double num2) { if (num1 > num2)
return num1; else return num2;
}
}
The maximum of 3 and 4 is 4
The maximum of 3.0 and 5.4 is 5.4

Page 13 of 30
Method Overriding : If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java. In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


• Method overriding is used to provide specific implementation of a method that is already provided by its
super class.
• Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class 2.
method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

super keyword in java


The super keyword in java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by
super reference variable.

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

class Animal{
String color="white";
} class Dog extends
Animal{String
color="black"; void printColor(){
System.out.println(color);//prints color of Dog class System.out.println(super.color);//prints color of Animal class } }
class TestSuper1{ public static void main(String args[]){
Dog d=new Dog(); d.printColor();
}}

black
white

EXERCISE: Use following class hierarchy

1. Write a program to illustrate the concept of class with Method overloading


Page 14 of 30
2. Write a program to illustrate the concept of Dynamic Polymorphism.
3. Write a program to illustrate the concept of Single inheritance
4. Write a program to illustrate the concept of Multi level inheritance

REVIEW QUESTIONS:
1. What is inheritance in java? Explain different types of inheritance with proper example.
2. Explain following with example:
i) Finalize() ii) static iii) super iv) final

EVALUATION:

Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)

Signature with date:

Page 15 of 30
EXPERIMENT NO: 6 DATE: / /

TITLE: How to use Exception handling

OBJECTIVES:On completion of this experiment student will able to…

 understand use of exception handling try,catch,throw,throws,finally


 Undefined Exception
THEORY:
The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow
of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between checked and unchecked exceptions.

What is exception handling


Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked
exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception
The classes that extend Throwable class except Runtime Exception and Error are known as checked exceptions
e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that extend Runtime Exception are known as unchecked exceptions e.g. Arithmetic Exception, Null
Pointer Exception, Array Index Out Of Bounds Exception etc. Unchecked exceptions are not checked at compiletime
rather they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java try block


Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Page 16 of 30
Java try block must be followed by either catch or finally block.

Java Multi catch block


If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block.

Java finally block


It 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.

Java throw keyword


The Java throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked exception
in java by throw keyword. The throw keyword is mainly used to throw custom exception.

Java throws keyword


It is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception
Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not performing check up before the code being used.

EXERCISE:
1. Write an exception class for a time of day that can accept only 24 hour representation of clock hours. Write a java
program to input various formats of timings and throw suitable error messages.

2. Write a method for computing by doing repetitive multiplication. x and y are of type integer and are to be
given as command line arguments. Raise and handle exception(s) for invalid values of x and y. Also define method
main. Use finally in above program and explain its usage.

3. Write a program to input name and age of a person and throws a user defined exception, if entered age is negative.

REVIEW QUESTIONS:
1. What is Exception? Demonstrate how you can handle different types of exception separately.
2. Differentiate the following: Checked and Unchecked exceptions.
.

EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)

Signature with date:

Page 17 of 30
EXPERIMENT NO: 7 DATE: / /

TITLE:To Understand the Concept of Abstract Class.

OBJECTIVES: student will able to… On completion of this experiment


 use abstract class

THEORY:
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and nonabstract
methods (method with body).
Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only important things to the user and hides the internal details for example sending sms, you just
type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Example abstract class


1. abstract class A{}

abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method


abstract void printStatus();//no body and 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();
}
}
EXCERCISE:
1. The abstract Vegetable class has three subclasses named Potato, Brinjal and Tomato. Write an application that
demonstrates how to establish this class hierarchy. Declare one instance variable of type String that indicates the
color of a vegetable. Create and display instances of these objects. Override the toString() method of Object to
return a string with the name of the vegetable and its color. .

2. Create an abstract class ‘Shape’ with two members base and height , a member function for initialization and a
pure virtual function to compute area(). Derive two specific classes ‘Triangle’ and ‘Rectangle’ which override the
function area(). Use these classes in main function and display the area of triangle and rectangle.
Page 18 of 30
REVIEW QUESTIONS:
1. Differentiate between abstract class and Interface.
2. State whether the following statements are true or false.
(i) An abstract class contains constructors.

EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)

Signature with date:

Page 19 of 30
EXPERIMENT NO: 8 DATE: / /

TITLE: To Understand concept of interface.

OBJECTIVES: On completion of this experiment student will able to use interface

THEORY:
Interface

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.
In other words, you can say that interfaces can have methods and variables but the methods declared in interface contain
only method signature, not body.
Java Interface also represents IS-A relationship. It cannot
be instantiated just like abstract class.
An interface is a completely "abstract class" that is used to group related methods with empty bodies:

// interface Animal { public void animal Sound(); // interface method


(does not have a body) public void run(); // interface method (does not
have a body)
}
To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with
the implements keyword (instead of extends). The body of the interface method is provided by the "implement"
class:

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

• It is used to achieve abstraction.


• By interface, we can support the functionality of multiple inheritance. It can be used to
achieve loose coupling.

Understanding relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another interface but a class
implements an interface.

Page 20 of 30
EXCERCISE:

1. Write a program that illustrates interface inheritance. Interface A is extended by A1 and A2. Interface A12 inherits
from both P1 and P2.Each interface declares one constant and one method. Class B implements A12.Instantiate B
and invoke each of its methods. Each method displays one of the constants.

2. Write an interface called shape with methods draw() and getArea(). Further design two classes called ‘Circle’
and ‘Rectangle’ that implements ‘Shape’ to compute area of respective shapes. Use appropriate getter and setter
methods. Write a java program for the same.

REVIEW QUESTIONS:
1. What is Interface? Write steps to declare and define an interface and explain with sample program.

EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)

Signature with date:

Page 21 of 30
EXPERIMENT NO: 9 DATE: / /

TITLE: Understand concept JavaFX and UI controls

OBJECTIVES: On completion of this experiment student


 use JavaFX and UI controls
THEORY:

Every user interface considers the following three main aspects −


• UI elements − These are the core visual elements which the user eventually sees and interacts with. JavaFX
provides a huge list of widely used and common elements varying from basic to complex, which we will
cover in this tutorial.
• Layouts − They define how UI elements should be organized on the screen and provide a final look and
feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter.
• Behavior − These are events which occur when the user interacts with UI elements. This part will be covered
in the Event Handling chapter.
JavaFX provides several classes in the package javafx.scene.control. To create various GUI components (controls),
JavaFX supports several controls such as date picker, button text field, etc.
Each control is represented by a class; you can create a control by instantiating its respective class.

To fully benefit from JavaFX it is useful to understand how JavaFX is designed, and to have a good overview of
what features JavaFX contains. The purpose of this text is to give you that JavaFX overview. This text will first look
at the general JavaFX design, then look at the various features in JavaFX.

If you are familiar with Flash / Flex, you will see that JavaFX is somewhat inspired by Flash / Flex. Some of the
same ideas are found in JavaFX. In general, a JavaFX application contains one or more stages which corresponds
to windows. Each stage has a scene attached to it. Each scene can have an object graph of controls, layouts etc.
attached to it, called the scene graph. These concepts are all explained in more detail later. Here is an illustration of
the general structure of a JavaFX application:

Page 22 of 30
Stage:
The stage is the outer frame for a JavaFX application. The stage typically corresponds to a window. In the early
days where JavaFX could run in the browser, the stage could also refer to the area inside the web page that JavaFX
had available to draw itself.

Since the deprecation of the Java browser plugin JavaFX is mostly used for desktop applications. Here, JavaFX
replaces Swing as the recommended desktop GUI framework. When used in a desktop environment, a JavaFX
application can have multiple windows open. Each window has its own stage.

Each stage is represented by a Stage object inside a JavaFX application. A JavaFX application has a primary Stage
object which is created for you by the JavaFX runtime. A JavaFX application can create additional Stage objects if
it needs additional windows open. For instance, for dialogs, wizards etc.

Scene:
To display anything on a stage in a JavaFX application, you need a scene. A stage can only show one scene at a
time, but it is possible to exchange the scene at runtime. Just like a stage in a theater can be rearranged to show
multiple scenes during a play, a stage object in JavaFX can show multiple scenes (one at a time) during the life time
of a JavaFX application.

Imagine a computer game. A game might have multiple "screens" to show to the user. For instance, an initial menu
screen, the main game screen (where the game is played), a game over screen and a high score screen. Each of these
screens can be represented by a different scene. When the game needs to change from one screen to the next, it
simply attaches the corresponding scene to the Stage object of the JavaFX application.

A scene is represented by a Scene object inside a JavaFX application. A JavaFX application must create all Scene
objects it needs.

Scene Graph:
All visual components (controls, layouts etc.) must be attached to a scene to be displayed, and that scene must be
attached to a stage for the whole scene to be visible. The total object graph of all the controls, layouts etc. attached
to a scene is called the scene graph.

Nodes:
All components attached to the scene graph are called nodes. All nodes are subclasses of a JavaFX class called
javafx.scene.Node .

There are two types of nodes: Branch nodes and leaf nodes. A branch node is a node that can contain other nodes
(child nodes). Branch nodes are also referred to as parent nodes because they can contain child nodes. A leaf node
is a node which cannot contain other nodes.

Controls
JavaFX controls are JavaFX components which provide some kind of control functionality inside a JavaFX
application. For instance, a button, radio button, table, tree etc.

For a control to be visible it must be attached to the scene graph of some Scene object.

Page 23 of 30
Controls are usually nested inside some JavaFX layout component that manages the layout of controls relative to
each other.

JavaFX contains the following controls:

Accordion ListView SplitPane


Button Menu TableView
CheckBox MenuBar TabPane
ChoiceBox PasswordField TextArea
ColorPicker ProgressBar TextField
ComboBox RadioButton TitledPane
DatePicker Slider ToggleButton
Label Spinner ToolBar
TreeView SplitMenuButton TreeTableView

Layouts

JavaFX layouts are components which contains other components inside them. The layout component manages
the layout of the components nested inside it. JavaFX layout components are also sometimes called parent
components because they contain child components, and because layout components are subclasses of the
JavaFX class javafx.scene.Parent.

A layout component must be attached to the scene graph of some Scene object to be visible. JavaFX contains
the following layout components:
Group StackPane VBox
Region TilePane FlowPane
Pane GridPane TextFlow
HBox AnchorPane BorderPane

Each of these layout components will be covered in separate texts.

Nested Layouts
It is possible to nest layout components inside other layout components. This can be useful to achieve a specific
layout. For instance, to get horizontal rows of components which are not layed out in a grid, but differently for
each row, you can nest multiple HBox layout components inside a VBox component.

Charts

JavaFX comes with a set of built-in ready-to-use chart components, so you don't have to code charts from scratch
everytime you need a basic chart. JavaFX contains the following chart components:

Page 24 of 30
AreaChart LineChart StackedAreaChart
BarChart PieChart StackedBarChart
BubbleChart ScatterChart

Audio
JavaFX contains features that makes it easy to play audio in JavaFX applications. This is typically useful in games
or educational applications.

Video
JavaFX contains features that makes it easy to play video in JavaFX applications. This is typically useful in
streaming applications, games or educational applications.

WebView
JavaFX contains a WebView component which is capable of showing web pages (HTML5, CSS etc.). The JavaFX
WebView component is based on WebKit - the web page rendering engine also used in Chrome and Safari.

EXCERCISE:

1. Write a program that displays an image in a label, a title in a label, and text in the text area as follows:

2. Write a JavaFX program to display the mouse position in the form of (x,y) co-ordinates, when the text present on
the screen is dragged somewhere else.

3. Write a JavaFX application for creating a login form.

REVIEW QUESTIONS:
1. What methods do you use to register a handler for a mouse pressed, released, clicked, entered, exited, movedand
dragged event?
2. What is an event source object? What is an event object? Describe the relationship between an event sourceobject and
an event object

EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)

Signature with date:


Page 25 of 30
EXPERIMENT NO: 10 DATE: / /

TITLE: To Understand concept of binary I/O, recursion and generics

OBJECTIVES: On completion of this experiment student will able to…


 use binary I/O, recursion and generics s
THEORY:

Binary I/O

The legacy API (classes in the java.io.* package) is perfect for manipulating low-level binary I/O operations such
as reading and writing exactly one byte at a time, whereas the NIO API (classes in the java.nio.* package) is
more convenient for reading and writing the whole file at once, and of course, faster than the old File I/O API.

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 stream in the java.io package supports
many data such as primitives, object, localized characters, etc.

Stream
A stream can be defined as a sequence of data. There are two kinds of Streams − InputStream
− The InputStream is used to read data from a source.
OutputStream − The OutputStream is used for writing data to a destination.

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte
streams but the most frequently used classes are, FileInputStream and FileOutputStream.

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to
perform input and output for 16-bit unicode. Though there are many classes related to character streams but the
most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream
and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time
and FileWriter writes two bytes at a time.

Standard Streams
All the programming languages provide support for standard I/O where the user's program can take input from a
keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming
languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java
provides the following three standard streams −

• Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard
input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's program and usually a computer
screen is used for standard output stream and represented as System.out.

Page 26 of 30
• Standard Error − This is used to output the error data produced by the user's program and usually a computer
screen is used for standard error stream and represented as System.err.

Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.

FileInputStream

This stream is used for reading data from the files. Objects can be created using the keyword new and there are
several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the file − InputStream f
= new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we create a file
object using File() method as follows − File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

FileOutputStream

FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already
exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file − OutputStream
f = new FileOutputStream("C:/java/hello")

Page 27 of 30
Following constructor takes a file object to create an output stream object to write the file. First, we create a
file object using File() method as follows − File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Recursion in Java

Recursion is the process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved
quite easily.
Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of
Graph, etc.

What is base condition in recursion?


In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed
in terms of smaller problems.
int fact(int n)
{ if (n < = 1) // base case
return 1;
else return n*fact(n-1);
}

How a particular problem is solved using recursion?


The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions
that stop the recursion. For example, we compute factorial n if we know factorial of (n-1). The base case for
factorial would be n = 0. We return 1 when n = 0.

If the base case is not reached or not defined, then the stack overflow problem may arise.
What is the difference between direct and indirect recursion?
A function fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive
if it calls another function say fun_new and fun_new calls fun directly or indirectly. Difference between direct and
indirect recursion has been illustrated in Table 1.
• Direct recursion: void directRecFun()
{
// Some code....

directRecFun();

// Some code...
}
• Indirect recursion: void indirectRecFun1()
{
// Some code...

Page 28 of 30
indirectRecFun2();

// Some code...
}
void indirectRecFun2()
{
// Some code...

indirectRecFun1();

// Some code...
}

What is difference between tailed and non-tailed recursion?


A recursive function is tail recursive when recursive call is the last thing executed by the function. Please refer
tail recursion article for details.

How memory is allocated to different function calls in recursion?


When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself,
the memory for the called function is allocated on top of memory allocated to calling function and different copy of
local variables is created for each function call. When the base case is reached, the function returns its value to the
function by whom it is called and memory is de-allocated and the process continues.

What are the advantages of recursive programming over iterative programming?


Recursion provides a clean and simple way to write code. Some problems are inherently recursive like tree
traversals, Tower of Hanoi, etc. For such problems, it is preferred to write recursive code. We can write such
codes also iteratively with the help of a stack data structure. For example refer Inorder Tree Traversal without
Recursion, Iterative Tower of Hanoi.

What are the disadvantages of recursive programming over iterative programming?


Note that both recursive and iterative programs have the same problem-solving powers, i.e., every recursive
program can be written iteratively and vice versa is also true. The recursive program has greater space
requirements than iterative program as all functions will remain in the stack until the base case is reached. It also
has greater time requirements because of function calls and returns overhead.

Generics in Java

Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc. and user defined
types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList,
HashMap, etc. use generics very well. We can use them for any type.

Generic Class

Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use
following syntax.
// To create an instance of generic class

Page 29 of 30
BaseType <Type> obj = new BaseType <Type>()
Note: In Parameter type we can not use primitives like
'int','char' or 'double'.

Generic Functions:
We can also write generic functions that can be called with different types of arguments based on the type of
arguments passed to generic method, the compiler handles each method.

Advantages of Generics:
Programs that uses Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use for any type we want.
2. Type Safety : Generics make errors to appear compile time than at run time (It’s always better to know
problems in your code at compile time rather than making your code fail at run time). Suppose you want to
create an ArrayList that store name of students and if by mistake programmer adds an integer object instead
of string, compiler allows it. But, when we retrieve this data from ArrayList, it causes problems at runtime.
3. Individual Type Casting is not needed: If we do not use generics, then, in the above example every-time we
retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval operation is a big headache.
If we already know that our list only holds string data then we need not to typecast it every time.
4. Implementing generic algorithms: By using generics, we can implement algorithms that work on different
types of objects and at the same they are type safe too.

EXCERCISE:
1. Write a program to count the total number of chars, words, lines, alphabets, digits, white spaces in given file.
2. Write the program for factorial using the concept of recursion.
3. Write a program to implement Tower of Hanoi through recursion
4. Implement sorting of an array of comparable object using Generic Method.

REVIEW QUESTIONS:
1. How to define Generic class and interface explain with example.
2. Explain usage of class FileInputStream and FileOutputStream by giving an example.

EVALUATION:
Understanding /
Involvement
Problem solving Timely Completion Total
(3) (10)
(4)
(3)

Signature with date:

Page 30 of 30

You might also like