(Solved) OOP 1 IMP Questions
(Solved) OOP 1 IMP Questions
1
Sahil Vahora
2
Sahil Vahora
Just in Time (JIT) is runs after the program has started executing, on the
fly. It has access to runtime information and makes optimizations of the
code for better performance.
API are important software components bundled with the JDK. APIs in
Java include classes, interfaces, and user Interfaces. They enable
developers to integrate various applications and websites and offer real-
time information.
3
Sahil Vahora
Example:
class Main {
public static void main(String[] args)
{
System.out.println("I am a Geek");
}
}
Output:
I am a Geek
Example:
import java.util.Scanner;
class Main{
public static void main(String[]args) {
Scanner a = new Scanner(System.in);
a.nextInt();
System.out.println(a);
}
}
4
Sahil Vahora
Methods Description
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
1. Primitive data types: The primitive data types include Boolean, char, byte,
short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
5
Sahil Vahora
Example :
class Main {
public static void main(String[] args) {
byte range;
range = 124;
System.out.println(range);
short temperature;
temperature = -200;
System.out.println(temperature);
int a = -4250000;
System.out.println(a);
long b = -42332200000L;
System.out.println(b);
}
}
6
Sahil Vahora
There are many types of operators in Java which are given below:
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Assignment Operator.
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
7
Sahil Vahora
Example:
public class Main{
public static void main(String args[]){
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}
}
Converting a lower data type into a higher one is called widening type casting. It
is also known as implicit conversion or casting down. It is done automatically. It is
safe because there is no chance to lose data.
Converting a higher data type into a lower one is called narrowing type casting. It
is also known as explicit conversion or casting up. It is done manually by the
programmer.
8
Sahil Vahora
9
Sahil Vahora
Example:
public class JavaNestedIfExample {
public static void main(String[] args) {
int age=20;
int weight=80;
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}
}
Syntax:
switch(expression){
case value1:
break;
case value2:
break;
default:
}
10
Sahil Vahora
Example:
11
Sahil Vahora
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Example:
class Main{
public static void main(String[]args) {
12
Sahil Vahora
a[0] = 1;
a[1] = 2;
a[2] = 3;
b[0][0] = 5;
b[0][1] = 3;
b[1][0] = 8;
b[1][1] = 6;
System.out.println(b[1][1]);
System.out.println(a[2]);
}
}
13
Sahil Vahora
Object:
You will find yourself surrounded by the number of objects which have certain
characteristics and behaviours.
For example, we can say ‘Orange’ is an object. Its characteristics are: spherical
in shape and colour is orange. Its behaviour is: juicy and tastes sweet-sour.
Class:
For example, we can consider a car as a class that has characteristics like
steering wheels, seats, brakes, etc. And its behaviour is mobility. But we can
say Honda City having a reg.number 4654 is an ‘object’ that belongs to the
class ‘car’.
It was a brief description of objects and classes. Now we will understand the
Java class in detail.
14
Sahil Vahora
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
15
Sahil Vahora
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
16
Sahil Vahora
Abstraction Encapsulation
Abstraction is the process or While encapsulation is the process or
method of gaining the method to contain the information.
information.
The objects that help to perform Whereas the objects that result in
abstraction are encapsulated. encapsulation need not be abstracted.
17
Sahil Vahora
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Associated Class
A Wrapper class is used to create an A Primitive type is not an object
object; therefore, it has a corresponding so it does not belong to a class.
class.
Null Values
The wrapper class objects allow null A primitive data type does not
values. allow null values.
Memory Required
Required memory is higher than the Required memory is lower
primitive types. The Clustered Index comparing to wrapper classes.
does not require an additional space.
Collections
A Wrapper class can be used with a A primitive type is not used with
collection such as ArrayList, etc. collections.
18
Sahil Vahora
o Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
The extends keyword indicates that you are making a new class that derives from
an existing class. The meaning of "extends" is to increase the functionality.
19
Sahil Vahora
Example:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
20
Sahil Vahora
Every time an object is created using the new() keyword, at least one constructor
is called.
21
Sahil Vahora
Example:
class Bike1{
Bike1(){
System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Example:
class Student5{
int id;
String name;
int age;
r
Student5(int i,String n){
id = i;
name = n;
}
22
Sahil Vahora
If we have to perform only one operation, having same name of the methods
increases the readability of the program
In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.
Example :
class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
23
Sahil Vahora
Output :
22
33
In this example, we have created two methods that differs in data type
The first add method receives two integer arguments and second add method
receives two double arguments.
Example :
class Adder{
static int add(int a, int b){
return a+b;
}
static double add(double a, double b){
return a+b;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
Output :
22
24.9
24
Sahil Vahora
25
Sahil Vahora
Example:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);
System.out.println(super.color);
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
It provides random access to its elements. Random access means that we can
grab any element at constant time.
The difference between a built-in array and an ArrayList in Java, is that the size
of an array cannot be modified (if you want to add or remove elements to/from an
array, you have to create a new one). While elements can be added and removed
from an ArrayList whenever you want.
Syntax:
import java.util.ArrayList;
Example :
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
26
Sahil Vahora
System.out.println(list);
}
}
Methods Descriptions
The static keyword belongs to the class than an instance of the class.
27
Sahil Vahora
In this tutorial, we will learn about Java exceptions, its types, and the difference
between checked and unchecked exceptions.
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions. Let's consider a scenario:
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
28
Sahil Vahora
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
3) Error
Keyword Description
try The "try" keyword is used to specify a block where we should place
an exception code. It means we can't use try block alone. The try
block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
Example:
public class Main {
public static void main(String args[]) {
try {
int i = 1 / 100;
}
catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("Error");
}
29
Sahil Vahora
A finally block contains all the crucial statements that must be executed
whether exception occurs or not.
The statements present in this block will always execute regardless of
whether exception occurs in try block or not such as closing a
connection, stream etc.
A finally block must be associated with a try block, you cannot use finally
without a try block. You should place those statements in this block that
must be executed always.
Finally block is optional, as we have seen in previous tutorials that a try-
catch block is sufficient for exception handling, however if you place a
finally block then it will always run after the execution of try block.
In normal case when there is no exception in try block then the finally
block is executed after try block. However if an exception occurs then
the catch block is executed before finally block.
An exception in the finally block, behaves exactly like any other exception.
The statements present in the finally block execute even if the try block
contains control transfer statements like return, break or continue.
Example:
class Main{
public static void main(String args[]){
System.out.println(JavaFinally.myMethod());
}
public static int myMethod()
{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}
30
Sahil Vahora
There can be only abstract methods in the Java interface, not method body. It is
used to achieve abstraction and multiple inheritance in Java
In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Example:
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
31
Sahil Vahora
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.
32
Sahil Vahora
Class Interface
A class can be instantiated An interface can never be instantiated
A class can extend only one class but An interface can extend any number
can implement any number of of interfaces but cannot implement
interfaces any interface
33
Sahil Vahora
Comparable Comparator
Comparable provides Comparator provides compare() method
compareTo() method to sort to sort elements in Java.
elements in Java.
Comparable interface is present Comparator interface is present in java.util
in java.lang package. package.
34
Sahil Vahora
Example:
public class Main{
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
public static void main(String args[]){
try{
method();
}
catch(ArithmeticException e){
System.out.println("caught in main() method");
}
}
}
35
Sahil Vahora
Creating a Button
You create a button control by creating an instance of the Button class. Here is a
JavaFX Button instantiation example:
Creating a RadioButton
Creating a CheckBox
You create a JavaFX CheckBox control via the CheckBox constructor. Here is a
JavaFX CheckBox instantiation example:
36
Sahil Vahora
Creating a ListView
The JavaFX ListView control enables users to choose one or more options from a
predefined list of choices. The JavaFX ListView control is represented by the
class javafx.scene.control.ListView . This JavaFX ListView tutorial will explain
how to use the ListView class.
You create a ListView simply by creating a new instance of the ListView class.
Here is a JavaFX ListView instantiation example:
You can add items (options) to a ListView by obtaining its item collection and add
items to it. Here is an example that adds items to a JavaFX ListView :
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Creating a ToggleButton
ToggleButton Text
You can set or change the text of a JavaFX ToggleButton via its setText() method.
Here is an example of changing the text of a JavaFX ToggleButton via setText():
toggleButton.setText("New Text");
37
Sahil Vahora
Creating a TextField
You create a TextField control by creating an instance of the TextField class. Here
is a JavaFX TextField instantiation example:
You can set the text of a TextField using its setText() method. This is often useful
when you need to set the initial value for at text field that is part of a form. For
instance, editing an existing object or record. Here is a simple example of setting
the text of a JavaFX TextField:
textField.setText("Initial value");
1 HBox
The HBox layout arranges all the nodes in our application in a single
horizontal row.
The class named HBox of the package javafx.scene.layout represents the
text horizontal box layout.
2 VBox
The VBox layout arranges all the nodes in our application in a single
vertical column.
The class named VBox of the package javafx.scene.layout represents the
text Vertical box layout.
3 BorderPane
The Border Pane layout arranges the nodes in our application in top, left,
right, bottom and center positions.
The class named BorderPane of the
package javafx.scene.layout represents the border pane layout.
38
Sahil Vahora
4 StackPane
The stack pane layout arranges the nodes in our application on top of
another just like in a stack. The node added first is placed at the bottom of
the stack and the next node is placed on top of it.
The class named StackPane of the
package javafx.scene.layout represents the stack pane layout.
5 TextFlow
The Text Flow layout arranges multiple text nodes in a single flow.
The class named TextFlow of the package javafx.scene.layout represents
the text flow layout.
6 AnchorPane
The Anchor pane layout anchors the nodes in our application at a
particular distance from the pane.
The class named AnchorPane of the
package javafx.scene.layout represents the Anchor Pane layout.
7 TilePane
The Tile Pane layout adds all the nodes of our application in the form of
uniformly sized tiles.
The class named TilePane of the package javafx.scene.layout represents
the TilePane layout.
8 GridPane
The Grid Pane layout arranges the nodes in our application as a grid of
rows and columns. This layout comes handy while creating forms using
JavaFX.
The class named GridPane of the package javafx.scene.layout represents
the GridPane layout.
9 FlowPane
The flow pane layout wraps all the nodes in a flow. A horizontal flow pane
wraps the elements of the pane at its height, while a vertical flow pane
wraps the elements at its width.
The class named FlowPane of the package javafx.scene.layout represents
the Flow Pane layout.
39
Sahil Vahora
RGB Color
RGB color system is the most popular method to create a color in graphics. It
consists of three components named as RED → R, GREEN → G and BLUE → B.
Each component uses 8 Bits that means every component can have the integer
value from 0 to 22^8 - 1=255.
The computer screen can be seen as the collection of pixels. The set (R,G,B)
actually represents the emission of their respective LEDs on the screen.
If the value of RED is set to 0 then it means that the Red LED is turned off while
the value 255 indicates that the full emission of LED is being there. The
combination of (0,0,0) represents the black color while (255,255,255) represents
the white color. The middle values in that range can represent different colors.
There is a static method named as rgb() of Color class. It accepts three integer
arguments as Red, Green, Blue and one optional double argument called alpha.
The value of alpha is proportional to the opacity of the color. The alpha value 0
means that the color is completely transparent while the value 1 means that the
color is completely opaque.
JavaFX allows you to work with all popular image formats. Let's use
class javafx.scene.image.Image to load images from hard drive or a network
image sources. In order to display images on JavaFX, you use ImageView class.
javafx.scene.image.Image
Image image = new Image(input);
Image(InputStream inputStream)
40
Sahil Vahora
Image(String url)
import javafx.scene.image.ImageView;
We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
Additionally, it can access all the members of the outer class, including private
data members and methods.
41
Sahil Vahora
Example:
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
42
Sahil Vahora
OutputStream vs InputStream
OutputStream
InputStream
Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
Example:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedInputStreamExample {
public static void main(String args[]) throws IOException {
inputStream.read(bytes);
43
Sahil Vahora
outputStream.write(bytes);
outputStream.flush();
System.out.println("Data successfully written in the specified file");
}
}
Generics make a class, interface and, method, consider all (reference) types that
are given dynamically as parameters. This ensures type safety. Generic class
parameters are specified in angle brackets “<>” after the class name as of the
instance variable.
Example:
import java.io.*;
class GenericConstructor {
private double v;
44
Sahil Vahora
45
Sahil Vahora
A thread in Java is the direction or path that is taken while a program is being
executed. Generally, all the programs have at least one thread, known as the
main thread that is provided by the JVM or Java Virtual Machine at the starting
of the program’s execution.
In Java, a thread always exists in any one of the following states. These states
are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
New: Whenever a new thread is created, it is always in the new state. For a thread
in the new state, the code has not been run yet and thus has not begun its
execution.
Active: When a thread invokes the start() method, it moves from the new state to
the active state. The active state contains two states within it: one is runnable,
and the other is running.
o Runnable: A thread that is ready to run is then moved to the runnable state.
In the runnable state, the thread may be running or may be ready to run at
any given instant of time. It is the duty of the thread scheduler to provide
the thread time to run, i.e., moving the thread the running state.
46
Sahil Vahora
For example, a thread (let's say its name is A) may want to print some data from
the printer. However, at the same time, the other thread (let's say its name is B) is
using the printer to print some data. Therefore, thread A has to wait for thread B
to use the printer. Thus, thread A is in the blocked state. A thread in the blocked
state is unable to perform any execution and thus never consume any cycle of
the Central Processing Unit (CPU). Hence, we can say that thread A remains idle
until the thread scheduler reactivates thread A, which is in the waiting or blocked
state.
When the main thread invokes the join() method then, it is said that the main
thread is in the waiting state. The main thread then waits for the child threads to
complete their tasks. When the child threads complete their job, a notification is
sent to the main thread, which again moves the thread from waiting to the active
state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of
the thread scheduler to determine which thread to choose and which one to
reject, and the chosen thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread
(its name is A) has entered the critical section of a code and is not willing to leave
that critical section. In such a scenario, another thread (its name is B) has to wait
forever, which leads to starvation. To avoid such scenario, a timed waiting state
is given to thread B. Thus, thread lies in the waiting state for a specific span of
time, and not forever. A real example of timed waiting is when we invoke the
sleep() method on a specific thread. The sleep() method puts the thread in the
timed wait state. After the time runs out, the thread wakes up and start its
execution from when it has left earlier.
47
Sahil Vahora
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words,
the thread is dead, and there is no way one can respawn (active after kill) the dead
thread.
The following diagram shows the different states involved in the life cycle of a
thread.
4. Multiple null elements can be stored. 4. Null element can store only
once.
48
Sahil Vahora
The static variable is a class level variable and it is common to all the class objects
i.e. a single copy of the static variable is shared among all the class objects.
A static method manipulates the static variables in a class. It belongs to the class
instead of the class objects and can be invoked without using a class object.
The static initialization blocks can only initialize the static instance variables.
These blocks are only executed once when the class is loaded.
Example:
public class Demo {
static int x = 10;
static int y;
static void func(int z) {
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
static {
System.out.println("Running static initialization block.");
y = x + 5;
}
public static void main(String args[]) {
func(8);
}
}
Disadvantages:
Generics don't work with primitive types.
We can't create Generic Arrays
We cannot create an instance of a type parameter.
We cannot create, catch, or throw generic types.
Due to type erasure, you cannot use instance of with generic types.
We cannot declare static fields of a type parameter.
49
Sahil Vahora
Advantages:
There are basically three main advantages of generics in Java.
Types of synchronization:
1. Process synchronization
2. Thread synchronization
1. Mutual Exclusive
2. Inter-Thread Communication
50
Sahil Vahora
A. Mutual Exclusive
While sharing any resource, this will keep the thread interfering with one another
i.e. mutual exclusive. We can achieve this via
Synchronized Method
Synchronized Block
Static Synchronization
Synchronized Method
Implementation:
Example:
try {
Thread.sleep(600);
}
catch (Exception ex) {
System.out.println(ex.toString());
}
}
System.out.println("--------------------------");
try {
Thread.sleep(1000);
}
51
Sahil Vahora
}
}
}
public class Thread1 extends Thread {
PrintTest test;
Thread1(PrintTest p) { test = p; }
test.printThread(1);
}
}
PrintTest test;
Thread2(PrintTest p) { test = p; }
52