Professional Documents
Culture Documents
Oop 3140705 Ce&it
Oop 3140705 Ce&it
Arithmetic Operator
Operator Description Example
/ Division - Divides left hand operand by right hand operand B / A will give 2
% Modulus - Divides left hand operand by right hand operand B % A will give 0
and returns remainder
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
Arithmetic Operators in JAVA, consider A as 10 & B as 20
Relational Operators
Logical Operators
Assignment Operators
Operator Description Example
= Simple assignment operator, Assigns values from right C = A + B will
side operands to left side operand assign value of A +
B into C
+= Add AND assignment operator, It adds right operand C += A is equivalent
to the left operand and assign the result to left operand to C
=C+A
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent
operand to C
from the left operand and assign the result to left =C-A
operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent
operand with the left operand and assign the result to to C
left operand =C*A
/= Divide AND assignment operator, It divides left C /= A is equivalent
operand with the right operand and assign the result to to C
left operand =C/A
%= Modulus AND assignment operator, It takes modulus C %= A is equivalent
using to
two operands and assign the result to left operand C=C%A
<<= Left shift AND assignment operator C <<= 2 is same as C
= C
<< 2
>>= Right shift AND assignment operator C >>= 2 is same as C
= C
>> 2
&= Bitwise AND assignment operator C &= 2 is same as C
=C
&2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C
=C^2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C =
C|
2
2. Explain primitive Data types of JAVA.
Java defines 8 primitive types:
byte
Smallest integer type
It is a signed 8-bit type (1 Byte)
Range is -128 to 127
Especially useful when working with stream of data from a network or file
Example: byte b = 10;
short
short is signed 16-bit (2 Byte) type
Range : -32768 to 32767
It is probably least used Java type
Example: short vId = 1234;
int
The most commonly used type
It is signed 32-bit (4 Byte) type
Range: -2,147,483,648 to 2,147,483,647
Example: int a = 1234;
long
long is signed 64-bit (8 Byte) type
It is useful when int type is not large enough to hold the desired value
Example: long soconds = 1234124231;
char
It is 16-bit (2 Byte) type
Range: 0 to 65,536
Example: char first = ‘A’; char second = 65;
float
It is 32-bit (4-Byte) type
It specifies a single-precision value
Example: float price = 1234.45213f
double
It uses 64-bit (8-Byte)
All math functions such as sin(),cos(),sqrt() etc… returns double value
o Example: double pi = 3.14141414141414;
boolean
The boolean data type has only two possible values: true and false.
This data type represents one bit of information, but its "size" isn't something
that's precisely defined.
3) Explain the Mathematical functions of java.
The java.lang.Math class allows the use of many common mathematical functions that can
be used while creating programs.Since it is in the java.lang package, the Math class
does not need to be imported. However, in programs extensively utilizing these
functions, a static import can be used.
Math.E
The Math.E constant represents the value of Euler's number (e), the base of the natural
logarithm.
Min(), max()
The simple method: Both functions take two numbers of any data type as parameters. Min()
returns the smallest number, max() returns the greatest one.
All three functions are related to rounding. Round() takes a decimal number as parameter
and returns the rounded number of the double data type.Ceil() upwards and floor() rounds
downwards no matter what. round() very often use. practically used the other functions e.g.
in determining the number of pages of a guestbook. When we have 33 comments and we
print only 10 comments per page, they'll, therefore, occupy 3.3 pages. The result must be
rounded up since there will be actually 4 pages.
Both methods take a number of any type as a parameter. Abs() returns its absolute value and
signum() returns a number based on its sign, -1, 0 or 1 (for a negative number, zero and a
positive number).
Classic trigonometric functions, all take an angle as a double, which has to be entered in
radians (not degrees if your country uses them). To convert degrees to radians we multiply
them by (Math.PI / 180). The return value is also a double.
Inverse trigonometric (arcus, sometimes cyclometric) functions, which return the original
angle according to the trigonometric value. The parameter is a double and the returned angle
is in radians (also as double). If we wish to have an angle in degrees, we have to divide the
radians by (180 / Math.PI).
Pow() takes two double parameters. The first is the base of the power and the second is the
exponent. If we wanted to calculate eg. 23, the code would be as following:
System.out.println(Math.pow(2, 3));
Sqrt is an abbreviation of SQuare RooT, which returns the square root of the number given
as a double. Both functions return a double as the result.
Exp() returns the Euler's number raised to a given exponent. Log() returns the natural
logarithm of a given number. Log10() returns the decadic logarithm of a number. Hopefully,
you noticed that the method list lacks any general root function. We, however, can calculate
it using the functions the Math class provides. that roots work like this: 3rd root of 8 =
8^(1/3). So we can write:
System.out.println(Math.pow(8, (1.0/3.0)));
It's very important to write at least one number with a decimal point when we are dividing,
otherwise, Java will assume that we want it to apply whole-number division, and the result
would have been 8 ^ 0 = 1 in this case.
Division
Programming languages often differ in how they perform the division of numbers. You need
to be aware of these issues to avoid being, unpleasantly, surprised afterwards. Let's write a
simple program:
package onlineapp;
import java.util.Scanner;
int a = 5 / 2;
double b = 5 / 2;
double c = 5.0 / 2;
double d = 5 / 2.0;
// int f = 5 / 2.0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
divide 5/2 for several times in the code, which is mathematically 2.5. Nonetheless, the
results will not be the same in all cases. Can you guess what we'll get in each case? The
code wouldn't compile because of the line with the variable f, which we commented. The
problem is that in this case is that one of the results is a decimal number, which we're trying
to assign to an int variable. The program output will be the following:
Output
2.0
2.5
2.5
2.5
the result of this division is sometimes decimal and sometimes whole. It doesn't really
matter what the data type of the variable we're assigning the result to is. What really matters
is the data type of the numbers we divide by. If one of the numbers is decimal, the outcome
will always result in a decimal number. Division of 2 integers always returns an integer.
Keep in mind that if you compute the average and want a decimal result, at least one
variable must be cast to double.
int count = 4;
1) Break
The break keyword is used to breaks(stopping) a loop execution, which may be a for loop,
while loop, do while or for each loop.
When the break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
Syntax
The syntax of a break is a single statement inside any loop −
break;
Example
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This will produce the following result −
Output
10
20
2)Continue
The continue keyword is used to skip the particular recursion only in a loop execution,
which may be a for loop, while loop, do while or for each loop.
The continue keyword can be used in any of the loop control structures. It causes the loop
to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes control to immediately jump to the update
statement.
In a while loop or do/while loop, control immediately jumps to the Boolean expression.
Syntax
The syntax of a continue is a single statement inside any loop −
continue;
Example
Output
10
20
40
50
5) What is Array in java? Explain Passing and returning array from method.
java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring Array Variables
To use an array in a program, declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an
array variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Creating Arrays
can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
int[][] multiples = new int[4][2]; // 2D integer array with 4 rows and 2 columns
String[][] cities = new String[3][3]; // 2D String array with 3 rows and 3 columns
when you initially declare a two-dimensional array, you must remember to specify the
first dimension, for example following array declaration is illegal in Java.
int[][] wrong = new int[][]; // not OK, you must specify 1st dimension
int[][] right = new int[2][]; // OK
The first expression will throw "Variable must provide either dimension expressions or an
array initializer" error at compile time. On the other hand, the second dimension is
optional and even if you don't specify compiler will not complain, as shown below :
This is possible because a two-dimensional array in Java is nothing but an array of a one-
dimensional array, because of this, you can also create a two-dimensional array where
individual one-dimensional arrays have different length, as seen in the following example.
class TwoDimensionalArray {
default values of different types of primitive arrays here. Character array is a bit tricky
because if you print 0 as a character it will print a null character and used its integer value
by casting to int.Now there are two ways to initialize a two-dimensional array in Java,
either by using an array literal at the time of creation or by using nested for loop and
going through each element.
In the next example, learn how to loop through a two-dimensional array, initialize each
element and how to print a two-dimensional array in Java:
CONSTRUCTORS METHODS
A Constructor is a block of code that A Method is a collection of statements
initializes a newly created object. which returns a value upon its execution.
A Constructor can be used to initialize an A Method consists of Java code to be
object. executed.
A Constructor doesn’t have a return type. A Method must have a return type.
import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
25
Unboxing: It is just the reverse process of autoboxing. Automatically converting an object
of a wrapper class to its corresponding primitive type is known as unboxing. For example
– conversion of Integer to int, Long to long, Double to double etc.
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
24
Implementation
StringBuffer was introduced in Java 1.0 StringBuilder class was introduced in Java
1.5 after looking at shortcomings of
StringBuffer.
StringBuffer is lower than StringBuilder. StringBuilder is faster than StringBuffer
10.Discuss access modifiers in java.
obj.display();
}
}
Output:
class A
{
private void display()
{
System.out.println("GeeksforGeeks");
}
}
class B
{
public static void main(String args[])
{
A obj = new A();
//trying to access private method of another
class
obj.display();
}
}
Output:
error: display() has private access in A
obj.display();
Public access modifier:
public: The public access modifier is specified using the keyword public.
The public access modifier has the widest scope among all other access modifiers.
Classes, methods or data members which are declared as public are accessible from every
where in the program. There is no restriction on the scope of a public data members.
//Java program to illustrate
//public modifier
package p1;
public class A
{
public void display()
{
System.out.println("GeeksforGeeks");
}
}
package p2;
import p1.*;
class B
{
public static void main(String args[])
{
A obj = new A;
obj.display();
}
}
Output:
GeeksforGeeks
//Class A
public class A
{
protected void display()
{
System.out.println("GeeksforGeeks");
}
}
//Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
Output:
GeeksforGeeks
Other Constructors :
o Most other constructors take an array as a parameter to create a String.
char[] letters = {‘J’, ‘a’, ‘v’, ‘a’};
String word = new String(letters);
Methods of String Class in JAVA :
Method Description
char charAt(int index) charAt() function returns the character located at the
specified index.
int indexOf(char ch) Returns the index within this string of the first occurrence of
the specified character.
int compareTo(String o) Compares this String to another Object.
String concat(String str) Concatenates the specified string to the end of this string.
int length() The string length() method returns length of the string.
String trim() The string trim() method eliminates white spaces before and
after string.
String replace(char oc, The string replace() method replaces all occurrence of first
char nc) sequence of character with second sequence of character.
toUpperCase() The java string toUpperCase() method converts this string
into uppercase letter.
toLowerCase() string toLowerCase() method into lowercase letter.
Method overloading
In Java it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different. When this is the case,
the methods are said to be overloaded, and the process is referred to as method overloading.
When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to actually
call. Thus, overloaded methods must differ in the type and/or number of their parameters.
While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
When Java encounters a call to an overloaded method, it simply executes the
version of the method whose parameters match the arguments used in the call.
Example of Method Overloading by changing the no. of arguments: class
Calculation{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(int a,int b,int c){ System.out.println(a+b+c);
}
public static void main(String args[]){ Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Example of Method Overloading by changing data type of argument class
Calculation2{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(double a,double b){ System.out.println(a+b);
}
public static void main(String args[]){ Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Method Overriding.
In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to override
the method in the superclass.
When an overridden method is called from within a subclass, it will always refer to
the version of that method defined by the subclass. The version of the method defined by
the superclass will be hidden. Consider the following:
An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are to be handled.An
exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
A network connection has been lost in the middle of communications or the JVM
has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.Based on these, we have three
categories of Exceptions. You need to understand them to know how exception handling
works in Java.
There are mainly three types of Exceptions in java.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Example
import java.io.File;
import java.io.FileReader;
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Note − Since the methods read() and close() of FileReader class throws IOException, you
can observe that the compiler notifies to handle IOException, along with
FileNotFoundException.
For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Example
public class Unchecked_Demo {
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java)
Errors − These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They are
also ignored at the time of compilation.
Syntax
catch(Exception e) {
System.out.println("An exception was thrown");
throw e;
}
Example
public class RethrowException {
public static void test1() throws Exception {
System.out.println("The Exception in test1() method");
throw new Exception("thrown from test1() method");
}
public static void test2() throws Throwable {
try {
test1();
} catch(Exception e) {
System.out.println("Inside test2() method");
throw e;
}
}
public static void main(String[] args) throws Throwable {
try {
test2();
} catch(Exception e) {
System.out.println("Caught in main");
}
}
}
Output
The Exception in test1() method
Inside test2() method
Caught in main
15. Explain use of finally clause.
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear
path that alters the normal flow through the method. Depending upon how the method is
coded, it is even possible for an exception to cause the method to return prematurely. This
could be a problem in some methods.
For example, if a method opens a file upon entry and closes it upon exit, then you
will not want the code that closes the file to be bypassed by the exception-handling
mechanism. The finally keyword is designed to address this contingency.
Finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block. The finally block will execute
whether or not an exception is thrown. If an exception is thrown, the finally block will
execute even if no catch statement matches the exception.
Any time a method is about to return to the caller from inside a try/catch block, via
an uncaught exception or an explicit return statement, the finally clause is also executed just
before the method returns.
This can be useful for closing file handles and freeing up any other resources that
might have been allocated at the beginning of a method with the intent of disposing of them
before returning. The finally clause is optional. However, each try statement requires at least
one catch or a finally clause.
Here is an example program that shows three methods that exit in various ways, none
without executing their finally clauses:
// Demonstrate finally. class FinallyDemo {
// Through an exception out of the method. static void procA() {
try {
System.out.println("inside procA"); throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block. static void procB() {
try {
System.out.println("inside procB"); return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally. static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) { try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
In this example, procA( ) prematurely breaks out of the try by throwing an
exception. The finally clause is executed on the way out. procB( )’s try statement is exited
via a return statement. The finally clause is executed before procB( ) returns. In procC( ), the
try statement executes normally, without error. However, the finally block is still executed.
Output: inside procA procA’s finally
Exception caught inside procB
procB’s finally inside procC procC’s finally
16. Comparison between Abstract Class and interface.
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.
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.
Comparable Example
Student.java
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
File: TestSort1.java
import java.util.*;
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
105 Jai 21
101 Vijay 23
106 Ajay 27
Invoking Object’s clone method on an instance of the class that does not implement the
Cloneable interface results in an exception CloneNotSupportedException being thrown.
By convention, classes that implement this interface should override Object.clone()
method.
import java.lang.Cloneable;
// can be cloned.
int i;
String s;
// A class constructor
public A(int i,String s)
this.i = i;
this.s = s;
// clone() method.
@Override
throws CloneNotSupportedException
return super.clone();
throws CloneNotSupportedException
A b = (A)a.clone();
System.out.println(b.i);
System.out.println(b.s);
Output:
20
GeeksForGeeks
JavaFX provides classes named PixelReader and PixelWriter classes to read and write
pixels of an image. The WritableImage class is used to create a writable image.
Following is an example which demonstrates how to read and write pixels of an image.
Here, we are reading the color value of an image and making it darker.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
@Override
//Creating an image
writer.setColor(x, y, color.darker());
}
//Setting the view for the writable image
stage.setScene(scene);
stage.show();
launch(args);
Compile and execute the saved java file from the command prompt using the following
commands.
Javac WritingPixelsExample.java
java WritingPixelsExample
Inner class means one class which is a member of another class. There are basically
four types of inner classes in java.
1) Nested Inner class: Nested Inner class can access any private instance variable of
outer class. Like any other instance variable, we can have access modifier private,
protected, public and default modifier.
class Outer {
class Main {
output:
2) Method Local inner classes: Inner class can be declared within a method of an
outer class. In the following example, Inner is an inner class in outerMethod().
void outerMethod() {
System.out.println("inside outerMethod");
class MethodDemo {
Output
Output
void show() {
class Flavor1Demo {
// An anonymous class with Demo as base class static Demo d = new Demo() {
};
Output
Anonymous inner classes are declared without any name at all. They are created in two
ways.
class Flavor1Demo {
super.show();
};
Output
A JavaFX application will have three major components namely Stage, Scene and Nodes as
shown in the following diagram.
Stage
A stage has two parameters determining its position namely Width and Height. It is
divided as Content Area and Decorations (Title Bar and Borders).
Decorated
Undecorated
Transparent
Unified
Utility
You have to call the show() method to display the contents of a stage.
Scene
A scene represents the physical contents of a JavaFX application. It contains all the
contents of a scene graph. The class Scene of the package javafx.scene represents the scene
object. At an instance, the scene object is added to only one stage.
You can create a scene by instantiating the Scene Class. You can opt for the size of the
scene by passing its dimensions (height and width) along with the root node to its
constructor.
Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon,
etc.
Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
Root Node − The first Scene Graph is known as the Root node.
Branch Node/Parent Node − The node with child nodes are known as branch/parent
nodes. The abstract class named Parent of the package javafx.scene is the base class of all
the parent nodes, and those parent nodes will be of the following types −
o Group − A group node is a collective node that contains a list of children nodes.
Whenever the group node is rendered, all its child nodes are rendered in order. Any
transformation, effect state applied on the group will be applied to all the child nodes.
o Region − It is the base class of all the JavaFX Node based UI Controls, such as
Chart, Pane and Control.
o WebView − This node manages the web engine and displays its contents.
Leaf Node − The node without child nodes is known as the leaf node. For example,
Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes.
It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all
the nodes will be clipped to the scene and any alteration in the size of the scene will not
affect the layout of the scene.
21. What is Handling Events? Write down different Phases of Event Handling in Java
FX.
Event Handling is the mechanism that controls the event and decides what should happen,
if an event occurs. This mechanism has the code which is known as an event handler that is
executed when an event occurs.
JavaFX provides handlers and filters to handle events. In JavaFX every event has −
Target − The node on which an event occurred. A target can be a window, scene,
and a node.
Source − The source from which the event is generated will be the source of the
event. In the above scenario, mouse is the source of the event.
Type − Type of the occurred event; in case of mouse event – mouse pressed, mouse
released are the type of events.
Route Construction
Whenever an event is generated, the default/initial route of the event is determined by
construction of an Event Dispatch chain. It is the path from the stage to the source Node.
Following is the event dispatch chain for the event generated, when we click on the play
button in the above scenario.
After the construction of the event dispatch chain, the root node of the application
dispatches the event. This event travels to all nodes in the dispatch chain (from top to
bottom). If any of these nodes has a filter registered for the generated event, it will be
executed. If none of the nodes in the dispatch chain has a filter for the event generated,
then it is passed to the target node and finally the target node processes the event.
In the event bubbling phase, the event is travelled from the target node to the stage node
(bottom to top). If any of the nodes in the event dispatch chain has a handler registered for
the generated event, it will be executed. If none of these nodes have handlers to handle the
event, then the event reaches the root node and finally the process will be completed.
Event filters and handlers are those which contains application logic to process an event. A
node can register to more than one handler/filter. In case of parent–child nodes, you can
provide a common filter/handler to the parents, which is processed as default for all the
child nodes.
As mentioned above, during the event, processing is a filter that is executed and during the
event bubbling phase, a handler is executed. All the handlers and filters implement the
interface EventHandler of the package javafx.event.
To add an event filter to a node, you need to register this filter using the
method addEventFilter() of the Node class.
22. Explain RadioButton with Example.
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.
The following code shows how one radio button is selected from a toggle group.
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
launch(args);
@Override
button1.setToggleGroup(group);
button2.setToggleGroup(group);
button3.setToggleGroup(group);
button4.setToggleGroup(group);
root.setSpacing(10);
root.getChildren().addAll(button1,button2,button3,button4);
primaryStage.setScene(scene);
primaryStage.show();
Output:
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.
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;
launch(args);
@Override
root.getChildren().addAll(l,c1,c2,c3,c4);
root.setSpacing(5);
primaryStage.setScene(scene);
primaryStage.setTitle("CheckBox Example");
primaryStage.show();
Output:
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.
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
root.getChildren().add(slider);
primaryStage.setScene(scene);
primaryStage.setTitle("Slider Example");
primaryStage.show();
launch(args);
Output:
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.
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
root.getChildren().add(s);
primaryStage.setScene(scene);
primaryStage.setTitle("ScrollBar Example");
primaryStage.show();
launch(args);
Output:
Setting values and orientation
As we see in the modern days application, the scrollbar is shown horizontally as well as
vertically. In JavaFX, we can set any of the orientation for the
scrollbar. setOrientation() and passing the Orientation.VERTICAL property into the
method as an argument.
1. setMin()
2. setMax()
3. setValue()
these methods are used to set the minimum, maximum and current value of the scrollbar. It
decides span of the scrollbar. The following code shows the implementation.
package application;
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
s.setMin(0);
s.setMax(200);
s.setValue(110);
s.setOrientation(Orientation.VERTICAL);
s.setUnitIncrement(12);
s.setBlockIncrement(10);
root.getChildren().add(s);
primaryStage.setScene(scene);
primaryStage.setTitle("ScrollBar Example");
primaryStage.show();
launch(args);
Output:
26. Explain the JavaFX 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.
Lets see an example where the user is shown the two text boxes and prompted to fill its
user-id and password.
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;
launch(args);
}
@Override
root.addRow(2, b);
primaryStage.setScene(scene);
primaryStage.show();
Output:
27. How to Declare Random Access File classes and their methods.
RandomAccessFile class file behaves like a large array of bytes stored in the file
system.Instances of this class support both reading and writing to a random access file.
Class declaration
extends Object
Class constructors
Class methods
4 long getFilePointer()
This method returns the current offset in this file.
5 long length()
This method returns the length of this file.
6 int read()
This method reads a byte of data from this file.
7 int read(byte[] b)
This method reads up to b.length bytes of data from this file into an
array of bytes.
11 char readChar()
This method reads a character from this file.
12 double readDouble()
This method reads a double from this file.
13 float readFloat()
This method reads a float from this file.
14 void readFully(byte[] b)
This method reads b.length bytes from this file into the byte array,
starting at the current file pointer.
15 void readFully(byte[] b, int off, int len)
This method reads exactly len bytes from this file into the byte
array, starting at the current file pointer.
16 int readInt()
This method reads a signed 32-bit integer from this file.
17 String readLine()
This method reads the next line of text from this file.
18 long readLong()
This method reads a signed 64-bit integer from this file.
19 short readShort()
This method reads a signed 16-bit number from this file.
20 int readUnsignedByte()
This method reads an unsigned eight-bit number from this file.
21 int readUnsignedShort()
This method reads an unsigned 16-bit number from this file.
22 String readUTF()
This method reads in a string from this file.
23 void seek(long pos)
This method sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write occurs.
25 int skipBytes(int n)
This method attempts to skip over n bytes of input discarding the
skipped bytes.
26 void write(byte[] b)
This method writes b.length bytes from the specified byte array to
this file, starting at the current file pointer.
28 void write(int b)
This method writes the specified byte to this file.
29 void writeBoolean(boolean v)
This method writes a boolean to the file as a one-byte value.
30 void writeByte(int v)
This method writes a byte to the file as a one-byte value.
31 void writeBytes(String s)
This method writes the string to the file as a sequence of bytes.
32 void writeChar(int v)
This method writes a char to the file as a two-byte value, high byte
first.
33 void writeChars(String s)
This method writes a string to the file as a sequence of characters.
34 void writeDouble(double v)
This method converts the double argument to a long using the
doubleToLongBits method in class Double, and then writes that
long value to the file as an eight-byte quantity, high byte first.
35 void writeFloat(float v)
This method converts the float argument to an int using the
floatToIntBits method in class Float, and then writes that int value
to the file as a four-byte quantity, high byte first.
36 void writeInt(int v)
This method writes an int to the file as four bytes, high byte first.
37 void writeLong(long v)
This method writes a long to the file as eight bytes, high byte first.
38 void writeShort(int v)
This method writes a short to the file as two bytes, high byte first.
28. What is Tail Recursion? Can a non-tail recursive function be written as tail-
recursive to optimize it?
A recursive function is tail recursive when recursive call is the last thing executed by the
function. For example the following C++ function print() is tail recursive.
void print(int n)
if (n < 0) return;
print(n-1);
it looks like a tail recursive at first look. If we take a closer look, we can see that the
value returned
by fact(n-1) is used in fact(n), so the call to fact(n-1) is not the last thing done by
fact(n).
class GFG {
// A NON-tail-recursive function.
// fact(n)
if (n == 0) return 1;
return n*fact(n-1);
// Driver program
System.out.println(fact(5));
}
// This code is contributed by Smitha.
Output :
120
The above function can be written as a tail recursive function. The idea is to use one
more argument and accumulate the factorial value in second argument. When n reaches
0, return the accumulated value.
class GFG {
// to calculate factorial
if (n == 0)
return a;
// Driver code
System.out.println(fact(5));
Output :
120
Generic classes :We can define our own classes with generics type. A generic type is a
class or interface that is parameterized over types. We use angle brackets (<>) to specify
the type parameter.
package com.journaldev.generics;
private Object t;
return t;
this.t = t;
String str = (String) type.get(); //type casting, error prone and can cause
ClassCastException
use type casting and it can produce ClassCastException at runtime. Now use java generic
class to rewrite the same class as shown below.
package com.journaldev.generics;
private T t;
public T get(){
return this.t;
this.t=t1;
type.set("Pankaj"); //valid
type1.set("Pankaj"); //valid
the use of GenericsType class in the main method. We don’t need to do type-casting and
we can remove ClassCastException at runtime. If we don’t provide the type at the time of
creation, the compiler will produce a warning that “GenericsType is a raw type.
References to generic type GenericsType<T> should be parameterized”. When we don’t
provide the type, the type becomes Object and hence it’s allowing both String and Integer
objects. But, we should always try to avoid this because we will have to use type casting
while working on raw type that can produce runtime errors.
Comparable interface is a great example of Generics in interfaces and it’s written as:
package java.lang;
import java.util.*;
In similar way, we can create generic interfaces in java. We can also have multiple type
parameters as in Map interface. Again we can provide parameterized value to a
parameterized type also, for example new HashMap<String, List<String>>(); is valid.
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It
makes the code stable by detecting the bugs at compile time.Before generics, we can store
any type of objects in the collection, i.e., non-generic. Now generics force the java
programmer to store a specific type of objects. Question mark (?) is the wildcard in
generics and represent an unknown type. The wildcard can be used as the type of a
parameter, field, or local variable and sometimes as a return type. use wildcards while
invoking a generic method or instantiating a generic class.
2) Unbounded Wildcard,
Upper bounded wildcards are used to relax the restriction on the type of variable in a
method. Suppose we want to write a method that will return the sum of numbers in the list,
so our implementation will be something like this.
double sum = 0;
for(Number n : list){
sum += n.doubleValue();
return sum;
Now the problem with above implementation is that it won’t work with List of Integers or
Doubles because we know that List<Integer> and List<Double> are not related, this is
when an upper bounded wildcard is helpful. We use generics wildcard
with extends keyword and the upper bound class or interface that will allow us to pass
argument of upper bound or it’s subclasses types.
package com.journaldev.generics;
import java.util.ArrayList;
import java.util.List;
System.out.println("Sum of ints="+sum);
double sum = 0;
for(Number n : list){
sum += n.doubleValue();
return sum;
}
It’s similar like writing our code in terms of interface, in the above method we can use all
the methods of upper bound class Number. Note that with upper bounded list, we are not
allowed to add any object to the list except null. If we will try to add an element to the list
inside the sum method, the program won’t compile.
Sometimes we have a situation where we want our generic method to be working with all
types, in this case, an unbounded wildcard can be used. Its same as using <? extends
Object>.
System.out.print(obj + "::");
We can provide List<String> or List<Integer> or any other type of Object list argument to
the printData method. Similar to upper bound list, we are not allowed to add anything to
the list.
Suppose we want to add Integers to a list of integers in a method, we can keep the
argument type as List<Integer> but it will be tied up with Integers whereas List<Number>
and List<Object> can also hold integers, so we can use a lower bound wildcard to achieve
this. We use generics wildcard (?) with super keyword and lower bound class to achieve
this.
pass lower bound or any supertype of lower bound as an argument, in this case, java
compiler allows to add lower bound object types to the list.
list.add(new Integer(50));
Stack only defines the default constructor, which creates an empty stack. Stack includes all
the methods defined by Vector, and adds several of its own.
Stack( )
the methods inherited from its parent class Vector, Stack defines the following methods −
1 boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if
the stack contains elements.
2 Object peek( )
Returns the element on the top of the stack, but does not remove it.
3 Object pop( )
Returns the element on the top of the stack, removing it in the process.
Example
The following program illustrates several of the methods supported by this collection −
import java.util.*;
st.push(new Integer(a));
System.out.println("push(" + a + ")");
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
Output
stack: [ ]
push(42)
stack: [42]
push(66)
pop -> 99
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
Queue represents a first-in, first out collection of object. It is used when you need a first-in,
first-out access of items. When you add an item in the list, it is called enqueue, and when
you remove an item, it is called deque.
The following table lists some of the commonly used properties of the Queue class −
1 Count
Gets the number of elements contained in the Queue
The following table lists some of the commonly used methods of the Queue class −
Example of Queue −
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
q.Enqueue('A');
q.Enqueue('M');
q.Enqueue('G');
q.Enqueue('W');
q.Enqueue('V');
q.Enqueue('H');
Console.WriteLine();
char ch = (char)q.Dequeue();
ch = (char)q.Dequeue();
Console.ReadKey();
When the above code is compiled and executed, it produces the following result −
Current queue:
AMGW
Current queue:
AMGWVH
Removing values
Syntax:
Return Value: This method returns an immutable map containing only the specified key-
value mapping.
Example 1:
// singletonMap() method
import java.util.*;
throws Exception
try {
map = Collections
.singletonMap("key", "Value");
+ map);
catch (IllegalArgumentException e) {
Output:
A Thread in Java at any point of time exists in any one of the following states. A thread
lies only in one of the shown states at any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated
The diagram shown below represent various states of a thread at any instant of time.
1. New Thread: When a new thread is created, it is in the new state. The thread has
not yet started to run when thread is in this state. When a thread lies in the new state, it’s
code is yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to runnable state. In this
state, a thread might actually be running or it might be ready run at any instant of time.
It is the responsibility of the thread scheduler to give the thread, time to
run. A multi-threaded program allocates a fixed amount of time to each individual
thread. Each and every thread runs for a short while and then pauses and relinquishes
the CPU to another thread, so that other threads can get a chance to run. When this
happens, all such threads that are ready to run, waiting for the CPU and the currently
running thread lies in runnable state.
• Blocked
• Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked state.
It’s the responsibility of the thread scheduler to reactivate and schedule a
blocked/waiting thread. A thread in this state cannot continue its execution any further
until it is moved to runnable state. Any thread in these states does not consume any CPU
cycle.
A thread is in the blocked state when it tries to access a protected section of code that is
currently locked by some other thread. When the protected section is unlocked, the
schedule picks one of the thread which is blocked for that section and moves it to the
runnable state. Whereas, a thread is in the waiting state when it waits for another thread
on a condition. When this condition is fulfilled, the scheduler is notified and the waiting
thread is moved to runnable state.
4. Timed Waiting: A thread lies in timed waiting state when it calls a method with
a time out parameter. A thread lies in this state until the timeout is completed or until a
notification is received. For example, when a thread calls sleep or a conditional wait, it
is moved to a timed waiting state.
• Because there occurred some unusual erroneous event, like segmentation fault or
an unhandled exception.
Output:
[Hello]
[World]
[Synchronized]
36. Write a class name “Point” having data member X and Y of integer type. Write a function to
input two points and display addition of two points.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Point
{
int x;
int y;
int sum()
{
int sum;
sum = x + y;
return sum;
}
int result;
Point objp = new Point();
objp.put(p,q);
result = objp.sum();
System.out.println("The Sum of X and Y is:" + result);
Output
Enter Point X:
10
Enter Point Y:
20
The Sum of X and Y is:30
37. Write a Java Program to create a class student having following data members : rollno, name,
sub1, sub2, sub3. Display the rollno, name, marks, total marks of student
class Studentinfo
{
int rollno;
String name;
int sub1,sub2,sub3;
}
void display()
{
System.out.println("Roll No:" + rollno);
System.out.println("Name:" + name);
System.out.println("Sub1:"+sub1);
System.out.println("Sub2:"+sub2);
System.out.println("Sub3:"+sub3);
int totalmarks()
{
int total = sub1 + sub2 + sub3;
return total;
}
Output
Roll No:101
Name:Ajay
Sub1:80
Sub2:85
Sub3:90
Total Marks:255
38. Write a program in java to demonstrate use of parameterized constructor using ‘this’ keyword.
class Rectangle
{
int length,height;
Rectangle(int len ,int hei)
{
this.length = len;
this.height = hei;
}
}
public class Main
{
public static void main(String[] args)
{
Rectangle rec = new Rectangle(20, 10);
System.out.println("Rec.length = " + rec.length);
System.out.println("Rec.breath = " + rec.height);
}
}
Output
Rec.length = 20
Rec.height = 10