0% found this document useful (0 votes)
34 views

Qa 12 JP

The document describes the key characteristics of object-oriented programming, including objects, classes, abstraction, encapsulation, inheritance, and polymorphism. Objects are real-world entities with properties (attributes) and behaviors (methods). Classes define the common properties and behaviors of objects. Abstraction hides unnecessary details and there are two types: abstract classes and abstract methods. Encapsulation binds code and data together and hides implementation details. Inheritance allows classes to inherit properties from other classes in a hierarchy. Polymorphism allows one action to be performed in different ways.

Uploaded by

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

Qa 12 JP

The document describes the key characteristics of object-oriented programming, including objects, classes, abstraction, encapsulation, inheritance, and polymorphism. Objects are real-world entities with properties (attributes) and behaviors (methods). Classes define the common properties and behaviors of objects. Abstraction hides unnecessary details and there are two types: abstract classes and abstract methods. Encapsulation binds code and data together and hides implementation details. Inheritance allows classes to inherit properties from other classes in a hierarchy. Polymorphism allows one action to be performed in different ways.

Uploaded by

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

11a.1 Describe the characteristics of object-oriented programming?

Answer:
• Object Oriented Programming is a Methodology or Paradigm.
• In OOP an Object represents an entity in the real world.
• An OOP program, a collection of objects that interact to solve a task/problem.
Characteristics of Object-Oriented Programming

1. Objects
• Objects are basic concepts of Object Oriented Programming which revolve around the
real life entities.
• Objects are real-world entity such as book, cat, house, pencil, person, etc. Any things
we see, that could be differentiated from another is called object.
• Objects should have a well-defined boundary.
• An object is an instance of a class.
• Every object has its own set of properties, which defines the state of the object and
its own behavior.
• State: It is represented by attributes of an object. It also reflects the properties of an
object.
• Behavior: It is represented by methods of an object. It also reflects the response of an
object with other objects.
• Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Creating Object
• When an object is instantiated / created memory is allocated.
• A software object maintains its state in variables and implements its behavior with
methods.
• Objects are the building blocks of Object-Oriented Programming
Using new keyword
• The new keyword is used to create objects.
Syntax:
ClassName objectName = new ClassName();
Example:
Employee empOne = new Employee(“Vijayakumar S”);
Object Creation has three parts
1. Declaration: Variable declarations that associate a variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which initialize
the new object.
2. Class
• Classes are basic concepts of Object-Oriented Programming.
• A class is a blueprint or a template from which individual objects are created.
• A class is a collection of data members (Fields) and member functions (Methods).
• A class is a group of objects which have common properties.
• It is a logical entity (A class is a logical grouping of data and functions).
• When a class is defined, no memory is allocated.

Syntax of Class:
Access modifier class ClassName
{
fields;
methods;
constructors;
}

Declaring class in Java.


Every class in Java can be composed of the following elements:
• fields
• methods
• constructors

Class declarations can include


• Modifiers such as public, private.
• The class name, with the initial letter capitalized by convention.
• The class body, surrounded by braces, {}.
Example:

3.Abstraction
• Abstraction is the concept of object-oriented programming that “shows” only essential
attributes and “hides” unnecessary information.
• The main purpose of abstraction is hiding the unnecessary details from the users.
• An abstract class or method is defined with abstract keyword.
• Example: When we are driving a car, we are only concerned about driving the car
start/stop the car, accelerate, break, etc. we are not concerned about the actual
mechanism works internally.
Types of Abstraction
1. Abstract Class
2. Abstract Methods
Syntax
abstract class ParentClass
{
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3(): string;
}
4. Encapsulation
• Encapsulation is defined as the wrapping up of data under a single unit.
• It is the mechanism that binds together code and the data it manipulates.
• Encapsulation is a protective shield that prevents the data from being accessed by the
code outside this shield.
• Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which
they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
5. Inheritance
• Inheritance is the mechanism by which one object is allowed to derive the
properties (fields and methods) of another. Inheritance in OOP = When a class
derives from another class.
• The class features are inherited is known as super class (or a base class or a parent
class). The class that inherits the other class is known as sub class (or a derived class,
extended class, or child class).
• Inheritance supports reusability.
• An inherited class is defined by using the extends keyword.
6. Polymorphism
• Polymorphism is the ability of an object to take on many forms.
• Polymorphism is a concept by which a single action can be performed by different
ways.
There are two types of polymorphism:

11a.2. Describe abstraction and its types with example?


Answer:
• Abstraction is the concept of object-oriented programming that “shows” only
essential attributes and “hides” unnecessary information.
• The main purpose of abstraction is hiding the unnecessary details from the users.
• In other words, it deals with the outside view of an object.
• Ex: When we are driving a car, we are only concerned about driving the car start/stop
the car, accelerate, break, etc. we are not concerned about the actual mechanism
works internally.
• Abstraction in Object Oriented Programming helps to reduce the complexity of
the design and implementation process of software.
Types of Abstraction
1. Abstract Class
2. Abstract Methods
Abstract Class
• Abstract Class is a type of class in OOPs, that declare one or more abstract methods.
• These classes can have abstract methods as well as concrete methods. A normal class
cannot have abstract methods.
• An abstract class is a class that contains at least one abstract method.
Abstract Method
• Abstract Method is a method that has just the method definition but does not contain
implementation.
• A method without a body is known as an Abstract Method. It must be declared in an
abstract class.
• The abstract method will never be final because the abstract class must implement all
the abstract methods.
An abstract class or method is defined with abstract keyword.
Syntax
abstract class ParentClass
{
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
Example of Abstract class that has an abstract method
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
Output:
running safely
11a.3 Describe interface and its types with example?
Answer:

• An interface in Java is a blueprint of a class. It has static constants and abstract


methods.
• The interface in Java is a mechanism to achieve abstraction.
• There can be only abstract methods in the Java interface, not method body. It is used
to achieve abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
• Java Interface also represents the IS-A relationship.

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

• It is used to achieve abstraction.


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

Syntax of interface declaration:

We can implement the interface in two different ways as following,


1. Implicit
2. Explicit
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output:
Hello

11a.4 Explain methods?


Answer:
A method is defined as a sequence of some declaration and execution statements.
These statements gather together to perform a specific task. A function or a method must be
defined before it is used anywhere in the program.
Syntax:
[access-specifier] [modifier] return-type function-name ([parameter list])
{
body of the function/method;
}

1. Access specifier
It can be public or protected or private or default. It is optional to use an access specifier
while defining a method.
2. Modifier
It can be static, final, synchronized, transient, and volatile. It is optional to use a modifier
3. Return-Type
It specifies the type of value that the return statement of the function returns. It may be any
valid Java data type. If no value is being returned, we use the return type as void.
4. Function-name
The name of the function should be a valid Java identifier. The naming conventions generally
followed for method names are:
✔ It should be meaningful.

✔ It should begin with a lowercase letter. For names having multiple words, we use the
camelCase naming convention.
For example:

✔ printReportCard()

✔ getMarks()
The method name should generally begin with a verb followed by one or more nouns.
For example:

✔ readData

✔ findFile

✔ calculateInterestAmount
5. Parameter list
The parameter list is a comma-separated list of variables of a function referred to as
arguments or parameters. A function may be without any parameters and in this case, the
parameter list is empty.
6. Method Body
The body of the Java method should be enclosed within curly braces{} containing all the
code to perform operations and tasks..
Example method definition:

11a.5 Description of object-oriented programming analysis process and structure-


oriented analysis process?
Answer:
Object-oriented analysis
• It is concerned with modeling the application domain.
• The main focus in on data structure and real-world objects that are important.
• It uses Incremental or Iterative methodology to refine and extend our design.
• It is suitable for large projects with changing user requirements.
• Risk while using this analysis technique is low and reusability is also high.
• Requirement engineering includes Use case model (find Use cases, Flow of events,
Activity Diagram), the Object model (find Classes and class relations, Object
interaction, Object to ER mapping), Statechart Diagram, and deployment diagram.
• This technique is new and is mostly preferred.
Structured Analysis
• The main focus is on process and procedures of system.
• It uses System Development Life Cycle (SDLC) methodology for different purposes
like planning, analyzing, designing, implementing, and supporting an information
system.
• It is suitable for well-defined projects with stable user requirements. Risk while using
this analysis technique is high and reusability is also low.
• Structuring requirements include DFDs (Data Flow Diagram), Structured English, ER
(Entity Relationship) diagram, CFD (Control Flow Diagram), Data Dictionary,
Decision table/tree, State transition diagram.
• This technique is old and is not preferred usually.
11b.1 Describe constructors and its types with example?
Answer:
Constructors
• Constructor initializes an object when it is created.
• Constructor has the same name as its class.
• Constructor is syntactically similar to a method.
• Constructors have no explicit return type.
• Constructors are used to give initial values to the instance variables or to perform any
other start-up procedures.
• All classes have constructors, whether programmer define one or not.
• Java automatically provides a default constructor that initializes all member variables
to default values.
• Once programmer defines own constructor, the system defined default constructor is
no longer used.
Syntax:
class ClassName
{
ClassName()
{
// Initialization Statements;
}
}
Two types of constructors:
• No argument Constructors (Also called as Default Constructor)
• Parameterized Constructors
No Argument Constructors - User Defined Default Constructor
• No argument constructors do not accept any parameters.
• Constructor which is defined in the class by the programmer is known as user-
defined default constructor.
• These constructors the instance variables of a method will be initialized with
fixed values for all objects.
Example
class MyClass
{
int num;
MyClass()
{
num = 100;
}
}
public class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}}
Output:
100 100
Parameterized Constructors
• Constructor that accepts one or more parameters.
• Parameters are added in the same way as added to a method
• Declare them inside the parentheses after the constructor's name.
Example
class MyClass
{
int x;
MyClass(int i)
{
x = i;
}
}
public class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(20);
System.out.println(t1.x + " " + t2.x);
}
}
Output:
10 20
11b.2 Explain no argument and parameterized constructor with example?
Answer:
Constructor initializes an object when it is created. Constructor has the same name as
its class. All classes have constructors, whether programmer define one or not.
Two types of constructors:
• No argument Constructors (Also called as Default Constructor)
• Parameterized Constructors
No Argument Constructors - User Defined Default Constructor
• No argument constructors do not accept any parameters.
• Constructor which is defined in the class by the programmer is known as user-
defined default constructor.
• These constructors the instance variables of a method will be initialized with
fixed values for all objects.
Example
class MyClass
{
int num;
MyClass()
{
num = 100;
}
}
public class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}}
Output:
100 100
Parameterized Constructors
• Constructor that accepts one or more parameters.
• Parameters are added in the same way as added to a method
• Declare them inside the parentheses after the constructor's name.
Example
class MyClass
{
int x;
MyClass(int i)
{
x = i;
}
}
public class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(20);
System.out.println(t1.x + " " + t2.x);
}
}
Output:
10 20

11.b.3 Explain constructor overloading with example?


Answer:
Constructor Overloading
• Like methods, a constructor can also be overloaded.
• Overloaded constructors are differentiated based on their type of parameters or
number of parameters.
• Constructor overloading is not much different than method overloading.
• In case of method overloading program have multiple methods with same name and
different signature.
• Whereas in Constructor overloading program have multiple constructor with same
name and different signature.
• Only difference is that constructor have No return type.
Constructor overloading Example:
class Cricketer
{
String name;
String team;
int age;
Cricketer() // Default constructor
{
name = "";
team = "";
age = 0;
}
//Constructor overloaded
Cricketer(String name, String team, int age)
{
this.name = name;
this.team = team;
this.age = age;
}
// Constructor object as Parameter
Cricketer(Cricketer ckt)
{
this.name = ckt.name;
this.team = ckt.team;
this.age = ckt.age;
}
// Overriding the toString() method
public String toString()
{
return "This is " + name + " of " + team;
}
}
public class ConstructorOverloadingDemo
{
public static void main(String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("Sachin", "India", 32);
Cricketer c3 = new Cricketer(c2);
System.out.println(c2);
// compiler writes here c2.toString()
System.out.println(c3);
// compiler writes here c3.toString()
c1.name = "Virat";
c1.team = "India";
c1.age = 32;
System.out.println(c1);
// compiler writes here c1.toString()
}
}
Output:
This is Sachin of India
This is Sachin of India
This is Virat of India

11b.4 What is class and explain declaration of class?


Answer:
Class
• Classes are basic concepts of Object-Oriented Programming.
• A class is a blueprint or a template from which individual objects are created.
• A class is a collection of data members (Fields) and member functions (Methods).
• A class is a group of objects which have common properties.
• It is a logical entity (A class is a logical grouping of data and functions).
• When a class is defined, no memory is allocated.
Example of Classes:

Syntax of Class:
Access modifier class ClassName
{
fields;
methods;
constructors;
}
Declaring class in Java.
Every class in Java can be composed of the following elements:
• fields
• methods
• constructors
Class declarations can include
• Modifiers such as public, private.
• The class name, with the initial letter capitalized by convention.
• The class body, surrounded by braces, {}.

This is a class declaration. The class body (the area between the braces) contains all the code
that provides for the life cycle of the objects created from the class.

Constructors for initializing new objects, declarations for the fields that provide the
state of the class and its objects, and methods to implement the behavior of the class and its
objects.

Example code to declare a class:

11b.5 What is object and explain creation of object?


Answer:
Objects
• Objects are basic concepts of Object-Oriented Programming which revolve around the
real-life entities.
• Objects are real-world entity such as book, cat, house, pencil, person, etc. Any things
we see, that could be differentiated from another is called object.
• Objects should have a well-defined boundary.
• An object is an instance of a class.
• Every object has its own set of properties, which defines the state of the object and its
own behavior.
• State: It is represented by attributes of an object. It also reflects the properties of an
object.
• Behavior: It is represented by methods of an object. It also reflects the response of an
object with other objects.
• Identity: It gives a unique name to an object and enables one object to interact with
other objects.

Train
Properties Behavior
− Train No. − reserveticket()
− Train Name − cancelticket()
− No. of seat − checkavailability()

Creating Object
• When an object is instantiated / created memory is allocated.
• A software object maintains its state in variables and implements its behaviour with
methods.
• Objects are the building blocks of Object Oriented Programming
Using new keyword
The new keyword is used to create objects.
Syntax:
ClassName objectName = new ClassName();
Example:
Employee empOne = new Employee(“Vijayakumar S”);
Object Creation has three parts
1. Declaration: Variable declarations that associate a variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which
initialize the new object.

12a.1 Explain access modifier?


Answer:
Access Specifier
• Java provides four Access Modifiers to set access levels
• Access Modifier set access levels for classes, variables, methods and constructors.
The four access levels are
• default
• private
• public
• protected
default: The access level of a default modifier is only within the package. It from cannot be
accessed outside the package. No modifiers are needed.
Example:
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
Example:
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}

public class Simple


{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
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.
Example:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello

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.
Example:
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output: Hello
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
12a.2 Explain default and private access specifier with example?
Answer:
Access Specifier
• Java provides four Access Modifiers to set access levels
• Access Modifier set access levels for classes, variables, methods and constructors.
The four access levels are
• default
• private
• public
• protected
default: The access level of a default modifier is only within the package. It from
cannot be accessed outside the package. No modifiers are needed.
Example:
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.

private : The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Example:
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}

public class Simple


{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is a compile-time error.

12a.3 Explain public and protected access specifier with example?


Answer:
Access Specifier
• Java provides four Access Modifiers to set access levels
• Access Modifier set access levels for classes, variables, methods and constructors.
The four access levels are
• default
• private
• public
• protected
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.
Example:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello

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.
Example:
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output: Hello
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
12a.4 Explain non access modifier?
Java provides a number of non-access modifiers to achieve many other functionalities.
1. static
The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The static
keyword belongs to the class than an instance of the class.
To access static methods there is no need to instantiate the class. Static
methods can be accessed using just the class name.
Syntax
static data_type var_name = var_value;
2. final
The final keyword in java is used to restrict the user. The java final keyword
can be used in many contexts. Final can be: variable, method and class.
The final keyword indicates that the specific class cannot be extended or a method
cannot be overridden.
Syntax
final data_type VAR_NAME= var_value;
Use uppercase to declare final variables in Java.
3. abstract
The abstract keyword is used to achieve abstraction in Java. It is a non-access
modifier which is used to create abstract class and method. The role of an abstract
class is to contain abstract methods.
Syntax
abstract class class-name
{
//body of class
}
4. Synchronized
Java programming language provides a very handy way of creating
threads and synchronizing their task by using synchronized blocks to keep shared
resources.
Syntax
public synchronized void showDetails()
{
.......
}
5. transient
Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.
Syntax
public transient int limit = 55; // will not persist
public int b; // will persist
6. Volatile
Volatile keyword is used to modify the value of a variable (either
primitive type or objects) by different threads. It is also used to make classes thread
safe.
Syntax
volatile data_type variable_name;
7. native
The native keyword is applied to a method to indicate that the method is
implemented in native code using JNI (Java Native Interface). Native is a modifier
applicable only for methods and cannot apply it anywhere else. The methods which
are implemented in C, C++ are called as native methods or foreign methods.
Syntax
[ public | protected | private] native [return_type] method ();
A method marked as native cannot have a body and should end with a semicolon.

12a.5 Explain static and final keyword with example?


Answer:
Java provides a number of non-access modifiers to achieve many other functionalities.
• static
• final
• abstract
• synchronized
• native
• transient
• volatile

1. static
The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static keyword
belongs to the class than an instance of the class.
To access static methods there is no need to instantiate the class. Static methods can
be accessed using just the class name.

Syntax
static data_type var_name = var_value;
Example:
// static variable
class static_gfg {
static String s = “RMK";
}
class GFG {
public static void main(String[] args)
{
// No object required
System.out.println(
static_gfg.s);
}
}
OUTPUT: RMK
In this above code sample, we have declared the String as static, part of
the static_gfg class. Generally, to access the string, we first need to create the object
of the static_gfg class, but as we have declared it as static, we do not need to create an
object of static_gfg class to access the string. We can
use className.variableName for accessing it.

2. final
• The final keyword in java is used to restrict the user. The java final keyword
can be used in many contexts. Final can be: variable, method and class.
• The final keyword indicates that the specific class cannot be extended or a
method cannot be overridden.

Syntax
final data_type VAR_NAME= var_value;
Final Variables Example:

public class Test


{
final int value = 10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue()
{
value = 12; // will give an error
}
}
12b.2 Explain abstract, synchronized and transient keyword with example?
Answer:
abstract
• The abstract keyword is used to achieve abstraction in Java. It is a non-access
modifier which is used to create abstract class and method. The role of an abstract
class is to contain abstract methods.
• A class cannot be both abstract and final (since a final class cannot be extended). If
a class contains abstract methods, then the class should be declared abstract.
Otherwise, a compile error will be thrown.
Syntax
abstract class class-name
{
//body of class
}
Example:
public abstract class SuperClass
{
abstract void m(); // abstract method
}
class SubClass extends SuperClass
{
// implements the abstract method
void m()
{
.........
}
}
synchronized
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks to keep shared resources.
Syntax
public synchronized void showDetails()
{
.......
}
transient
Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
Syntax
public transient int limit = 55; // will not persist
public int b; // will persist
12b.2 Explain volatile and native keyword with example?
Answer:
Volatile
Volatile keyword is used to modify the value of a variable (either primitive type
or objects) by different threads. It is also used to make classes thread safe.
Syntax
volatile data_type variable_name;
Example:
public class MyRunnable implements Runnable
{
private volatile boolean active;
public void run()
{
active = true;
while (active)
{
// line 1
// some code here
}
}
public void stop() {
active = false;
// line 2
}
}
Usually, run () is called in one thread (the one you start using the Runnable), and
stop () is called from another thread. If in line 1, the cached value of active is used, the loop
may not stop when you set active to false in line 2. That's when you want to use volatile.
native
The native keyword is applied to a method to indicate that the method is
implemented in native code using JNI (Java Native Interface). Native is a modifier
applicable only for methods and cannot apply it anywhere else. The methods which are
implemented in C, C++ are called as native methods or foreign methods.
Syntax
[ public | protected | private] native [return_type] method ();
A method marked as native cannot have a body and should end with a semicolon.
Example:

Class GFG

// native method

public native void printMethod ();

static

// The name of DLL file

System.loadLibrary ("LibraryName");

public static void main (String[] args)

GFG obj = new GFG ();

obj.printMethod ();

}
12b.3 Explain comment statements?
Answer:
• Comments are the statements that are not executed by the compiler and interpreter.
• Comments can be used to provide information or explanation about the variable,
method, class or any statement.
• Comments can also be used to hide program code.
Types of Comments
There are three types of comments in Java.
• Single Line Comment
• Multi Line Comment
• Documentation Comment
Single Line Comment
The single line comment is used to comment only one line.
Syntax:
//This is single line comment
Example:
public class CommentsDemo {
public static void main(String[] args) {
int i = 10; // Here, i is a variable
System.out.println(i);
}
}
Output:
10

Multi Line Comment


The multi line comment is used to comment multiple lines of code.
Syntax:
/*
This
is
multi line
comment
*/
Example:
public class CommentsDemo {
public static void main(String[] args) {
/*
Let's declare and print variable in java.
*/
int i = 10;
System.out.println(i);
}
}
Output:
10

Java Documentation Comment


The documentation comment is used to create documentation API. To create
documentation API, javadoc tool need to be used.
Syntax:
/**
This
is
documentation
comment
*/
Example
/**
The Calculator class provides methods to get addition and subtraction of given 2 numbers.
*/
public class Calculator {
/** The add() method returns addition of given numbers. */
public static int add(int a, int b) {
return a + b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b) {
return a - b;
}
}
Compile it by javac tool:
javac Calculator.java
Create Documentation API by javadoc tool:
javadoc Calculator.java
• Now, there will be HTML files created for Calculator class in the current directory.
• Open the HTML files and see the explanation of Calculator class provided through
documentation comment.

12b.4 Describe types of comment statement with example?


Answer:
• Comments are the statements that are not executed by the compiler and interpreter.
• Comments can be used to provide information or explanation about the variable,
method, class or any statement.
• Comments can also be used to hide program code.
Types of Comments
There are three types of comments in Java.
• Single Line Comment
• Multi Line Comment
• Documentation Comment
Single Line Comment
The single line comment is used to comment only one line.
Syntax:
//This is single line comment
Example:
public class CommentsDemo {
public static void main(String[] args) {
int i = 10; // Here, i is a variable
System.out.println(i);
}
}
Output:
10

Multi Line Comment


The multi line comment is used to comment multiple lines of code.
Syntax:
/*
This
is
multi line
comment
*/
Example:
public class CommentsDemo {
public static void main(String[] args) {
/*
Let's declare and print variable in java.
*/
int i = 10;
System.out.println(i);
}
}
Output:
10

Java Documentation Comment


The documentation comment is used to create documentation API. To create
documentation API, javadoc tool need to be used.
Syntax:
/**
This
is
documentation
comment
*/
Example
/**
The Calculator class provides methods to get addition and subtraction of given 2 numbers.
*/
public class Calculator {
/** The add() method returns addition of given numbers. */
public static int add(int a, int b) {
return a + b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b) {
return a - b;
}
}
Compile it by javac tool:
javac Calculator.java
Create Documentation API by javadoc tool:
javadoc Calculator.java
• Now, there will be HTML files created for Calculator class in the current directory.
• Open the HTML files and see the explanation of Calculator class provided through
documentation comment.

12b.5 Write the difference between object-oriented analysis process and structure-
oriented analysis process?
Answer:

Object-oriented analysis
• It is concerned with modeling the application domain.
• The main focus in on data structure and real-world objects that are important.
• It uses Incremental or Iterative methodology to refine and extend our design.
• It is suitable for large projects with changing user requirements.
• Risk while using this analysis technique is low and reusability is also high.
• Requirement engineering includes Use case model (find Use cases, Flow of events,
Activity Diagram), the Object model (find Classes and class relations, Object
interaction, Object to ER mapping), Statechart Diagram, and deployment diagram.
• This technique is new and is mostly preferred.

Structured Analysis
• The main focus is on process and procedures of system.
• It uses System Development Life Cycle (SDLC) methodology for different purposes
like planning, analyzing, designing, implementing, and supporting an information
system.
• It is suitable for well-defined projects with stable user requirements. Risk while using
this analysis technique is high and reusability is also low.
• Structuring requirements include DFDs (Data Flow Diagram), Structured English, ER
(Entity Relationship) diagram, CFD (Control Flow Diagram), Data Dictionary,
Decision table/tree, State transition diagram.
• This technique is old and is not preferred usually.

13a.1 Describe features of java programming?


Answer:

Object Oriented
In java, everything is an object which has some data and behaviour. Java can be
easily extended as it is based on Object Model. Following are some basic concept of OOP’s.
i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation

Simple
• Java is easy to learn and its syntax is quite simple, and easy to understand. The
confusing and ambiguous concepts of C++ are either left out in Java
• Eg : Pointers and Operator Overloading are not there in java but were an important
part of C++.

Secure
• When it comes to security, Java is always the first choice.
• With java secure features it enable us to develop virus free system.
• Java program always runs in Java runtime environment with almost null interaction
with system OS, hence it is more secure.

Platform Independent
• Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines.
• Java is guaranteed to be write-once, run-anywhere language.
• On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.

Robust
• Robustness is the capacity of a computer system to handle the errors during execution
and manage the incorrect input of data.
Java is robust because it utilizes strong memory management.
Portable
• Java Byte code can be carried to any platform. No implementation dependent features.
• Everything related to storage is predefined, example: size of primitive data types.
Architectural Neutral
• Compiler generates bytecodes, which have nothing to do with a particular computer
architecture,
• Hence a Java program is easy to intrepret on any machine.
Dynamic
• Java is a dynamic language.
• It supports the dynamic loading of classes.
• It means classes are loaded on demand.
• It also supports functions from its native languages, i.e., C and C++.
Java Interpreter
• Java is a platform-independent programming language. It means that we can run Java
on the platforms that have a Java interpreter.
• It is the reason that makes the Java platform-independent.
• The Java interpreter converts the Java bytecode (.class file) into the code understand
by the operating system.

High Performance
• Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.
• It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.
Multi-threaded
• A thread is like a separate program, executing concurrently.
• We can write Java programs that deal with many tasks at once by defining multiple
threads.
• The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area.
• Threads are important for multi-media, Web applications, etc.
Distributed
• Java is also a distributed language. Programs can be designed to run on computer
networks.
• Java has a special class library for communicating using TCP/IP protocols.
• Creating network connections is very much easy in Java as compared to C/C++.
13a.2 Explain the structure of java programming?
Answer:

Documentation Section
It is used to improve the readability of the program. It consists of comments in Java which
include basic information such as the method’s usage or functionality to make it easier for the
programmer to understand it while reviewing or debugging the code. A Java comment is not
necessarily limited to a confined space, it can appear anywhere in the code. The compiler
ignores these comments during the time of execution and is solely meant for improving the
readability of the Java program.
There are three types of comments that Java supports
• Single line Comment - Single line comments can be written using
// Single line Comment
• Multi-line Comment - Block comments are used to provide descriptions of files,
methods, data structures and algorithms. Block comments may be used at the
beginning of each file and before each method
/*
Here is a block comment
*/
• Documentation Comment: The JDK javadoc tool uses doc comments when
preparing automatically generated documentation.
/**
documentation comments
*/
Package Statement
Java that allows you to declare your classes in a collection called package. There can
be only one package statement in a Java program and it has to be at the beginning of the code
before any class or interface declaration. This statement is optional, for example, take a look
at the statement below.
package student;
Import Statement
Many predefined classes are stored in packages in Java, an import statement is used to
refer to the classes stored in other packages. An import statement is always written after the
package statement but it has to be before any class declaration. We can import a specific class
or classes in an import statement.
import java.util.Date; // Imports the Date class from util package
import java.sql.*; // Imports all the classes from sql package
Interface Section
This section is used to specify an interface in Java. It is an optional section which is
mainly used to implement multiple inheritance in Java. An interface is a lot similar to a class
in Java but it contains only constants and method declarations.
Class Definition
A Java program may contain several class definitions, classes are an essential part of
any Java program. It defines the information about the user-defined classes in a program. A
class is a collection of variables and methods that operate on the fields. Every program in
Java will have at least one class with the main method.
Main Method Class
The main method is from where the execution actually starts and follows the order specified
for the following statements. Structure of main method class
public class Example{
//main method declaration
public static void main(String args[])
System.out.println ("hello world");
}
}
public class Example: This creates a class called Example. You should make sure that the
class name starts with a capital letter, and the public word means it is accessible from any
other classes.
Braces: The curly brackets are used to group all the commands together. To make sure that
the commands belong to a class or a method.
public static void main: When the main method is declared public, it means that it can be
used outside of this class as well. The word static means that we want to access a method
without making its objects. As we call the main method without creating any objects. The
word void indicates that it does not return any value. The main is declared as void because it
does not return any value. Main is the method, which is an essential part of any Java program.
String[] args: It is an array where each element is a string, which is named as args. If you
run the Java code through a console, you can pass the input parameter. The main() takes it as
an input.
System.out.println(); : The statement is used to print the output on the screen where the
system is a predefined class, out is an object of the PrintWriter class. The method println
prints the text on the screen with a new line. All Java statements end with a semicolon.
Example Structure of Java Source File
/* A first program in Java */
public class Welcome
{
public static void main( String args[])
{
System.out.println( "Welcome to Java!" );
// Prints Welcome to Java!
}
}
Output:
Welcome to java!
Execution of Java Program
Java program can be executed using the following means
1. In command prompt
2. IDE
3. Online compilers
13a.3 Describe java environment/java architecture?
Answer:
Java programs can typically be developed in five stages:
• Edit
• Compile
• Loading
• Verify
• Execute

1. Edit : Use an editor to type the source code (Welcome.java)


2. Compile: javac, the Java compiler is used to translate the source code to machine
independent, bytecode. Bytecodes are called .class file
3. Loading: Class loader loads the bytecodes from .class and other libraries file into
main memory.
4. Verify: Verifier make sure, whether the bytecodes are valid and do not violate
security restrictions
5. Execute: Java Virtual Machine (JVM) uses a combination of interpretation and just-
in-time compilation to translate bytecodes into machine language. Applications are
run on user's machine, i.e. executed by interpreter with java command (java
Welcome).
13a.4 Describe datatypes in java and its types?
Answer:
• Data types specify the different sizes and values that can be stored in the variable.
• Java is a statically-typed programming language. It means, all variables must be
declared before its use. That is why we need to declare variable's type and name.

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.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
There are 8 types of primitive data types:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7
decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal


digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values

Boolean Data Type


• The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.
• The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Boolean one = false
Byte Data Type
• The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.
• The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.
Example:
byte a = 10, byte b = -20
Short Data Type
• The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.
• The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
short s = 10000, short r = -5000
Int Data Type
• The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
• The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
int a = 100000, int b = -200000
Long Data Type
• The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when
you need a range of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L
Float Data Type
• The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited.
• It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers.
• The float data type should never be used for precise values, such as currency. Its
default value is 0.0F.
Example:
float f1 = 234.5f
Double Data Type
• The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited.
• The double data type is generally used for decimal values just like float.
• The double data type also should never be used for precise values, such as currency.
Its default value is 0.0d.
Example:
double d1 = 12.3
Char Data Type
• The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
• The char data type is used to store characters.
Example:
char letterA = 'A'
Non-Primitive Data types
• Non-primitive types are created by the programmer and is not defined by Java
(except for String).
• Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.

13a.5 Describe core java and explain the difference between the core java and advanced
java?
Answer:
Both Core Java and Advance Java are parts of Java programming, but for
understanding the entire Java better, we need to differentiate between both. So, below we
have described some differences between both core java and advance Java:

Core Java Advance Java

Core Java covers the basic concepts of the Advance Java covers the advanced topics
Java programming language. and concepts of the Java programming language.

Core Java is used for developing Advance Java is used for developing
computing or desktop applications. enterprise applications.

It is the first step, to begin with, Java. It is the next step after completing the Core
Java.

Core Java is based on single-tier Advance Java is based on two-tier


architecture. architecture.

It comes under Java SE. It comes under Java EE or J2EE.

It covers core topics such as OOPs, It covers advanced topics such as JDBC,
inheritance, exception handling, etc. servlets, JSP, web services etc.
13b.1 Explain autoboxing with example?
Answer:
The automatic conversion that the Java compiler makes between the primitive types
and their corresponding object wrapper classes.

Autoboxing
• Automatic conversion of primitive types to the object of their corresponding wrapper
classes is known as autoboxing.
• For example, converting int to Integer class. The Java compiler applies autoboxing
when a primitive value is:
• Passed as a parameter to a method that expects an object of the corresponding
wrapper class.
• Assigned to a variable of the corresponding wrapper class.
Example
// Java program to demonstrate Autoboxing
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));
}
}
13b.2 Explain unboxing with example?
Answer:
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. The Java compiler applies to unbox when an
object of a wrapper class is:
• Passed as a parameter to a method that expects a value of the corresponding
primitive type.
• Assigned to a variable of the corresponding primitive type.

Example
// 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);
}
}
13b.3 Explain widening and narrow conversion with example?
Answer:
• Type promotion automatically promotes the lower range value to higher range value.
• Java automatically promotes each byte, short, or char operand to int when evaluating
an expression.
• If one operand is long, float or double the whole expression is promoted to long,
float, or double respectively.

Automatic Type Convertion


// Java Program to Illustrate Automatic Type Conversion
// Main class
class GFG
{
// Main driver method
public static void main(String[] args)
{
int i = 100;
// Automatic type conversion
// Integer to long type
long l = i;
// Automatic type conversion
// long to float type
float f = l;
// Print and display commands
System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
}
Output
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit Conversion

• If we want to assign a value of a larger data type to a smaller data type we perform
explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot be
done.
Example
// Java program to Illustrate Explicit Type Conversion
// Main class
public class GFG
{
// Main driver method
public static void main(String[] args)
{
// Double datatype
double d = 100.04;
// Explicit type casting by forcefully getting
// data from long datatype to integer type
long l = (long)d;
// Explicit type casting
int i = (int)l;
// Print statements
System.out.println("Double value " + d);
// While printing we will see that
// fractional part lost
System.out.println("Long value " + l);
// While printing we will see that
// fractional part lost
System.out.println("Int value " + i);
}
}
Output
Double value 100.04
Long value 100
Int value 100
13b.4 Explain datatype promotion and automatic type conversion with example?
Answer:
Data Type Promotion
• Type promotion automatically promotes the lower range value to higher range value.
• Java automatically promotes each byte, short, or char operand to int when evaluating
an expression.
• If one operand is long, float or double the whole expression is promoted to long,
float, or double respectively.
Automatic Type Conversion
// Java Program to Illustrate Automatic Type Conversion
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
int i = 100;
// Automatic type conversion
// Integer to long type
long l = i;
// Automatic type conversion
// long to float type
float f = l;
// Print and display commands
System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
}
Output
Int value 100
Long value 100
Float value 100.0

13b.5 Explain explicit conversion and type promotion in expression with example?
Answer:
Narrowing or Explicit Conversion
• If we want to assign a value of a larger data type to a smaller data type we perform
explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot be
done.
Example
// Java program to Illustrate Explicit Type Conversion
// Main class
public class GFG
{
// Main driver method
public static void main(String[] args)
{
// Double datatype
double d = 100.04;
// Explicit type casting by forcefully getting
// data from long datatype to integer type
long l = (long)d;
// Explicit type casting
int i = (int)l;
// Print statements
System.out.println("Double value " + d);
// While printing we will see that
// fractional part lost
System.out.println("Long value " + l);
// While printing we will see that
// fractional part lost
System.out.println("Int value " + i);
}
}
Output
Double value 100.04
Long value 100
Int value 100
Type Promotion in Expression
While evaluating expressions, the intermediate value may exceed the range of operands and
hence the expression value will be promoted. Some conditions for type promotion are:
1. Java automatically promotes each byte, short, or char operand to int when evaluating
an expression.
2. If one operand is long, float or double the whole expression is promoted to long, float,
or double respectively.
Example
// Java program to Illustrate Type promotion in Expressions
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Declaring and initializing primitive types
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
// The Expression
double result = (f * b) + (i / c) - (d * s);
// Printing the result obtained after
// all the promotions are done
System.out.println("result = " + result);
}
}
Output
result = 626.7784146484375
14a.1 Explain nested class and its types?
Answer:
Inner class:
Java inner class or nested class is a class that is declared inside the class or interface.
• 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.
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Types of Nested classes

There are two types of nested classes non-static and static nested classes. The non-
static nested classes are also known as inner classes.
• Non-static nested class (inner class)
• Member inner class
• Anonymous inner class
• Local inner class
• Static nested class
14a.2 Explain inner class and describe advantages of inner class?
Answer:
Java inner class or nested class is a class that is declared inside the class or interface.
• 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.
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Advantage of Java inner class
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Example:
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
System.out.println(“Data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output
Data is 30
14a.3 Explain non-static class with example?
Answer:
Types of Nested classes
There are two types of nested classes
• non-static and
• static nested classes.
The non-static nested classes are also known as inner classes.
Non-static nested class (inner class)
• Member inner class
• Anonymous inner class
• Local inner class

Member Inner Class


A non-static class that is created inside a class but outside a method is called member inner
class. It is also known as a regular inner class. It can be declared with access modifiers like
public, default, private, and protected.
Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
Example
In this example, we are creating a msg() method in the member inner class that is
accessing the private data member of the outer class.
TestMemberOuter1.java
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println(“Data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output
Data is 30
Java Anonymous Class
• In Java, a class can contain another class known as nested class. It's possible to create
a nested class without giving any name.
• A nested class that doesn't have any name is known as an anonymous class.
• An anonymous class must be defined inside another class. Hence, it is also known as
an anonymous inner class.
Syntax
class outerClass
{
// defining anonymous class
object1 = new Type(parameterList) {
// body of the anonymous class
};
}
Anonymous classes are defined inside an expression. So, the semicolon is used at the
end of anonymous classes to indicate the end of the expression.
Example

Method Local Inner Classes


Inner class can be declared within a method of an outer class which we will be illustrating in
the below example where Inner is an inner class in outerMethod().
Example
// Java Program to Illustrate Inner class can be
// declared within a method of outer class
// Class 1
// Outer class
class Outer
{
// Method inside outer class
void outerMethod()
{
// Print statement
System.out.println("inside outerMethod");
// Class 2
// Inner class
// It is local to outerMethod()
class Inner {
// Method defined inside inner class
void innerMethod()
{
// Print statement whenever inner class is
// called
System.out.println("inside innerMethod");
}
}
// Creating object of inner class
Inner y = new Inner ();
// Calling over method defined inside it
y.innerMethod();
}
}
// Class 3
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of outer class inside main()
// method
Outer x = new Outer();
// Calling over the same method
// as we did for inner class above
x.outerMethod();
}
}

Output
inside outerMethod
inside innerMethod
14a.5 Explain nested interface with example?
Answer:
An interface, i.e., declared within another interface or class, is known as a nested
interface. The nested interfaces are used to group related interfaces so that they can be easy to
maintain. The nested interface must be referred to by the outer interface or class. It can't be
accessed directly.
Points to remember for nested interfaces
• The nested interface must be public if it is declared inside the interface, but it can
have any access modifier if declared within the class.
• Nested interfaces are declared static
Syntax of nested interface which is declared within the interface
interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}
Example of nested interface which is declared within the interface
TestNestedInterface1.java
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();
//upcasting here
message.msg();
}
}
Output
Hello nested interface
As you can see in the above example, we are accessing the Message interface by its
outer interface Showable because it cannot be accessed directly. It is just like the almirah
inside the room; we cannot access the almirah directly because we must enter the room first.
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates a public and static interface as displayed below:
public static interface Showable$Message
{
public abstract void msg();
}
14b.1 Explain java member inner class with example?
Answer:
A non-static class that is created inside a class but outside a method is called member
inner class. It is also known as a regular inner class. It can be declared with access modifiers
like public, default, private, and protected.
Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
Example
In this example, we are creating a msg () method in the member inner class that is
accessing the private data member of the outer class.
TestMemberOuter1.java
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
System.out.println(“Data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output
Data is 30

14b.2 Explain java anonymous inner class with example?


Answer:

14b.3 Explain method local inner class with example?


Answer:
Inner class can be declared within a method of an outer class, which we will be illustrating in
the below example where Inner is an inner class in outerMethod().
Example
// Java Program to Illustrate Inner class can be
// declared within a method of outer class
// Class 1
// Outer class
class Outer
{
// Method inside outer class
void outerMethod()
{
// Print statement
System.out.println("inside outerMethod");
// Class 2
// Inner class
// It is local to outerMethod()
class Inner
{
// Method defined inside inner class
void innerMethod()
{
// Print statement whenever inner class is
// called
System.out.println("inside innerMethod");
}
}
// Creating object of inner class
Inner y = new Inner();
// Calling over method defined inside it
y.innerMethod();
}
}
// Class 3
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of outer class inside main()
// method
Outer x = new Outer();
// Calling over the same method
// as we did for inner class above
x.outerMethod();
}
}
Output
inside outerMethod
inside innerMethod

14b.4 Define non-primitive data types and explain the difference between the primitive
and non-primitive datatypes in java?
Answer:
The main difference between primitive and non-primitive data types are:
Primitive data types:
• The primitive data types include boolean, char, byte, short, int, long, float and
double.
• Primitive types are predefined (already defined) in Java.
• Primitive types cannot be used to call methods to perform certain operations.
• A primitive type has always a value.
• A primitive type starts with a lowercase letter.
• The size of a primitive type depends on the data type.
Non-primitive data types:
• The non-primitive data types include Classes, Interfaces, and Arrays.
• Non-primitive types are created by the programmer and is not defined by Java (except
for String).
• Non-primitive types can be used to call methods to perform certain operations.
• Non-primitive types can be null.
• Non-primitive types start with an uppercase letter.
• Non-primitive types have all the same size.

14b.5 Describe primitive datatypes?


Answer:
• Data types specify the different sizes and values that can be stored in the variable.
• Java is a statically-typed programming language. It means, all variables must be
declared before its use. That is why we need to declare variable's type and name.

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.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
There are 8 types of primitive data types:
Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7


decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal


digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values

Boolean Data Type


• The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.
• The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Boolean one = false
Byte Data Type
• The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.
• The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.
Example:
byte a = 10, byte b = -20
Short Data Type
• The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.
• The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
short s = 10000, short r = -5000
Int Data Type
• The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
• The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
int a = 100000, int b = -200000
Long Data Type
• The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when
you need a range of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L
Float Data Type
• The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited.
• It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers.
• The float data type should never be used for precise values, such as currency. Its
default value is 0.0F.
Example:
float f1 = 234.5f
Double Data Type
• The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited.
• The double data type is generally used for decimal values just like float.
• The double data type also should never be used for precise values, such as currency.
Its default value is 0.0d.
Example:
double d1 = 12.3
Char Data Type
• The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
• The char data type is used to store characters.
Example:
char letterA = 'A'
15a.1 Describe quality software characteristics?
Answer:
Quality Software Characteristics
• Functionality
• Reliability
• Usability
• Efficiency
• Maintainability
• Portability

1. Functionality

Suitability = To provide an adequate set of functions for specified tasks and user
objectives.
Accuracy = To provide the right or agreed-upon results or effects.
Interoperability = To interact with one or more specified systems.
Security = To prevent unintended access and resist deliberate attacks intended to gain
unauthorized access to confidential information.
2. Reliability

Maturity = To avoid failure as a result of faults in the software.


Fault Tolerance = To maintain a specified level of performance in case of software faults.
Recoverability = To reestablish its level of performance and recover the data directly
affected in the case of a failure.
3. Usability

Understandability = To enable the user to understand whether the software is suitable.


Learnability = To enable the user to learn its applications.
Operability = To enable the user to operate and control it.

4. Efficiency

Time Behavior = To provide appropriate response and processing times.


Resource Utilization = To use appropriate resources in an appropriate time when the
software performs its function under stated condition.
5. Maintainability

Testability = To enable modified software to be validated.


Stability = To minimize unexpected effects from modifications of the software.
Changeability = To enable a specified modification to be implemented.
Analyzability = To be diagnosed for deficiencies or causes of failures in the software.

6. Portability

Adaptability = To be modified for different specified environments without applying


actions.
Installability = To be installed in a specified environment.
Replaceability = To be used in place of other specified software in the environment of
that software.
15a.2 Describe association and its types?
Answer:
• An association is a “using” relationship between two or more objects in which
the objects have their own lifetime and there is no owner.
• Association manages one-to-one, one-to-many, and many-to-many relationships.
• The multiplicity between objects is defined by the Association.
• It shows how objects communicate with each other and how they use the
functionality and services provided by that communicated object.
• A person can have only one passport. It defines the one-to-one
• The Association between a College and Student, a College can have many
students. It defines the one-to-many
• A single student can associate with multiple teachers, and multiple students can
also be associated with a single teacher. Both are created or deleted
independently, so it defines the many-to-many

Types of Association

1) IS-A Association
The IS-A Association is also referred to as Inheritance.

Example:

2) HAS-A Association
The HAS-A Association is further classified into two parts, i.e., Aggregation
and Composition.
Aggregation
In aggregation, the child is not dependent on its parent i.e., standalone.
Example:

Composition
• In composition, the child is dependent on its parent.
• An aggregation is a special form of association, and composition is the
special form of aggregation.
Example:

15a.3 Explain inheritance and its types?


Answer:
Inheritance
Inheritance is the mechanism by which one object is allowed to derive the properties
(fields and methods) of another. Inheritance in OOP = When a class derives from another
class.

Syntax
class derived-class extends base-class
{
//methods and fields
}
• The class features are inherited is known as super class (or a base class or a parent
class). The class that inherits the other class is known as sub class (or a derived class,
extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
• The child class will inherit all the public and protected properties and methods from
the parent class. In addition, it can have its own properties and methods.
• Inheritance supports reusability,
• i.e. When we want to add new features to an existing entity, we can derive our new
entity from the existing using inheritance. This enables reusing the fields and methods
of the existing class.
An inherited class is defined by using the extends keyword.
Types of Inheritance:

1. Single Inheritance:

In single inheritance, subclasses inherit the features of one superclass. In the


image below, class A serves as a base class for the derived class B.
Example:
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one {


public void print_for() { System.out.println("for"); }
}
// Driver class
public class Main {
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
}
}
Output
Geek
for

2. Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as
well as the derived class also act as the base class to other class.

Example:
Class A serves as a base class for the derived class B, which in turn
serves as a base class for the derived class C.
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one {


public void print_for() { System.out.println("for"); }
}

class three extends two {


public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main {
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
}
}

Output
Geeks
for

3. Multiple Inheritance

Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class


can have more than one superclass and inherit features from all parent classes. Please note
that Java does not support multiple inheritances with classes. In java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C is derived from
interface A and B.
interface one {
public void print_geek();
}

interface two {
public void print_for();
}

interface three extends one, two {


public void print_geek();
}
class child implements three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}
// Drived class
public class Main {
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
}
}
Output
Geeks
for

4. Hybrid inheritance
In Java, the hybrid inheritance is the composition of two or more types of inheritance.
The main purpose of using hybrid inheritance is to modularize the code into well-defined
classes. It also provides the code reusability.
5. Hierarchical inheritance
When more than one classes inherit a same class then this is called hierarchical
inheritance.

15a.4 Describe IS-A and HAS-A association with example?


Answer:
A relationship in Java means different relations between two or more classes. For
example, if a class Bulb inherits another class Device, then we can say that Bulb is having
is-a relationship with Device, which implies Bulb is a device.

In Java, we have two types of relationship:


1. Is-A relationship: Whenever one class inherits another class, it is called an IS-
A relationship.
2. Has-A relationship: Whenever an instance of one class is used in another class,
it is called HAS-A relationship.
Example
// Java program to demonstrate the
// working of the Is-A relationship
import java.io.*;
// parent class
class Device
{
private String deviceName;
public void setDeviceName(String deviceName)
{
this.deviceName = deviceName;
}
public String getDeviceName()
{
return this.deviceName + " is a Device";
}
}
// child class
class Bulb extends Device {
public static void main(String gg[])
{
// parent class can store the reference
// of instance of child classes
Device device = new Bulb();

// set the device name to bulb


System.out.println("Device name is Bulb");
device.setDeviceName("Bulb");

// print the device name


System.out.println(device.getDeviceName());
}
}

Class Device has a field named as deviceName. Class Bulb extends Device that
means Bulb is a type of Device. Since Device is the parent class which implies that class
Device can store the reference of an instance of class Bulb.
Output
Device name is Bulb
Bulb is a Device
Has-A relationship: Whenever an instance of one class is used in another class, it is called
HAS-A relationship.

Example:
Consider two classes Student and Address. Each student has own address that makes
has-a relationship but address has student not makes any sense. We can understand it more
clearly using Java code.
Class Address{
int street_no;
String city;
String state;
int pin;
Address(int street_no, String city, String state, int pin ){
this.street_no = street_no;
this.city = city;
this.state = state;
this.pin = pin;
}
}

class Student
{
String name;
Address ad;
}
Here in the above code, we can see Student class has-a relationship
with Address class. We have draw an image too to demonstrate relation between these two
classes.
The Student class has an instance variable of type Address. As we have a variable of
type Address in the Student class, it can use Address reference which is ad in this case, to
invoke methods of the Address class.

15a.5 Explain the method statements with syntax and example?

15b.1 Explain control statements in java and its types?


15b.2 Explain decision making statement with example?
15b.3 Explain loop statement with example?
15b.4 Explain jump statement with example?
15b.5 Explain about break, continue and return statement with example?
16a.1 Describe polymorphism and its types?
16a.2 Describe compile time polymorphism with example?
16a.3 Describe run time polymorphism with example?
16a.4 Explain static and dynamic binding with example?
16a.5 Explain early and late binding with example?

16b.1 Explain abstract keyword and its use with example?

16b.2 Explain super keyword and its use with example?


16b.3 Explain final keyword and its use with example?
16b.4 Explain static keyword and its use with example?
16b.5 What are all the operators in java and describe logical operator?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy