Download as pdf or txt
Download as pdf or txt
You are on page 1of 87

1. Explain Operators in JAVA.

Arithmetic Operator
Operator Description Example

+ Addition - Adds values on either side of the operator A + B will give


30
- Subtraction - Subtracts right hand operand from left hand A - B will give
operand -10
* Multiplication - Multiplies values on either side of the operator A * B will give 200

/ 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

Operator Description Example


== Checks if the values of two operands are equal or not, if yes (A == B) is not true.
then condition becomes true.
!= Checks if the values of two operands are equal or not, if values (A != B) is
are not equal then condition becomes true. true.
> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is not true.
the value of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.
Relational Operators in JAVA, consider A as 10 & B as 20
Bitwise Operators
Operator Description Example
& Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is
exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is
operand. 0011 1101
^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is
operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary and has (~A ) will give -61 which is
the effect of 'flipping' bits. 1100 0011 in 2's complement
form due to a signed binary
number.
<< Binary Left Shift Operator. The left operands value A << 2 will give 240 which is
is moved left by the number of bits specified by the 1111
right operand. 0000
>> Binary Right Shift Operator. The left operands value A >> 2 will give 15 which is
is moved right by the number of bits specified by the 1111
right operand.
>>> Shift right zero fill operator. The left operands value A >>>2 will give 15 which is
is moved right by the number of bits specified by the 0000
right operand and shifted values are filled up 1111
with zeros.
Bitwise Operators in JAVA, consider A as 60 & B as 13

Logical Operators

Operator Description Example


&& Called Logical AND operator. If both the operands are (A && B) is false.
non-zero, then the condition becomes true.
|| Called Logical OR Operator. If any of the two (A || B) is true.
operands are non-zero, then the condition becomes
true.
! Called Logical NOT Operator. Use to reverses the !(A && B) is true.
logical state of its operand. If a condition is true then
Logical NOT operator will make false.
Logical Operators in JAVA, consider A as true & B as false

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.

Math class methods

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.

Round(), ceil(), floor()

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.

Abs() and signum()

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

Sin(), cos(), tan()

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.

Acos(), asin(), atan()

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() and sqrt()

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(), log(), log10()

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;

public class Program

public static void main(String[] args) {

int a = 5 / 2;

double b = 5 / 2;

double c = 5.0 / 2;

double d = 5 / 2.0;

double e = 5.0 / 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 sum = 10;

int count = 4;

double average = (double)sum / count;

4) Explain following keywords of java with example.


1)Break
2)Continue

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

public class Test {


public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This will produce the following result −

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];

Passing Arrays to Methods


you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an int array −
Example
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
For example, the following statement invokes the printArray method to display 3, 1, 2, 6,
4, and 2 −
Example
printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method


A method may also return an array. For example, the following method returns an array
that is the reversal of another array −

Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {


result[j] = list[i];
}
return result;
}
6) How to declare and Initialize two dimensional Array in Java.
An array of more than one dimension is known as a Multi-dimensional array. Two of the
most common examples of multi-dimensional arrays are two and three-dimensional array
known as 2D and 3D array The length of the two-dimensional array is also fixed. can not
change the length of an array, mean, the number of rows and columns will remain fixed.
A 2x2 array can hold total 4 elements and they can be accessed using row and column
index like a[0][0] will give you elements in the first row and first column, similarly
a[1][1] will give elements from 2nd row and 2nd column. a normal array, the index starts
at 0 and finishes at length -1. 2D arrays are very common on platform games like Super
Mario Bros to represent screen or terrain; 2D arrays can also be used to represent
structures like a spreadsheet.
How to Declare 2 Dimensional Array in Java
How to create one-dimensional array and fact that multi-dimensional arrays are just an
array of the array in Java, then creating a 2-dimensional array is very easy. Instead of one
bracket, here example to use two e.g. int[][] is a two-dimensional integer array. You can
define a 2D array in Java as follows :

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 :

String[][] myArray = new String[5][]; // OK


String[][] yourArray = new String[5][4]; // OK

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 {

public static void main(String[] args) {


String[][] salutation = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Kumar"}
};
// Mr. Kumar
System.out.println(salutation[0][0] + salutation[1][0]);
// Mrs. Kumar
System.out.println(salutation[0][1] + salutation[1][0]);
}
}

The output from this program is:


Mr. Kumar
Mrs. Kumar
In this example, you can see that salutation is a 2D array but its first row has 3 elements
while the second row has just one element.

How to Initialize Two Dimensional Array in Java


just declared and created the array, haven't initialized them. Which means all elements of
the array has their default values e.g. zero for an array of integral values e.g. byte, short,
char and int, 0.0 for floating-point arrays like float and double, false for boolean arrays
and null for an array of reference type like String array elements.

verify this by accessing the first element of a two-dimensional array as multiples[0][0],


which will print zero, as shown below:
boolean[][] booleans = new boolean[2][2];
System.out.println("booleans[0][0] : " + booleans[0][0]);
byte[][] bytes = new byte[2][2];
System.out.println("bytes[0][0] : " + bytes[0][0]);
char[][] chars = new char[1][1];
System.out.println("chars[0][0] : " + (int)chars[0][0]);
short[][] shorts = new short[2][2];
System.out.println("short[0][0] : " + shorts[0][0]);
int[][] ints = new int[3][2];
System.out.println("ints[0][0] : " + ints[0][0]);
long[][] longs = new long[2][2];
System.out.println("longs[0][0] : " + longs[0][0]);
float[][] floats = new float[1][2];
System.out.println("floats[0][0] : " + floats[0][0]);
double[][] doubles = new double[2][2];
System.out.println("doubles[0][0] : " + doubles[0][0]);
Object[][] objects = new Object[2][2];
System.out.println("objects[0][0] : " + objects[0][0]);
Output
booleans[0][0] : false
bytes[0][0] : 0
chars[0][0] : 0
short[0][0] : 0
ints[0][0] : 0
longs[0][0] : 0
floats[0][0] : 0.0
doubles[0][0] : 0.0
objects[0][0] : null

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:

// initializing two dimensional array as literal


String[][] names = {
{"Sam", "Smith"},
{"Robert", "Delgro"},
{"James", "Gosling"},
};

// how to initialize two dimensional array in Java


// using for loop
int[][] board = new int[3][3];

for (int i = 0; i < board.length; i++) {


for (int j = 0; j < board[i].length; j++) {
board[i][j] = i + j;
}
}
In the first example, have to created and initialized String array using an array literal,
while in the second example created a two-dimensional array board, and later initialized it
by looping through the array.

7. What are the Differentiate between constructor and method.

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 is invoked implicitly by the A Method is invoked by the programmer.


system.

A Constructor is invoked when a object is A Method is invoked through method


created using the keyword new. calls.

A Constructor doesn’t have a return type. A Method must have a return type.

A Constructor initializes a object that A Method does operations on an already


doesn’t exist. created object.

Constructor’s name must be same as the A Method’s name can be anything.


name of the class.

8. Describe Primitive data type wrapper class in detail.


A Wrapper class is a class whose object wraps or contains a primitive data types. When create
an object to a wrapper class, it contains a field and in this field, and its store a primitive data
types. In other word a primitive value into a wrapper class object.They convert primitive data
types into objects. Objects are needed if wish to modify the arguments passed into a method
because primitive types are passed by value.The classes in java.util package handles only
objects and hence wrapper classes.Data structures in the Collection framework, such as
ArrayList and Vector, store only objects and not primitive types.An object is needed to support
synchronization in multithreading.
Primitive Data types and their Corresponding Wrapper class
Autoboxing and Unboxing wrapper class.

Autoboxing: Automatic conversion of primitive types to the object of their corresponding


wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to
Long, double to Double etc.
Example:
// Java program to demonstrate Autoboxing

import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';

// Autoboxing- primitive to Character object conversion


Character a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();

// Autoboxing because ArrayList stores only objects


arrayList.add(25);

// printing the values from object


System.out.println(arrayList.get(0));
}
}
Output:

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.

// Java program to demonstrate Unboxing


import java.util.ArrayList;

class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';

// unboxing - Character object to primitive conversion


char a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();


arrayList.add(24);

// unboxing because get method returns an Integer object


int num = arrayList.get(0);

// printing the values from primitive data types


System.out.println(num);
}
}
Output:

24
Implementation

// Java program to demonstrate Wrapping and UnWrapping


// in Java Classes
class WrappingUnwrapping
{
public static void main(String args[])
{
// byte data type
byte a = 1;

// wrapping around Byte object


Byte byteobj = new Byte(a);

// int data type


int b = 10;

//wrapping around Integer object


Integer intobj = new Integer(b);

// float data type


float c = 18.6f;

// wrapping around Float object


Float floatobj = new Float(c);

// double data type


double d = 250.5;

// Wrapping around Double object


Double doubleobj = new Double(d);

// char data type


char e='a';

// wrapping around Character object


Character charobj=e;

// printing the values from objects


System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Byte object byteobj: " + byteobj);
System.out.println("Integer object intobj: " + intobj);
System.out.println("Float object floatobj: " + floatobj);
System.out.println("Double object doubleobj: " + doubleobj);
System.out.println("Character object charobj: " + charobj);

// objects to data types (retrieving data types from objects)


// unwrapping objects to primitive data types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;

// printing the values from data types


System.out.println("Unwrapped values (printing as data types)");
System.out.println("byte value, bv: " + bv);
System.out.println("int value, iv: " + iv);
System.out.println("float value, fv: " + fv);
System.out.println("double value, dv: " + dv);
System.out.println("char value, cv: " + cv);
}
}
Output:

Values of Wrapper objects (printing as objects)


Byte object byteobj: 1
Integer object intobj: 10
Float object floatobj: 18.6
Double object doubleobj: 250.5
Character object charobj: a
Unwrapped values (printing as data types)
byte value, bv: 1
int value, iv: 10
float value, fv: 18.6
double value, dv: 250.5
char value, cv: a
9. What is the Differentiate between StringBuffers and StringBuilders?
StringBuffer StringBuilder

StringBuffer is synchronized i.e. thread StringBuilder is non-synchronized i.e. not


safe. It means two threads can't call the thread safe. It means two threads can call
methods of StringBuffer simultaneously. the methods of StringBuilder
simultaneously.
StringBuffer is less efficient than StringBuilder is more efficient than
StringBuilder. StringBuffer.

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.

There are four types of access modifiers available in java:

1. Default – No keyword required


2. Private
3. Public
4. Protected

Default access modifier:

When no access modifier is specified for a class , method or data member – It is


said to be having the default access modifier by default.The data members, class or methods
which are not declared using any access modifiers i.e. having default access modifier are
accessible only within the same package.In this example create two packages and the classes
in the packages will be having the default access modifiers and we will try to access a class
from one package from a class of second package.

Java program to illustrate default


modifier
package p1;

//Class Geeks is having Default


access modifier
class Geek
{
void display()
{
System.out.println("Hello
World!");
}
}

//Java program to illustrate error


while
//using class from different package
with
//default modifier
package p2;
import p1.*;

//This class is having default access


modifier
class GeekNew
{
public static void main(String
args[])
{
//accessing class Geek from
package p1
Geeks obj = new Geek();

obj.display();
}
}
Output:

Compile time error

Private access modifier:

 The private access modifier is specified using the keyword private.


 The methods or data members declared as private are accessible only within the class in
which they are declared.
 Any other class of same package will not be able to access these members.
 Top level Classes or interface can not be declared as private because
1. private means “only visible within the enclosing class”.
2. protected means “only visible within the enclosing class and any subclasses”
Hence these modifiers in terms of application to classes, they apply only to nested classes
and not on top level classes
In this example, we will create two classes A and B within same package p1. We will declare
a method in class A as private and try to access this method from class B and see the result.
//Java program to illustrate error while
//using class from different package with
//private modifier
package p1;

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

Protected access modifier


protected: The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within same package or
sub classes in different package.
In this example, we will create two packages p1 and p2. Class A in p1 is made public, to
access it in p2. The method display in class A is protected and class B is inherited from class
A and this protected method is then accessed by creating an object of class B.

//Java program to illustrate


//protected modifier
package p1;

//Class A
public class A
{
protected void display()
{
System.out.println("GeeksforGeeks");
}
}

//Java program to illustrate


//protected modifier
package p2;
import p1.*; //importing all classes in package p1

//Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}

}
Output:

GeeksforGeeks

11. Explain String Class in JAVA.

 An object of the String class represents a string of characters.


 The String class belongs to the java.lang package, which does not require an import statement.
 Like other classes, String has constructors and methods.
 Unlike other classes, String has two operators, + and += (used for concatenation).
 Immutability:
o Once created, a string cannot be changed: none of its methods changes the string.
o Such objects are called immutable.
o Immutable objects are convenient because several references can point to the same object
safely: there is no danger of changing an object through one reference without the others
being aware of the change.
o Advantages Of Immutability
 Uses less memory.
o Disadvantages of Immutability
o — you need to create a new string and throw away the old one even for small changes.
 Empty Strings:
o An empty String has no characters. It’s length is 0.
String word1 = "";
String word2 = new String();
 Not the same as an uninitialized String (null
string) private String errorMsg;
 Copy Constructors :
o Copy constructor creates a copy of an existing String. Also rarely used.
o Not the same as an assignment.
o Copy Constructor: Each variable points to a different copy of the String.

o Assignment: Both variables point to the same String.

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

12. Explain Method overloading and Method Overriding.

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:

// Method overriding. class A {


int i, j;
A(int a, int b) {i = a; j = b;
}
// display i and j void show() {
System.out.println("i and j: " + i + " " + j);
}
}
Class B extends A
{
int k;
B(int a, int b, int c) {super(a, b); k = c;
}
// display k – this overrides show() in A void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) { B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

13. What is Exception? Explain types of Exception.

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 user has entered an invalid data.

 A file that needs to be opened cannot be found.

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

Checked exceptions − A checked exception is an exception that is checked (notified) by the


compiler at compilation-time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer should take care of (handle) these
exceptions.

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;

public class FilenotFound_Demo {

public static void main(String args[]) {


File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program, you will get the following exceptions.

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.

Unchecked exceptions − An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.

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 {

public static void main(String args[]) {


int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get the following exception.

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.

14. How to rethrow an exception? Explain with Example.


Sometime need to rethrow an exception in Java. If a catch block cannot handle the particular
exception it has caught, we can rethrow the exception. The rethrow expression causes the
originally thrown object to be rethrown.
Because the exception has already been caught at the scope in which the rethrow expression
occurs, it is rethrown out to the next enclosing try block. Therefore, it cannot be handled by
catch blocks at the scope in which the rethrow expression occurred. Any catch blocks for the
enclosing try block have an opportunity to catch the exception.

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.

Abstract Class Interface


A Java abstract class can have instance Java interface are implicitly abstract
methods that implement a default and cannot have implementations
behavior.
An abstract class may contain non-final Variables declared in a Java interface is
variables. by default final
A Java abstract class can have the usual Members of a Java interface are public
flavors of class members like private, by default
protected, etc..
A Java abstract class should be Java interface should be implemented
extended using keyword “extends”. using keyword “implements”.
A Java class can extend only one A Java class can implement multiple
abstract class. interfaces

17. Explain Comparable and Cloneabal 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.

compareTo(Object obj) method

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

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

Comparable Example

Student.java

class Student implements Comparable<Student>{

int rollno;

String name;

int age;
Student(int rollno,String name,int age){

this.rollno=rollno;

this.name=name;

this.age=age;

public int compareTo(Student st){

if(age==st.age)

return 0;

else if(age>st.age)

return 1;

else

return -1;

File: TestSort1.java

import java.util.*;

public class TestSort1{

public static void main(String args[]){

ArrayList<Student> al=new ArrayList<Student>();

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){

System.out.println(st.rollno+" "+st.name+" "+st.age);

105 Jai 21

101 Vijay 23

106 Ajay 27

Cloneable interface : Cloneable interface is present in java.lang package. There is a


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

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.

Java program to illustrate Cloneable interface

import java.lang.Cloneable;

// By implementing Cloneable interface

// we make sure that instances of class A

// can be cloned.

class A implements Cloneable

int i;

String s;

// A class constructor
public A(int i,String s)

this.i = i;

this.s = s;

// Overriding clone() method

// by simply calling Object class

// clone() method.

@Override

protected Object clone()

throws CloneNotSupportedException

return super.clone();

public class Test

public static void main(String[] args)

throws CloneNotSupportedException

A a = new A(20, "GeeksForGeeks");

// cloning 'a' and holding

// new cloned object reference in b


// down-casting as clone() return type is Object

A b = (A)a.clone();

System.out.println(b.i);

System.out.println(b.s);

Output:

20

GeeksForGeeks

18. Explain Image-View class with Example.

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.

Save this code in a file with the name WritingPixelsExample.java.

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;

public class WritingPixelsExample extends Application {

@Override

public void start(Stage stage) throws FileNotFoundException {

//Creating an image

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

int width = (int)image.getWidth();

int height = (int)image.getHeight();

//Creating a writable image

WritableImage wImage = new WritableImage(width, height);

//Reading color from the loaded image

PixelReader pixelReader = image.getPixelReader();

//getting the pixel writer

PixelWriter writer = wImage.getPixelWriter();

//Reading the color of the image

for(int y = 0; y < height; y++) {

for(int x = 0; x < width; x++) {

//Retrieving the color of the pixel of the loaded image

Color color = pixelReader.getColor(x, y);

//Setting the color to the writable image

writer.setColor(x, y, color.darker());

}
//Setting the view for the writable image

ImageView imageView = new ImageView(wImage);

//Creating a Group object

Group root = new Group(imageView);

//Creating a scene object

Scene scene = new Scene(root, 600, 500);

//Setting title to the Stage

stage.setTitle("Writing pixels ");

//Adding scene to the stage

stage.setScene(scene);

//Displaying the contents of the stage

stage.show();

public static void main(String args[]) {

launch(args);

Compile and execute the saved java file from the command prompt using the following
commands.

Javac WritingPixelsExample.java

java WritingPixelsExample

On executing, the program generates a JavaFX window as follows −


19. Explain inner class with example.

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

2) Method Local inner classes

3) Anonymous inner classes

4) Static nested classes

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 {

// Simple nested inner class class Inner


{ public void show() {

System.out.println("In a nested class method");

class Main {

public static void main(String[] args) { Outer.Inner in = new Outer().new Inner();


in.show();

output:

In a nested class method

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

filter_none edit play_arrow brightness_4 class Outer {

void outerMethod() {
System.out.println("inside outerMethod");

// Inner class is local to outerMethod() class Inner {

void innerMethod() { System.out.println("inside innerMethod");

Inner y = new Inner(); y.innerMethod();

class MethodDemo {

public static void main(String[] args) { Outer x = new Outer(); x.outerMethod();

Output

Inside outerMethod Inside innerMethod


3) Static nested classes: Static nested classes are not technically an inner class. They
are like a static member of outer class.

filter_none edit play_arrow brightness_4 class Outer {

private static void outerMethod() { System.out.println("inside outerMethod");

// A static inner class static class Inner {

public static void main(String[] args) { System.out.println("inside inner class


Method"); outerMethod();

Output

inside inner class Method inside outerMethod


4) Anonymous inner classes: Anonymous inner classes are declared without any
name at all. They are created in two ways.

a) As subclass of specified type filter_none

edit play_arrow brightness_4 class Demo {

void show() {

System.out.println("i am in show method of super class");

class Flavor1Demo {

// An anonymous class with Demo as base class static Demo d = new Demo() {

void show() { super.show();

System.out.println("i am in Flavor1Demo class");

};

public static void main(String[] args){


d.show();

Output

inside inner class Method inside outerMethod Anonymous inner classes

Anonymous inner classes are declared without any name at all. They are created in two
ways.

a) As subclass of specified type filter_none

edit play_arrow brightness_4 class Demo { void show() {

System.out.println("i am in show method of super class");

class Flavor1Demo {

// An anonymous class with Demo as base class


static Demo d = new Demo() { void show() {

super.show();

System.out.println("i am in Flavor1Demo class");

};

public static void main(String[] args){ d.show();

Output

inside inner class Method inside outer Method

20. Explain the Basic structure of JAVAFX program.

A JavaFX application will have three major components namely Stage, Scene and Nodes as
shown in the following diagram.
Stage

A stage (a window) contains all the objects of a JavaFX application. It is represented


by Stage class of the package javafx.stage. The primary stage is created by the platform
itself. The created stage object is passed as an argument to the start() method of
the Application class (explained in the next section).

A stage has two parameters determining its position namely Width and Height. It is
divided as Content Area and Decorations (Title Bar and Borders).

There are five types of stages available −

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

Scene Graph and Nodes

A scene graph is a tree-like data structure (hierarchical) representing the contents of a


scene. In contrast, a node is a visual/graphical object of a scene graph.

A node may include −

 Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon,
etc.

 UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.

 Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.

 Media elements such as Audio, Video and Image Objects.


The Node Class of the package javafx.scene represents a node in JavaFX, this class is the
super class of all the nodes.

As discussed earlier a node is of three types −

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

Phases of Event Handling in JavaFX

Whenever an event is generated, JavaFX undergoes the following phases.

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.

Event Capturing Phase

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.

Event Bubbling Phase

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 Handlers and Filters

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.

Adding and Removing Event Filter

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;

public class RadioButtonTest extends Application {

public static void main(String[] args) {

launch(args);

@Override

public void start(Stage primaryStage) throws Exception {

// TODO Auto-generated method stub

ToggleGroup group = new ToggleGroup();

RadioButton button1 = new RadioButton("option 1");

RadioButton button2 = new RadioButton("option 2");

RadioButton button3 = new RadioButton("option 3");

RadioButton button4 = new RadioButton("option 4");

button1.setToggleGroup(group);

button2.setToggleGroup(group);

button3.setToggleGroup(group);
button4.setToggleGroup(group);

VBox root=new VBox();

root.setSpacing(10);

root.getChildren().addAll(button1,button2,button3,button4);

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

primaryStage.setScene(scene);

primaryStage.setTitle("Radio Button Example");

primaryStage.show();

Output:

23. Write a syntax and Example of CheckBox in UI control.

The Check Box is used to provide more than one choices to the user. It can be used in a
scenario where the user is prompted to select more than one option or the user wants to
select multiple options.

It is different from the radiobutton in the sense that, we can select more than one
checkboxes in a scenerio.

Instantiate javafx.scene.control.CheckBox class to implement CheckBox.

Syntax to create a blank CheckBox.

1. CheckBox checkbox = new CheckBox();

Syntax to a label with the checkbox.

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


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

The following code implements CheckBox into our application.

package application;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.CheckBox;

import javafx.scene.control.Label;

import javafx.scene.layout.HBox;

import javafx.stage.Stage;

public class CheckBoxTest extends Application {

public static void main(String[] args) {

launch(args);

@Override

public void start(Stage primaryStage) throws Exception {

// TODO Auto-generated method stub

Label l = new Label("What do you listen: ");

CheckBox c1 = new CheckBox("Radio one");

CheckBox c2 = new CheckBox("Radio Mirchi");

CheckBox c3 = new CheckBox("Red FM");

CheckBox c4 = new CheckBox("FM GOLD");

HBox root = new HBox();

root.getChildren().addAll(l,c1,c2,c3,c4);

root.setSpacing(5);

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

primaryStage.setScene(scene);

primaryStage.setTitle("CheckBox Example");
primaryStage.show();

Output:

24. Write a JavaFX Slider with Example.

JavaFX slider is used to provide a pane of option to the user in a graphical form where the
user needs to move a slider over the range of values to select one of them. Slider can be
created by instantiating javafx.scene.control.Slider class.

The constructor accepts three arguments:

1)the minimum value,

2) the maximum value, and

3)the initial value of the slider.

package application;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Slider;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class SliderTest extends Application{

public void start(Stage primaryStage) throws Exception {

// TODO Auto-generated method stub


Slider slider = new Slider(1,100,20);

StackPane root = new StackPane();

root.getChildren().add(slider);

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

primaryStage.setScene(scene);

primaryStage.setTitle("Slider Example");

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output:

25. Explain JavaFX ScrollBar class and methods.

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.

The following code implements scrollbar into our application.

package application;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.ScrollBar;
import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class ScrollBar extends Application{

@Override

public void start(Stage primaryStage) throws Exception {

// TODO Auto-generated method stub

ScrollBar s = new ScrollBar();

StackPane root = new StackPane();

root.getChildren().add(s);

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

primaryStage.setScene(scene);

primaryStage.setTitle("ScrollBar Example");

primaryStage.show();

public static void main(String[] args) {

launch(args);

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.

ScrollBar class also provide three methods named as:

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;

public class Progress_Indicator extends Application{

@Override

publicvoid start(Stage primaryStage) throws Exception {


// TODO Auto-generated method stub

ScrollBar s = new ScrollBar();

s.setMin(0);

s.setMax(200);

s.setValue(110);

s.setOrientation(Orientation.VERTICAL);

s.setUnitIncrement(12);

s.setBlockIncrement(10);

StackPane root = new StackPane();

root.getChildren().add(s);

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

primaryStage.setScene(scene);

primaryStage.setTitle("ScrollBar Example");

primaryStage.show();

public static void main(String[] args) {

launch(args);

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;

public class TextFieldTest extends Application {

public static void main(String[] args) {

launch(args);

}
@Override

public void start(Stage primaryStage) throws Exception {

// TODO Auto-generated method stub

Label user_id=new Label("User ID");

Label password = new Label("Password");

TextField tf1=new TextField();

TextField tf2=new TextField();

Button b = new Button("Submit");

GridPane root = new GridPane();

root.addRow(0, user_id, tf1);

root.addRow(1, password, tf2);

root.addRow(2, b);

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

primaryStage.setScene(scene);

primaryStage.setTitle("Text Field Example");

primaryStage.show();

Output:
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

Following is the declaration for Java.io.RandomAccessFile class −

public class RandomAccessFile

Sr.No. Constructor & Description


1 RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and
optionally to write to, the file specified by the File argument.

2 RandomAccessFile(File file, String mode)


This creates a random access file stream to read from, and
optionally to write to, a file with the specified name.

extends Object

implements DataOutput, DataInput, Closeable

Class constructors

Class methods

Sr.No. Method & Description


1 void close()
This method Closes this random access file stream and releases any
system resources associated with the stream.
2 FileChannel getChannel()
This method returns the unique FileChannel object associated with
this file.
3 FileDescriptor getFD()
This method returns the opaque file descriptor object associated
with this stream.

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.

8 int read(byte[] b, int off, int len)


This method reads up to len bytes of data from this file into an array
of bytes.
9 boolean readBoolean()
This method reads a boolean from this file.
10 byte readByte()
This method reads a signed eight-bit value from this file.

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.

24 void setLength(long newLength)


This method sets the length of this file.

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.

27 void write(byte[] b, int off, int len)


This method writes len bytes from the specified byte array starting
at offset off to this file.

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.

39 void writeUTF(String str)


This method writes a string to the file using modified UTF-8
encoding in a machine-independent manner.

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.

// An example of tail recursive function

void print(int n)

if (n < 0) return;

cout << " " << n;

// The last executed statement is recursive call

print(n-1);

Consider the following function to calculate factorial of n. It is a non-tail-recursive


function. Although

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.

// The function is not tail

// recursive because the value

// returned by fact(n-1) is used

// in fact(n) and call to fact(n-1)

// is not the last thing done by

// fact(n)

static int fact(int n)

if (n == 0) return 1;

return n*fact(n-1);

// Driver program

public static void main(String[]


args)

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.

// Java Code for Tail Recursion

class GFG {

// A tail recursive function

// to calculate factorial

static int factTR(int n, int a)

if (n == 0)

return a;

return factTR(n - 1, n * a);

// A wrapper over factTR

static int fact(int n)

return factTR(n, 1);

// Driver code

static public void main


(String[] args)

System.out.println(fact(5));

// This code is contributed by


Smitha.

Output :

120

29. Defining Generic classes and interfaces, Generic methods.

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.

To understand the benefit, let’s say we have a simple class as:

package com.journaldev.generics;

public class GenericsTypeOld {

private Object t;

public Object get() {

return t;

public void set(Object t) {

this.t = t;

public static void main(String args[]){

GenericsTypeOld type = new GenericsTypeOld();


type.set("Pankaj");

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;

public class GenericsType<T> {

private T t;

public T get(){

return this.t;

public void set(T t1){

this.t=t1;

public static void main(String args[]){

GenericsType<String> type = new GenericsType<>();

type.set("Pankaj"); //valid

GenericsType type1 = new GenericsType(); //raw type

type1.set("Pankaj"); //valid

type1.set(10); //valid and autoboxing support

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.

3. Java Generic Interface

Comparable interface is a great example of Generics in interfaces and it’s written as:

package java.lang;

import java.util.*;

public interface Comparable<T> {

public int compareTo(T o);

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.

30. Explain Wildcard Generic types.

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.

Types of Wildcard Generic types, we will learn about

1)Upper bounded wildcards,

2) Unbounded Wildcard,

3) Lower bounded Wildcard

1)Java Generics Upper Bounded 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.

public static double sum(List<Number> list){

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.

The above implementation can be modified like the below program.

package com.journaldev.generics;

import java.util.ArrayList;

import java.util.List;

public class GenericsWildcards {

public static void main(String[] args) {

List<Integer> ints = new ArrayList<>();

ints.add(3); ints.add(5); ints.add(10);

double sum = sum(ints);

System.out.println("Sum of ints="+sum);

public static double sum(List<? extends Number> list){

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.

2) Java Generics Unbounded Wildcard

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

public static void printData(List<?> list){

for(Object obj : list){

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.

3) Java Generics Lower bounded Wildcard

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.

public static void addIntegers(List<? super Integer> list){

list.add(new Integer(50));

31.Explain stack class with example.

Stack is a subclass of Vector that implements a standard last-in, first-out stack.

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 −

Sr.No. Method & Description

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.

4 Object push(Object element)


Pushes the element onto the stack. Element is also returned.

5 int search(Object element)


Searches for element in the stack. If found, its offset from the top of the stack is
returned. Otherwise, -1 is returned.

Example

The following program illustrates several of the methods supported by this collection −

import java.util.*;

public class StackDemo {

static void showpush(Stack st, int a) {

st.push(new Integer(a));

System.out.println("push(" + a + ")");

System.out.println("stack: " + st);

static void showpop(Stack st) {

System.out.print("pop -> ");

Integer a = (Integer) st.pop();


System.out.println(a);

System.out.println("stack: " + st);

public static void main(String args[]) {

Stack st = new Stack();

System.out.println("stack: " + st);

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

This will produce the following result −

Output

stack: [ ]

push(42)

stack: [42]

push(66)

stack: [42, 66]


push(99)

stack: [42, 66, 99]

pop -> 99

stack: [42, 66]

pop -> 66

stack: [42]

pop -> 42

stack: [ ]

pop -> empty stack

32 .Explain Queue classes with methods in detail.

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.

Methods and Properties of the Queue Class

The following table lists some of the commonly used properties of the Queue class −

Sr.No. Property & Description

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 −

Sr.No. Method & Description

1 public virtual void Clear();


Removes all elements from the Queue.
2 public virtual bool Contains(object obj);
Determines whether an element is in the Queue.

3 public virtual object Dequeue();


Removes and returns the object at the beginning of the Queue.

4 public virtual void Enqueue(object obj);


Adds an object to the end of the Queue.

5 public virtual object[] ToArray();


Copies the Queue to a new array.

6 public virtual void TrimToSize();


Sets the capacity to the actual number of elements in the Queue.

Example of Queue −

using System;

using System.Collections;

namespace CollectionsApplication {

class Program {

static void Main(string[] args) {

Queue q = new Queue();

q.Enqueue('A');

q.Enqueue('M');

q.Enqueue('G');

q.Enqueue('W');

Console.WriteLine("Current queue: ");

foreach (char c in q) Console.Write(c + " ");


Console.WriteLine();

q.Enqueue('V');

q.Enqueue('H');

Console.WriteLine("Current queue: ");

foreach (char c in q) Console.Write(c + " ");

Console.WriteLine();

Console.WriteLine("Removing some values ");

char ch = (char)q.Dequeue();

Console.WriteLine("The removed value: {0}", ch);

ch = (char)q.Dequeue();

Console.WriteLine("The removed value: {0}", ch);

Console.ReadKey();

When the above code is compiled and executed, it produces the following result −

Current queue:

AMGW

Current queue:

AMGWVH

Removing values

The removed value: A

The removed value: M


33.Write a short note singletonMap() method.

The singletonMap() method of java.util.Collections class is used to return an immutable


map, mapping only the specified key to the specified value. The returned map is
serializable.

Syntax:

public static Map singletonMap(K key, V value)

Parameters: This method takes the following parameters as a argument:

key – the sole key to be stored in the returned map.

value – the value to which the returned map maps key.

Return Value: This method returns an immutable map containing only the specified key-
value mapping.

The examples of the singletonMap() method

Example 1:

// Java program to demonstrate

// singletonMap() method

// for <String, String> Value

import java.util.*;

public class GFG1 {

public static void main(String[] argv)

throws Exception

try {

// create singleton map

// using singletonMap() method


Map<String, String>

map = Collections

.singletonMap("key", "Value");

// pritning the singletonMap

System.out.println("Singleton map is: "

+ map);

catch (IllegalArgumentException e) {

System.out.println("Exception thrown : " + e);

Output:

Singleton map is: {key=Value}

34. Draw and Explain Thread Life Cycle.

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.

3. Blocked/Waiting state:When a thread is temporarily inactive, then it’s in one of


the following states:

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

If a currently running thread is moved to blocked/waiting state, another thread in the


runnable state is scheduled by the thread scheduler to run. It is the responsibility of
thread scheduler to determine which thread to run.

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.

5. Terminated State: A thread terminates because of either of the following reasons:


• Because it exists normally. This happens when the code of thread has entirely
executed by the program.

• Because there occurred some unusual erroneous event, like segmentation fault or
an unhandled exception.

35. Why synchronization is required in multithreaded programming and how can


we implement it in program?
 When two or more threads need access to a shared resource, they need some way
to ensure that the resource will be used by only one thread at a time. The process by
which this synchronization is achieved is called thread synchronization. The
synchronized keyword in Java creates a block of code referred to as a critical section.
Every Java object with a critical section of code gets a lock associated with the object.
To enter a critical section, a thread needs to obtain the corresponding object's lock.
 Here, object is a reference to the object being synchronized. A synchronized
block ensures that a call to a method that is a member of object occurs only after the
current thread has successfully entered object's monitor.
 Here is an example, using a synchronized block within the run( ) method: This

would produce following result:

// This program uses a synchronized block. class Callme {


void call(String msg) {
System.out.print("[" + msg); try {
Thread.sleep(1000);
} catch (InterruptedException e) { System.out.println("Interrupted");
}
System.out.println("]");
}
}

// File Name : Caller.java


class Caller implements Runnable { String msg;
Callme target; Thread t;
public Caller(Callme targ, String s) { target = targ;
msg = s;
t = new Thread(this); t.start();
}

// synchronize calls to call() public void run() {


synchronized(target) { // synchronized block target.call(msg);
}
}
}
// File Name : Synch.java class Synch {
public static void main(String args[]) { Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target,
"World");
// wait for threads to end try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) { System.out.println("Interrupted");
}
}
}

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;

void put(int a, int b)


{
x = a;
y = b;
}

int sum()
{
int sum;
sum = x + y;
return sum;
}

public class Sumofpoints


{
public static void main(String args[]) throws IOException
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Point X;");
int p = Integer.parseInt(bf.readLine());

System.out.println("Enter Point Y;");


int q = Integer.parseInt(bf.readLine());

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 inputinfo(int r,String n,int s1,int s2,int s3)


{
rollno = r;
name = n;
sub1 = s1;
sub2 = s2;
sub3 = s3;

}
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;
}

public class Studentresult


{
public static void main(String args[])
{
int result;
Studentinfo s = new Studentinfo();
s.inputinfo(101,"Ajay", 80, 85, 90);
s.display();
result = s.totalmarks();
System.out.println("Total Marks:"+result);
}

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

38. Explain mouse and key event handler in JavaFX.


39. Write importance of JAVAFX compare to AWT and Swing.

You might also like