Structural Engineering Notes | Syllabus, Reference Books and Important Questions

Telecommunication Engineering Notes

Structural Engineering Notes: Are you planning to study Civil Engineering. Structural Engineering is the most crucial department in Civil Engineering. Acquiring the BTech Geeks notes will help you to score good grades in the exam. The Structural Engineering Notes includes a comprehensive study plan, all-important information and timetable.

Students will get information about the latest Reference Books and Syllabus for Structural Engineering Notes. Students pursuing Structural Engineering can access this article to refer to the best and credible Engineering Notes for their preparation process. Avail subject-wise B.Tech Notes related to Engineering Departments like ECE, CSE, Mech, EEE, Civil, etc. all in one place and plan your preparation according to your requirements.

Structural Engineering Notes act as important study material and improvise better preparation or revision and help students secure good grades. Students can refer to the Structural Engineering Notes as per the latest and updated syllabus from this article keeping in mind every student’s requirements and assessing their preparation efficiency.

Here is a list presenting the primary sources of information included in this article.

Introduction to Structural Engineering

Structural engineering is a specialization within the field of civil engineering that concentrates on the framework of buildings or edifices, and on designing those structures to resist the stresses and pressures of their environment, remain safe, and secure throughout their use. Structural engineering theory is based upon applied experiential knowledge and physical laws of the structural performance of varied materials and geometries. In other words, structural engineers make sure that buildings don’t fall and bridges don’t collapse.

Structural Engineering Notes and Study Material PDF Free Download

In Structural engineering Notes, you will learn the fundamentals of Structural engineering and various aspects of the topic. The students can also learn the theoretical and the application aspects of structural engineering. Studying from these notes helps the student to become active and so the learning process is improved. Candidates can start their preparation with all the tools to help them score better marks in the exam.

The students can refer and use the Structural Engineering Notes pdf and Study Materials as a reference. Students can refer to the following formats for Notes for Structural engineering and increase their efficiency and problem-solving skills to achieve excellent grades in the exams.

Structural Engineering Notes Reference Books

Reference books for Structural engineering Notes are an imperative source of information. It presents information and essential knowledge about the topics. Students should refer to books recommended by subject experts as it will help them to follow the subject accurately. Students will understand the Structural engineering topics if they confer the latest version that includes the updated syllabus. Here is a list of the best-recommended books for Structural engineering Notes Reference Books.

Books Author
Structures Or Why Things Don’t Fall Down J. E. Gordon
Steel Design William T. Segui
Building Construction Illustrated Francis D. K. Ching
Steel Design William T. Segui
PPI Structural Engineering Solved Problems C. Dale Buckner
Structural Steel Design Abi O. Aghayere, Jason Vigil
Simplified Engineering for Architects and Builders James Ambrose, Patrick Tripeny
Seismic Design of Foundations

Concepts and applications

Subhamoy Bhattacharya, Rolando P. Orense and Domenico Lombardi
The Structure – Works of Mahendra Raj Vandini Mehta, Rohit Raj Mehrdiratta, Ariel Huber
Safety-Related Nuclear Structures – Seismic Analysis American Society of Civil Engineers
Concrete Construction Engineering NAWY
Structural Engineering Brightwood Engineering Education
Numerical methods S.S.Sastry
Numerical methods and C Language C.Xavier
Prestressed concrete Krishna Raju

Structural Engineering Syllabus

The best way to commence your preparation for Structural Engineering is to understand the syllabus and the topics of the subject. The curriculum of Structural Engineering provides students a clear idea about what and how to study and analyse the subject.The Structural Engineering syllabus is a reliable course planning tool that plans and organises the subject for a student. The article on Structural Engineering Notes provides a detailed structure along with the latest and updated syllabus, and all the essential topics under each unit keeping in mind every student’s requirements and assessing their preparation efficiency.

Students must cover all the unit-wise topics before attempting the Structural Engineering exam so that the exam paper is easy to answer. The updated syllabus also ensures that students remain aware of the Structural Engineering updated details to prevent from wasting unnecessary time on irrelevant topics.

Here, we have presented the M. Tech Structural Engineering course curriculum for the student’s reference:

Subjects Topics
ADVANCED STRUCTURAL ANALYSIS
  • Introduction to matrix methods of analysis
  • Assembly of stiffness matrix
  • Analysis of plane truss
  • Special analysis procedures
STRUCTURAL DYNAMICS
  • Theory of vibrations
  • Introduction to Structural Dynamics
  • Single Degree of Freedom Systems
  • Multi Degree of Freedom Systems
  • Practical Vibration Analysis
  • Continuous Systems
  • Introduction to Earthquake Analysis
ADVANCED CONCRETE DESIGN
  • Basic Design Concepts
  • Limit Analysis of R.C.Structures
  • Design of Ribbed slabs
  • Flat slabs
  • Design of Reinforced Concrete Deep Beams & Corbels
  • Design of Compression members
FINITE ELEMENT METHODS
  • Introduction
  • Principles of Elasticity
  • One dimensional FEM
  • Isoparametric formulation
  • AxiSymmetric Analysis
  • Three dimensional FEM
  • Introduction to Finite Element Analysis of Plates
  • Linear analysis – Introduction to non
THEORY OF ELASTICITY AND PLASTICITY
  • Elasticity
  • Analysis of stress and strain
  • Torsion of Prismatic Bars
  • Bars
  • Theory of Plasticity
ADVANCED STEEL DESIGN
  • SIMPLE CONNECTIONS
  • MOMENT and ECCENTRIC CONNECTIONS
  • Design and Analysis of Industrial Buildings
  • DESIGN OF STEEL TRUSS GIRDER BRIDGES
  • Design of Steel Bunkers and Soils

List of Structural Engineering Important Questions

Candidates pursuing Structural Engineering can refer to the list of all the essential questions stated below for the Structural Engineering Notes. The questions assigned are aimed to help the students to excel in the examination.

  1. Why are the shear and moment diagrams essential? Explain
  2. What is the role of BIM in engineering projects?
  3. Explain the benefits of CDM regulations?
  4. Explain the Modulus of Elasticity.
  5. Explain the Redundancy and Equilibrium of Indeterminate Structures.
  6. Define the Pneumatic structure.
  7. Differentiate between static condensation and substructuring.
  8. What is Lumped mass idealization?
  9. Describe the term Deflection.
  10. Why is the Design of Nibs important?
  11. Define the AxiSymmetric Analysis.

Frequently Asked Questions on Structural Engineering Notes

Question 1.
Define the term Structural Engineering.

Answer:
Structural engineering is a specialization within the field of civil engineering that concentrates on the framework of buildings or edifices.

Question 2.
Name some of the important topics of structural engineering.

Answer:
Some of the important topics of Structural engineering are Structural Dynamics , Advanced Concrete Design, Finite Elements Methods, Computer Oriented Numerical Method, Pre Stressed Concrete and Experimental Stress Analysis .

Question 3.
Name some of the reference books for Structural Engineering.

Answer:
Some of the reference books for Structural Engineering are :

  1. Prestressed concrete by Krishna Raju
  2. Numerical methods by S.S.Sastry
  3. Experimental Stress Analysis by Dove and Adams
  4. Theory of Elasticity by Y.C.Fung.
  5. Numerical methods and C Language by C.Xavier

Question 4.
What is the importance of Structural Engineering Notes ?

Answer:
In Structural Engineering Notes, the students will learn the fundamentals of Structural engineering and various aspects of the topics. It will help them score good grades in the exam.

Conclusion

The article on Structural Engineering Notes is an important platform that offers reliable and authentic sources of reference. All the study materials listed above aim to assist and improvise every learner’s knowledge and understanding of the subjects and its topics, during the revision process and examination. Students can download the Structural Engineering Notes PDFs and practice from the provided notes from this article.

Python Programming – NumPy

Learn NumPy Library in Python – Complete Guide

Creating Numpy Arrays

Adding Elements in Numpy Array

Searching in Numpy Arrays

Get Metadata of Numpy Array

Selecting elements from Numpy Array

Modifying a Numpy Array

Converting NumPy Array to Other Data Structures

Numpy Array and File I/O

Verify Contents of Numpy Array

Counting Elements in Numpy Array

Advance Topics about Numpy Array

  • What is a Structured Numpy Array and how to create and sort it in Python?
  • numpy.zeros() & numpy.ones() | Create a numpy array of zeros or ones

Python Programming – NumPy

NUMPY

As discussed previously, simple one dimensional array operations can be executed using list, tuple etc. But carrying out multi-dimensional array operations using list is not easy. Python has an array module which provides methods for creating array, but they are slower to index than list. A good choice for carrying array operations is by using “NumPy” package.

NumPy is a Python package (licensed under the BSD license) which is helpful in scientific computing by providing multi-dimensional array object, various derived objects (such as masked arrays and matrices), and collection of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, basic linear algebra, basic statistical operations, and many more. At the core of the NumPy package, there is array object which encapsulates n-dimensional arrays of homogeneous data types. There are several important differences between the NumPy array and the standard Python sequence:

  • NumPy array has a fixed size at creation, unlike Python list (which can grow dynamically). Changing the size of a ndarray will create a new array and delete the original.
  • All elements in a NumPy array are required to be of the same data type.
  • NumPy array facilitates advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python’s built-in sequences.

History

NumPy is built on (and is a successor to) the successful “Numeric” package. Numeric was reasonably complete and stable, remains available, but is now obsolete. Numeric was originally written in 1995 largely by Jim Hugunin, while he was a graduate student at MIT. In 2001, Travis Oliphant along with Eric Jones and Pearu Peterson created “SciPy”, which had the the strenght of Numeric package along additional functionality. At about the same time as SciPy was being built, some Numeric users were hitting up against the limited capabilities of Numeric.

As a result, “numarray” (now obselete) was created by Perry Greenfield, Todd Miller, and RickWhite at the Space Science Telescope Institute as a replacement for Numeric. In early 2005, Travis Oliphant initiated an effort to bring the diverging community together under a common framework. The effort was paid off with the release of a new package Numpy (with version 0.9.2) in early 2006, which is an amalgam of the code base of Numeric with additional features of numarray. The NumPy name was christened from the unofficial name of “Numerical Python”.

Universal functions

NumPy provides familiar mathematical functions such as sin ( ), cos ( ), exp ( ), etc. In NumPy, these are called “universal functions”. Within NumPy, these functions operate element-wise on an array, producing an array as output.

>>> a=np . arange ( 3 ) 
>>> a 
array ( [ 0 , 1 , 2 ] ) 
>>> np . exp ( a ) 
array ( [ 1 . , 2 . 71828183 , 7 . 3890561 ] )
>>> np . sqrt ( a ) 
array ( [ 0 . , 1 . , 1 . 41421356 ] )

The Matrix Class

There is also a matrix class, which returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations.

>>> np . matrix ( [ [ 1 . 0 , 2 . 0 ] , [ 3 . 0 , 4 . 0 ] ] ) 
matrix ( [ [ 1 . , 2 . ] , 
[ 3 . , 4 . ] ] )
>>> a=np . matrix ( ' 1 . 0 2 . 0 ; 3 . 0 4 . 0 ' ) 
>>> a
matrix ( [ [ 1 . , 2 . ] , 
[ 3 . , 4 . ] ] )
>>> a . T                                                                           # Transpose of a matrix
matrix ( [ [ 1 . , 3 . ] ,
[ 2 . , 4 .] ] ) 
>>> x=np . matrix ( ' 5 . 0 7 . 0 ' )
>>> y=x.T
>>> y
matrix ( [ [ 5 . ] ,
[ 7 . ] ] )
>>> a*y                                                                          # Matrix multiplication
matrix ( [ [ 19 . ] ,
[ 43 . ] ] )
>>> a.I                                                                           # Inverse of a matrix
matrix ( [ [ -2 . , 1 . ] ,
[ 1 . 5 , -0 . 5 ] ] )

In this Page, We are Providing Python Programming – NumPy. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Scope

In this Page, We are Providing Python Programming – Scope. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Scope

Scope

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one. The scope of names defined in a class block is limited to the class block. If a name is bound in a block, it is a local variable of that block. If a name is bound at the module level, it is a global variable. The variables of the module code block are local and global.

In Python, variables that are only referenced inside a function are implicitly global. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and the programmer need to explicitly declare it as global.

The scope is bit difficult to understand, the following examples might prove fruitful.

def f ( ) :
        print s
s=" I hate spam "
f ( )

The variable s is defined as the string “I hate spam”, before the function call f ( ). The only statement in f ( ) is the print statement. As there is no local variable s in f ( ), the value from the global s will be used. So the output will be the string “I hate spam”. The question is, what will happen, if the programmer changes the value of s inside of the function f ( ) ? Will it affect the global s as well? The test is in the following piece of code:

def f ( ) :
      s="Me too." 
      print s
s=" I hate spam." 
f ( )
print s

The output looks like the following. It can be observed that s in f ( ) is local variable of f ( ).

Me too.
I hate spam.

The following example tries to combine the previous two examples i.e. first access s and then assigning a value tp it in function
f ( ).

def f ( ) :
    print s 
    s="Me too." 
    print s

s=" I hate spam." 
f ( )
print s

The code will raise an exception- UnboundLocalError: local variable ‘s’ referenced before assignment

Python assumes that a local variable is required due to the assignment to s anywhere inside f ( ), so the first print statement gives the error message. Any variable which is changed or created inside of a function is local, if it has not been declared as a global variable. To tell Python to recognize the variable as global, use the keyword global, as shown in the following example.

def f ( ) :
      global s 
      print s
      s=" That's clear." 
      print s

s="Python is great ! " 
f ( )
print s

Now there is no ambiguity. The output is as follows:

Python is great !
That's clear.
That's clear.

Local variables of functions cannot be accessed from outside the function code block.

def f ( ) :
s=" I am globally not known" 
       print s
f ( )
print s

Executing the above code will give following error message- NameError : name ‘s’ is not defined

OOPS Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on OOPS

Note: We have come out with a exclusive book on ‘OOP’s with real project scenarios’. In this book 
          we have tried to understand OOP’s fundamentals and also tried to apply them on projects by 
          simulating project scenarios.

Question 1.
What Is Object-Oriented Programming?
Answer:
OOP is a software designing technique where we think in terms of real-world objects.

Question 2.
What are a class and object?
Answer:
Class is a blueprint/template. Objects are instances of classes, in other words, they bring life in class. To use a class we need to ideate an object.

Question 3.
What are different properties provided by object-oriented systems?
Answer:
Following are characteristics of an object-oriented system:

Abstraction: Abstraction means show only what is necessary. Example color is abstracted to RGB (Red, Green Blue). By just making the combination of these three colors we can achieve any color in the world. So rather than remembering each and every color we just use RGB.

Encapsulation: It is a process of hiding all the complex processing from the outside world and makes your objects simple.

Inheritance: This concept helps to define the parent-child relationship between classes.

Polymorphism: It is a property of an object to act differently under different conditions. For instance, a simple user object depending on conditions can act as an admin or as a data entry object.
Remember the word APIE (Abstraction, Polymorphism, Inheritance, and Encapsulation).

Question 4.
How can we implement encapsulation in .NET?
Answer:
Encapsulation can be achieved by using the below five access modifiers.

  • Private: Only members of the class have access to the variables.
  • Protected: All members in the current class and in derived classes can access the variables.
  • Friend (internal in C#): Only members in the current project have access to the elements.
  • Protected friend (protected internal in C#): All members in the current project and all members in the derived class can access the variables.
  • Public: All members have access to all classes and projects.
Note: This question can also be tweaked by asking what are the different access modifiers in .NET

Question 5.
What’s the difference between abstraction and encapsulation?
Answer:

Note:  This question is a bit confusing question. Abstraction says show only what is necessary 
         and encapsulation says hide complexity. Does it look like talking the same things with different faces?

Abstraction and encapsulation complement each other. Encapsulation implements abstraction. Abstraction is the design process while encapsulation happens during the coding phase which is achieved by using access modifiers. Abstraction is done in the design phase while encapsulation is implemented in the execution phase using access modifiers.

Question 6.
How is inheritance implemented in .NET?
Inheritance is implemented by using the “:” symbol.
Below is a simple code snippet where we have the “Customer” class which is the parent class. We have then created a child class called “CustomerDiscount” which inherits all the properties and adds a “Discount” property.

class Customer
{
       public string customer name;
       public string customer code;
}
class CustomerDiscount: Customer
{
       public double Discount;
}

Question 7.
What are the two different types of polymorphism?
Answer:
There are two kinds of polymorphism static and dynamic. Many people also call them runtime or compile-time polymorphism.

Question 8.
How can we implement static polymorphism?
Answer:
Static polymorphism is implemented by using method overloading. In compile-time itself, we come to know if there are mismatches. The below code snippet shows how method overloading is implemented. The add method can take either 2 inputs or 3 inputs.
Depending on the number of inputs the addition logic is executed.

// add method with 2 inputs,
objmaths.add(1, 2);
// add method with 3 inputs,
objmaths.add(1, 2, 3);

Question 9.
How can we implement dynamic polymorphism?
Answer:
Dynamic polymorphism is implemented by using override and virtual keywords.
Below is a simple code snippet that has three classes, Customer class is the parent class.
CustomerDiscountlOPercent and CustomerDiscount2OPercent are child classes.
Customer parent class has a discount function which returns zero discounts. This function is defined as virtual and then overridden by both the child classes with 10% and 20% discounts.

class Customer
{
      public string customerName;
      public string customerCode;
      public virtual int Discount( )
      {
            return 0;
      }
}
class CustomerDiscountlOPercent: Customer
{
      public override int Dis.count( )
      {
          return 10;
      }
}
class CustomerDiscount20Percent: Customer
{
      public override int Discount()
      {
          return 20;
      }
}

Now on the client-side on the fly, your parent object can point to any child classes and invoke the child implementation accordingly. This is called dynamic polymorphism; the parent object can point to any of the child objects and invoke the child function dynamically.

Customer obj;
obj = new CustomerDiscountlOPercent();
obj = new CustomerDiscount2OPercent();

Question 10.
What are downcasting and upcasting?
Answer:
“Upcasting” means moving subclass objects to the parent class object. “Downcasting” is opposite to “Upcasting” moving the parent object to the child object.

OOP Interview Questions in . NET chapter 3 img 1

“Upcasting” is perfectly valid but “Downcasting” is not allowed in .NET as shown in Figure 3.1. For instance below is a simple “Customer” parent class which is further inherited by a child class “GoldCustomer”.

class Customer
{
}
class GoldCustomer: Customer
{
}

Below is an “upcasting” code where the child-parent class GoldCustomer is pushed to the Customer class.

Customer obj=new GoldCustomer( );

Below is a sample of “downcasting” code where a parent class object is tried to move to a child class object, this is not allowed in .NET.

GoldCustomer obj = new Customer( ); //not allowed illegal

Question 11.
What is the difference between overriding and overloading?
Answer:

Note:  I am not sure why this question is asked frequently. It’s like comparing apples with mangoes. 
          Probably it’s just the common word “over” which confuses developers.

Overloading is a concept where we can have the same method names with different input signatures. In overriding, we have a parent class with virtual functions which are overridden in the child classes.

Question 12.
What is operator overloading?
Answer:
Operator overloading is a concept of polymorphism where you can redefine operators like +, *, etc.,
with additional functionalities.

For instance, we can redefine the + functionalities to add objects like obj l + obj 2. Below is the simple code snippet which redefines the + operator.

class SomeClass
{
      private int someValue;
      public SomeClass(int val)
      {
            someValue = val;
      }
      public static SomeClass operator +(SomeClass argl, SomeClass arg2)
      {
            return new SomeClass(arg1.someValue + arg2.someValue);
      }
}

You can now use the + operator to add objects of type some class as shown in the below code snippet.

Obj = obj1 + obj2;

Question 13.
What are abstract classes?
Answer:
An abstract class is a half-defined parent class. The full implementation of abstract class is defined by the child classes.
For example below code, snippet shows a simple abstract class/half-defined class called “DatabaseCommon” and later the concrete classes, i.e., “SQLServer” and “Oracle” inherit and define a complete implementation for the same. To define an abstract class we need to use the abstract keyword.

public abstract class DatabaseCommon
{
}
public class SQLServer: DatabaseCommon
{
}
public class Oracle: DatabaseCommon
{
}

Question 14.
What are abstract methods?
Answer:
Abstract classes can have abstract methods. Abstract methods when defined in a parent class have to be implemented in the child classes. If abstract methods are not implemented it will throw an error.

Question 15.
What is an Interface?
Answer:
An interface is a contract that defines the signature of the functionality. It looks like a class but has no implementation. It has only an empty definition of methods, functions, events, and indexers.

Interfaces provide the forced implementation. For instance, in the below code snippet we have created a simple interface called ” id compulsory”. The below classes who implement interface “id compulsory” have to provide an implementation for “ExecSgi”.

interface IDbCompulsory
{
       void ExecSql();
}
public class SQLServer: IDbCompulsory
{
       public void ExecSql( )
{
// Here code for firing SQL Server SQL statements
// are written
}
}
public class Oracle: IDbCompulsory
{
      public void ExecSql()
      {
          // Here code for firing Oracle SQL statements
         // are written
      }
}

Question 14.
Does the interface have an accessibility modifier?
Answer:
All elements in the Interface should be public. So no accessibility modifier is required.

Question 15.
Can we create an object of the abstract class or an interface?
Answer:
No.

Question 16.
What is the difference between abstract classes and interfaces?
Answer:

Abstract class Interface
Implementation Some methods in abstract classes can have implementation. All methods, functions, properties in interfaces have to empty compulsorily.
Scenario Abstract classes are used when we want to share a common functionality in the parent-child relationships. Interfaces are used to define contracts, enforce standardization, decoupling, and dynamic polymorphism.
Variable declaration We can declare variables. In interface, we cannot declare variables.
Ingeritance VS Implementation Abstract classes are inherited. Interfaces are implemented.

Question 17.
An abstract with only an abstract method, how is it different from interfaces?
Answer:
If you define all methods, functions, properties as abstract in abstract class it inhibits the same behavior as an interface.

Question 18.
If we want to update the interface with new methods, what is the best practice?
Answer:
The biggest use of the interface is to ensure that strict contract is followed between clients and components. So that when changes happen on the components clients do not have to change too much. In real-world contracts between two parties do not change which implies that interfaces should also not change.

So if you want to add new methods or change methods in interfaces the best practice is to create new interfaces by inheriting. With this approach, your older client who is using the interface stays happy and the new clients who want those new or changed methods get the benefits of the new functionality.

Let’s consider you have a simple interface called ” view” which helps you to view data. Below is the code for the same. Let’s consider that this interface is consumed by many clients.

interface IView
{
public void View( );
}

Over a period of time some users demand “Edit” functionality as well but the rest of the users are happy with the ‘View” functionality and they do not want them to get affected by these changes. Now if you go and change this interface (“IView”) as shown in Figure 3.2 you will be disturbing everyone.

So the best option would be to add a new interface, i.e., “lEdit” which inherits from “IView”. So the “lEdit” will have the functionality for “Edit” as well as “View” because it’s also inheriting from “IView”. And the clients who are consuming “IView” do not need to update as “IView’ is not changed at all.

OOP Interview Questions in . NET chapter 3 img 2

interface IEdit: IView
{
public void Edit();
}

So putting this whole story in one single sentence for the interviewer.

Interface once fixed should not be changed. If we ever have to add new functions, new interfaces 
should be created so that we do not break compatibility with old clients.

Question 19.
What is a delegate?
Answer:
Delegate is an abstract pointer to a function or method. In other words, you can create a pointer that points to a method or function and then pass that pointer wherever you wish and invoke the function/ method.

Question 20.
How can we create a delegate?
Answer:
Creating a delegate is a four-step process:
  • Declare a delegate
  • Create an object reference
  • Point the reference to the method
  • Invoke the method via the delegate
Below is the code snippet for the same.
// Declare a delegate
public delegate int PointToAdd(int i, int y) ;
// Create a reference pointer
PointToAdd objpointer = null;
// Point to the method
objpointer = Add;
// Invoke the function/method
objpointer.Invoke(10, 20);
Question 21.
What is a multicast delegate?
Answer:
Normally when you create a delegate, your delegate points to only one function or method. In case you want to point to multiple functions and invoke them sequentially, you need to use the multicast delegate.
To point to multiple functions using delegate pointers we need to use the “+=” sign as shown in the below code snippet.
ptrcall += Method1;

ptrcall += Method2;
Question 22.
What are Events?
Answer:
Events are a higher level of encapsulation over delegates. Events use delegates internally. Delegates are naked and when passed to any other code, the client code can invoke the delegate. The event provides a publisher/subscriber mechanism model.
So subscribers subscribe to the event and the publisher then pushes messages to all the subscribers. Below is a simple code snippet for the same:
Create a delegate and declare the event for the same.
public delegate void CallEveryone( );

public event CallEveryone MyEvent;
Raise the event.
MyEvent( );
Attached client methods to the event are fired/notified.
obj. MyEvent += Function 1;
Question 23.
What is the difference between delegates and events?
Answer:
They(l) What is the difference between delegate and events? can not be compared because one derives from the other.
  • Actually, events use delegates at the bottom. But they add an extra layer of security on the delegates, thus forming the publisher and subscriber model.
  • As delegates function as pointers, they can move across any client. So any of the clients can add or remove events, which can be confusing. But events give the extra protection/encapsulation by adding the layer and making it a publisher and subscriber model. Just imagine one of your clients doing this
c.XyzCallback = null
This will reset all your delegates to nothing and you have to keep searching where the error is.
Question 24.
Do events have a return type?
Answer:
No, events do not have a return type.
Question 25.
Can events have access modifiers?
Answer:
Yes.
Question 26.
Can we have shared events?
Answer:
Yes, you can have shared events, do note only shared methods can raise shared events.
Question 27.
Explain Action, Func, Anonymous methods, and Lambda expressions.
Answer:
Left to the readers.
Question 28.
What is shadowing?
Answer:
Shadowing replaces the complete element of the parent class. For instance, you can see in the below sample code where the cisParent has a variable int “i”, which is replaced by the child class child by a method “i”. In other words when you refer to the parent object “i” it is a variable and when you refer to the child object” i” it is a method.
class clsParent
{
      public int i=0;
}
class cisChild: cisParent
{
     public new void i()
     {
          Console.WriteLine("Hey i became a method");
     }
}

Question 29.
What is the difference between shadowing and overriding?
Answer:
Overriding redefines only the implementation while shadowing redefines the whole element.

Question 30.
If we inherit a class do the private variables also get inherited?
Answer:
Yes, the variables are inherited.
Question 31.
How can we stop the class from further inheriting?
Answer:
We can stop the class from further inheriting by using the “sealed” keyword. For instance below is a sample code where we have a class called “Human” which is further inherited to create a “Male” or “Female” class.
Now the below code is great but we do not have anyone to further inherit from the “Male” or “Female” class. In simple words, “Male” and “Female” are the last legs in this inheritance hierarchy. This can be done by using the “sealed” keyword.
public class Human
{ }
public sealed class Male: Human
{ }
public sealed class Female: Human
{ }

If anyone tries to inherit the sealed classes an error appears” cannot derive from sealed type”.

Question 32.
What is the use of the “Must Inherit” keyword in VB.NET?
Answer:
If you want to create an abstract class in VB.NET it is done by using the “Must Inherit” keyword. You cannot create an object of a class, which is marked as “Must Inherit”. When you define the “Must Inherit” keyword for a class, you can only use the class by inheriting it.
Question 33.
What are the similarities between class and structure?
Answer:
Following are the similarities between classes and structures:
  • Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Structures and classes can implement the interface.
  • Both of them can have constructors with and without parameters.
  • Both can have delegates and events.
Question 34.
What is the difference between class and structure?
Answer:
Following are the key differences between them:
  • Structures are value types and classes are reference types. So structures use stack and classes use heap.
  • Structures members cannot be declared as protected, but class members can be. You cannot do inheritance in structures.
  • Structures do not require constructors while classes require.
  • Objects created from classes are terminated using Garbage Collector (GC). Structures are not destroyed using GC.
Question 35.
When to use structures and when to use classes?
Answer:
You will use structures when:
Point 1: If you want to represent a custom value type. This custom value type is derived from primitive data types (int, double). Some of the examples of custom types are coordinates (which have X, Y), complex numbers (which have real and imaginary components). You can also term these things as value objects or technical objects. Technical objects do not represent real-world objects like customers, suppliers, invoices, etc.
Point 2: If you want to have a low memory footprint. For instance, let’s say you want to plot a graph. To plot a graph you need to have 100’s of objects created so that you can represent coordinates. Now if you create a class and generate those 10Q’s of objects you end up putting a lot of load on your garbage collector. If you create a “struct”, it is a value type as shown in Figure 3.3. So they get created and destroyed immediately. Thus putting less load on memory.
For all other scenarios use a class.
OOP Interview Questions in . NET chapter 3 img 3
Question 36.
What does virtual keyword mean?
Answer:
The signifies that method and property can be overridden by the child classes.
Question 37.
What are shared (VB.NET)/Static(C#) variables?
Answer:
When you define a variable as static or shared only one instance of the object or variable is created.
Question 38.
What is an enum and what are the benefits of using it?
Answer:
enum helps to define, manage and assign constants in an effective way. Now the below sample code is good but the level values are not readable.
if (level == 0)(Console.WriteLine(“Below quality”);}
else if (level == 1)(Console.WriteLine(“Moderate quality”);}
else if(level == 2)(Console.WriteLine(“High quality”);}
Now by declaring a simple enum called Quality as shown below.
enum Quality
{
Low = 0,
Moderate = 1,
High = 2
};

Our code would look more readable as shown below. The other big benefit is if we change the numeric values of quality we do not have to change throughout the project. So we can go a change the Low quality to 1 and no change in code is required.

if (level == Quality.Low)(Console.WriteLine(“Below quality”);}
else if (level == Quality.Moderate)(Console.WriteLine(“Moderate quality”);}
else if(level == Quality.High)(Console.WriteLine(“High quality”);}
So summarizing enum has two big benefits:
  • Code becomes more readable.
  • Easy to change constants without affecting the project. Easy maintenance.
Question 39.
What is the use of Flags in the enum?
Answer:
“Flags” is an enum attribute. If you want to set multiple values to an enum we need to use Flags.
[Flags]
enum MyColors
{
Green = 0,
Red = 1,
Blue = 2
} ;

In the below code we are setting “MyColors” enum to “Blue” and “Green” valuess.

MyColors color = MyColors.Blue | MyColors.Green;


if ((color & MyColors.Blue) == MyColors.Blue)
{
Console.WriteLine(" Blue");
}
if ((color & MyColors.Green) == MyColors.Green)
{
Console.WriteLine(" Green");
}

Question 40.

How can we loop through Enum values?
Answer:
We can use the “Get values ( )” method of the “Enum” class which returns an array of Enum values.
varx = Enum. GetValues(typeot(MyColors));

Question 41.
What is the use of the “Enum. parse” method?
Answer:
Interviewers can also put this question differently on how to convert a string to an Enum value.

OOP Interview Questions in . NET chapter 3 img 4

Many times we would like to convert a string into Enum objects. For example, let’s say you have a color Enum and you would like to pass string “Red” and get Enum object “color. Red”.

“Enum. parse” method parses the string to an Enum value. Like in the below code we pass the “Red” string value and it gets typecasted to enum which has green Enum as a constant.

MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyCo!ors), “Red”);

Question 42.
What are nested classes?
Answer:
Nested classes are classes within classes.
If you create the child class object which constructor will fire first?

public class class1
{
public class1( ){ }
}
public class class2: class1
{
public class2( ){ }
}

Parent class constructor will fire first.

Question 43.
In what instances you will declare a constructor to be private?
Answer:
When we create a private constructor, we cannot create an object of the class. Private constructors are used when we want only a single instance of the class to be created and externally no one can use the ‘ new’ keyword to create the object.

Question 45.
Can we have different access modifiers on getting/set methods of a property?
Answer:
Yes, we can have different access modifiers. The below code will compile perfectly well.

public string CustName
{
get
{
return _Custname;
}
protected set
{
Custname = value;
}
}

Question 46.
How can you define a property read-only for the external world and writable in the same assembly?
Answer:

This question is a variation to the previous question. So it's possible that the interviewer 
  can ask the previous question in this format.

Let’s first try to understand this question. Let’s say if you have a class called “Customer” with a property “CustomerCode”. Now you want that anyone can read from the “CustomerCode” property but this property can only be set from within the assembly.
In other words, anyone can run the below code.

Customer obj = new Customer();
string x = obj.CustomerCode;

But the setting of the value can be only done from within assembly. The below code will run only if it is within the assembly and it will throw an error if it is external to the assembly.

Customer obj = new Customer( );
obj. CustomerCode - “c001”;

This can be achieved by having different access modifiers for “set” and “get” properties on the “CustomerCode” property.

So for the “get”, we will have public access modifiers and for “set” we will apply internal access modifiers. Now because “get” is public this property can be read anywhere and because the “set” is internal it can only be accessed from within assembly. Below is the code for the same.

class Customer
{
      private string _CustomerCode = " ";
      public string CustomerCode
      {
           get { return _CustomerCode; }
           internal set { _CustomerCode = value; }
      }
}

Question 47.
Will the final run in this code?
Answer:
In the below code in the try statement we have a return statement, will the finally block still run.

public static void Main()
{
    try
   {
        // Some code
        return;
  }
  finally
 {
        //Will this run
  }
}

Yes, the final code will run even though there is a return statement in the trial. The final block will run irrespective of what happens in the try block. That’s the reason why finally block is a good place to put clean up code.

Question 48.
What is an Indexer?
Answer:
Many times classes have contained (aggregated or composed) collections. For example, in the below code you can see we have a customer class that has an Address collection.

public class Customer
{
private List<Address> Addresses = new List<Address>( );
}

Now let’s say we would like to fetch the addresses collected by “Pincode” and “PhoneNumber”. So the logical step would be that you would go and create two overloaded functions one which fetches by using “PhoneNumber” and the other by “PinCode”. You can see in the below code we have two functions defined.

public Address getAddress(int PinCode)
{
       for each (Address o in Addresses)
       {
              if (o.Pincode == PinCode)
              {
                   return o;
              }
       }
       return null;
}
public Address getAddress(string PhoneNumber)
{
      for each (Address o in Addresses)
      {
            if (o.MobileNumber == PhoneNumber)
            {
                   return o;
            }
      }
      return null;
}

Now on the client-side, your code would look something as shown below.

Customer Customers = new Customerf);
Customers.getAddress(1001);
Customers.getAddress(“9 090”) ;

Now the above code is great but how about simplifying things further. How about something more simple as shown in the below code. In other words, the class itself is to be indexed.

Customer Customers = new Customer();
Address o = Customers[10001]; o = Customers[“4320948”];

You can see in the Figure 3.5 where we can have two overloaded indexers “Pincode” and “PhoneNumber”.

 

OOP Interview Questions in . NET chapter 3 img 5

This can be achieved by using an indexer. There are two things we need to remember about indexers:

  • “Indexer” is defined by using the ” this” keyword.
  • “Indexer” is a property so we need to define set and get for the same.

Below is the code implementation for the indexer. You can see we have used the “this” keyword with two overloaded functions one which will fetch us address by using the “PhoneNumber” and the other by using “PinCode”.

public class Customer
{
       private List<Address> Addresses = new List<Address>( );
       public Address this[int PinCode]
       {
           get
           {
                  for each (Address o in Addresses)
                  {
                         if (o.Pincode == PinCode)
                         {
                              return o;
                         }
                 }
                 return null;
            }
}
public Address this[string PhoneNumber]
{
      get
      { 
            for each (Address o in Addresses)
            {
                  if (o.MobileNumber == PhoneNumber)
                  { 
                           return o;
                  }
          }
          return null;
         }
     }
}

Once you put the above “indexer” code you should be able to access the address collection from the Customer object using an indexer ” [ ]” as shown in Figure 3.5.

Summarizing in one sentence: Indexers help to access contained collection within a class using a simplified interface. It is syntactic sugar.

Question 49.
Can we have a static indexer in C#?
Answer:
NO.

Managerial Economics and Financial Analysis Notes | Syllabus, Reference Books and Important Questions

Managerial Economics and Financial Analysis Notes

Managerial Economics and Financial Analysis Notes: Planning to choose a career in the field of Managerial Economics And Financial Analysis. Acquiring the best notes will help you to score better marks in the exam. The Managerial Economics And Financial Analysis note includes a comprehensive study plan, all-important information, and timetable. Students can refer to the Big Data Lecture Notes For CSE as per the latest and updated syllabus from this article.

Students will get information about the latest Reference Books, Syllabus, and Important Questions List for Managerial Economics And Financial Analysis Notes. MEFA Notes are one of the essential study materials that can improve the students’ preparation for the exam. Candidates with the help of these notes can score better marks.

The article given below helps the students access the best Managerial Economics And Financial Analysis Notes as per the latest curriculum.

Introduction to Managerial Economics and Financial Analysis

Managerial Economics has its origins in microeconomics and it deals with the individual or micro-enterprises. It deals with the concepts, tools, and methodologies and application of economic theories, to solve practical problems in a business. Managerial economics is a combination of managerial opinion and economics theory. The financial analysis deals with the evaluation of stability, viability and profitability of a business, project or sub-business. It helps professionals to prepare reports using ratios and other financial analysis techniques. Having a clear understanding of this subject allows for evaluation and scanning the external business environment and taking appropriate internal decisions.

Managerial Economics and Financial Analysis Notes and Study Material – Free PDF Download

In Managerial Economics And Financial Analysis Notes, you will learn about the Nature and Scope of Managerial Economics and Financial Analysis Features and different aspects of the topic. Learning from notes helps the student become active, so the learning process is improved. Aspirants can start their preparation with all the tools to help them score better marks in the exam. The students can refer to and use the MEFA Notes and Study Materials as a reference. Students pursuing engineering can also download PDF notes. Students can refer to the following formats for Notes for Managerial Economics And Financial Analysis and increase their efficiency and problem-solving skills to achieve excellent grades in the exams.

  • Managerial Economics and Financial Analysis PDF
  • Managerial Economics and Financial Analysis Notes PDF
  • Managerial Economics and Financial Analysis Lecture Notes Pdf
  • Managerial Economics and Financial Analysis Handwritten Notes PDF
  • Managerial Economics and Financial Analysis Notes Question bank with answers PDF
  • Managerial Economics and Financial Analysis previous year question papers PDF
  • Managerial Economics and Financial Analysis Notes PPT

Managerial Economics and Financial Analysis Notes Reference Books

Reference books for Managerial Economics And Financial Analysis are an essential source of information. It provides explanations and necessary information about the topics. Students should refer to books recommended by subject experts as it will help them to understand the subject accurately. Candidates will understand the topics if they consult the latest version that includes the updated syllabus. Here is a list of the best-recommended books for Managerial Economics And Financial Analysis Reference Books.

  • The market for “lemons”: Uncertainty, Quality and the market mechanism – Akerlof, G. A.
  • The economic implications of learning by doing – Arrow, K. J.
  • Managerial Economics And Business Strategy – Michael Baye
  • Managerial Economy Strategy, Tactics and Applications – Frederick H. Harris, James R. McGuigan, and Moyer
  • Managerial Economics – Kate and Young
  • Financial Modeling and Valuation – Paul Pignataro
  • Financial Analysis and Planning – Jack Alexander
  • Corporate Financial Analysis – Blaine Robertson
  • Managerial Economics And Financial Analysis – A.R Aryasri
  • Managerial Economics and Financial Analysis 2nd Edition – Siddiqui SA, Siddiqui AS
  • Managerial Economics and Financial Analysis- M. Kasi Reddy & Saraswathi
  • Managerial Economics – Varshney & Maheswari

Managerial Economics And Financial Analysis Reference Books

Managerial Economics and Financial Analysis PDF Syllabus

The best way to commence your preparation for the Managerial Economics And Financial Analysis course is to understand the syllabus and the topics of the subject. The syllabus of Managerial Economics And Financial Analysis is a reliable course planning tool that plans and organizes the subject for a student. The article on Managerial Economics And Financial Analysis Notes provide a detailed structure along with the latest and updated syllabus, keeping in mind every student’s requirements and assessing their preparation efficiency.

The curriculum of Managerial Economics And Financial Analysis provides students a clear idea about what and how to study and analyze the subject. The article on MEFA Notes presents all the essential topics under each unit so that students can allot time for each topic and prepare accordingly. Students must cover all the unit-wise topics before attempting the Managerial Economics And Financial Analysis Lecture Notes PDF so that the exam paper is easy to answer. The updated syllabus also assures that students remain aware of the MEFA Lecture Notes updated syllabus to prevent wasting unnecessary time on irrelevant topics.

Here is a list syllabus for Managerial Economics And Financial Analysis course.

Chapter Topics 
Introduction to Managerial Economics Definition, Nature and Scope of Managerial Economics, Micro and Macroeconomic concepts.

Demand Analysis

Demand Determinants, Law of Demand and exceptions.

Elasticity Of Demand:

Definition, Significance and Types, Measurement of elasticity of Demand. Forecasting Demand, Factors governing demand Forecasting, methods of Demand Forecasting.

Production & Cost Analysis Production Function- Isocost and Isoquants MRTS, Combination of Inputs- Least Cost, Production function Cobb-Douglas, Laws of Returns, Internal and External Economies of Scale.

Cost Analysis

Cost concepts. Break-even Analysis Determination of Break-Even Point – Managerial Significance.

Markets & New Economic Environment Types of Markets and competition, Perfect competition Features, Monopolistic Competition and Monopoly. Policies and Objectives of Pricing- Methods of Pricing. Business

Features of different forms of Business Organisation, Changing Business Environment in Post-liberalization scenario.

Introduction to Capital and Financial Accounting Capital and its significance, Types of Capital, Working capital and Estimation of Fixed requirements, sources and methods of raising finance – Capital Budget, Trading forecast, Cash Budget. Concepts, Accounting Definition and Conventions (GAAP); Formats for preparation of Trial Balance and Final Accounts -Profit and Loss Account, Trading Account, and Balance Sheet.
Investment Decision Capital budgeting proposals Features, Capital Budgeting Methods: Payback Method, Accounting Rate of Return (ARR) and Net Present Value Method (simple problems). Financial Analysis: Activity Ratios, Interpretation and Analysis of Liquidity Ratios, and Profitability ratios and Capital structure Ratios.

List of Managerial Economics and Financial Analysis Important Questions

Candidates pursuing Managerial Economics And Financial Analysis can refer to the list of all the essential questions stated below for the Managerial Economics, And Financial Analysis notes. The assigned questions are aimed to help the students to excel in the examination. Here is a list of questions that will help the students to understand the subject precisely.

  • What do you mean by Managerial Economics?
  • Define the term Macro Economics.
  • What is the difference between Macro Economics and Micro Economics?
  • Describe the term Break-Even Point.
  • What do you mean by Iso- Cost?
  • Define the term Iso- Quant.
  • Demonstrate perfect competition.
  • Describe product differentiation
  • What is oligopoly?
  • Outline the fundamentals of capital.
  • Explain the elements of working capital.
  • What is Financial Accounting?
  • Discuss the significance of Journal Proper.
  • What are the different types of Accounting Concepts?

MEFA Important Questions

Frequently Asked Questions on Managerial Economics and Financial Analysis Notes

Question 1.
Name some of the topics of Managerial Economics and Financial Analysis?

Answer:
Some of the topics of Managerial Economics and Financial Analysis are: Production & Cost Analysis, Capital and Financial Accounting Introduction, Markets & New Economic Environment and Investment Decision

Question 2.
What are the strategies to study for the Managerial Economics and Financial Analysis exam?

Answer:
Candidates preparing for the engineering exam should make notes on all related study materials and questions for smooth preparation. They should practice more mock tests, test series and explore more books for preparation for exams. They should also practice the updated version of MEFA books.

Question 3.
Define the term Managerial Economics?

Answer:
Managerial economics deals with the concepts, tools, and methodologies, and application of economic theories, to solve practical problems in a business. Managerial economics is a combination of managerial opinion and economics theory.

Question 4.
What is Financial Analysis?

Answer:
The financial analysis deals with the evaluation of stability, viability, and profitability of a business, project, or sub-business. Financial Analysis is operated by professionals who prepare reports using other techniques and ratios.

Conclusion

The Managerial Economics And Financial Analysis Notes Pdf and Study Materials presented above are aimed to assist the students at the time of exam preparations. They are reliable and have authoritative references focused on helping graduates and improving their knowledge and understanding of the subject during the time of preparation for the exam. Students can refer and practice from the provided notes for Managerial Economics And Financial Analysis and essential questions from this article.

Python Interview Questions on Array Sequence

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Array Sequence

Low Level Arrays

Let’s try to understand how information is stored in low-level computer architecture in order to understand how array sequences work. Here is a small brush-up on computer science basics on memory units.

We know that the smallest unit of data in a computer is a bit (0 or 1). 8 bits together make a byte. A byte has 8 binary digits. Characters such as alphabets, numbers, or symbols are stored in bytes. A computer system memory has a huge number of bytes and tracking of how information is stored in these bytes is done with the help of a memory address. Every byte has a unique memory address which makes tracking information easier.

The following diagram depicts a lower-level computer memory. It shows a small section of memory of individual bytes with consecutive addresses.

Python Interview Questions on Array Sequence chapter 9 img 1

Computer system hardware is designed in such a manner that the main memory can easily access any byte in the system. The primary memory is located in the CPU itself and is known as RAM. Any byte irrespective of the address can be accessed easily. Every byte in memory can be stored or retrieved in constant time, hence its Big-O notation for the time complexity would be O(1).

There is a link between an identifier of a value and the memory address where it is stored, the programming language keeps a track of this association. So, a variable student_name may store name details for a student and class_ teacher would store the name of a class teacher. While programming, it is often required to keep a track of all related objects.

So, if you want to keep a track of scores in various subjects for a student, then it is a wise idea to group these values under one single name, assign each value an index and use the index to retrieve the desired value. This can be done with the help of Arrays. An array is nothing but a contiguous block of memory.

Python internally stores every Unicode character in 2 bytes. So, if you want to store a 5-letter word (let’s say ‘state’) in python, this is how it would get stored in memory:

Python Interview Questions on Array Sequence chapter 9 img 2

Since each Unicode character occupies 2 bytes, the word STATE is stored in 10 consecutive bytes in the memory. So, this is a case of an array of 5 characters. Every location of an array is referred to as a cell. Every array element is numbered and its position is called index. In other words, the index describes the location of an element.

Table

Every cell of an array must utilize the same number of bytes.

The actual address of the 1st element of the array is called the Base Address. Let’s say the name of the array mentioned above is my_array[ ]. The Base address of my_array[ ] is 1826. If we have this information it is easy to calculate the address of any element in the array.

Address of my array [index] = Base Address +( Storage size in bytes of one element in the array) * index.

Therefore, Address of my array[3] = 1826 + 2*3
= 1826 + 6
= 182C
After that, slight information on how things work at a lower level lets’s get back to the higher level of programming where the programmer is only concerned with the elements and index of the array.

Referential Array

We know that in an array, every cell must occupy the same number of bytes. Suppose we have to save string values for the food menu. The names can be of different lengths. In this case, we can try to save enough space considering the longest possible name that we can think of but that does not seem to be a wise thing to do like a lot of space is wasted in the process and you never know there may be a name longer than the value that we have catered for. A smarter solution, in this case, would be to use an array of object references.

Python Interview Questions on Array Sequence chapter 9 img 3

In this case, every element of the array is actually a reference to an object. The benefit of this is that every object which is of string value can be of different length but the addresses will occupy the same number of cells. This helps in maintaining the constant time factor of order O(1).

In Python, lists are referential in nature. They store pointers to addresses in the memory. Every memory address requires a space of 64-bits which is fixed.

Question 1.
You have a list integer list having integer values. What happens when you give the following command?
integer_list[1] + = 7
Answer:
In this case, the value of the integer at index 1 does not change rather we end up referring to space in the memory that stores the new value i.e. the sum of integer_list[1]+7.

Question 2.
State whether True or False:
A single list instance may include multiple references to the same object as elements of the list.
Answer:
True

Question 3.
Can a single object be an element of two or more lists?
Answer:
Yes

Question 4.
What happens when you compute a slice of the list?
Answer:
When you compute a slice of the list, a new list instance is created. This new list actually contains references to the same elements that were in the parent list.
For example:

>>> my_list = [1, 2,8,9, "cat", "bat", 18]
>>> slice_list = my_list[2:6]
>>> slice_list
[8, 9, 'cat' , 'bat' ]
>>>

This is shown in the following diagram:

Python Interview Questions on Array Sequence chapter 9 img 4

Question 5.
Suppose we change the value of the element at index 1 of the slice just to 18 (preceding diagram). How will you represent this in a diagram?
Answer:
When we say sliceJist[1]=18, we actually are changing the reference that earlier pointed to 9 to another reference that points to value 18. The actual integer object is not changed, only the reference is shifted from one location to the other.

Python Interview Questions on Array Sequence chapter 9 img 5

Deep Copy and Shallow Copy in Python

Python has a module named “copy” that allows deep copy or shallow copy mutable objects.

Assignment statements can be used to create a binding between a target and an object, however, they cannot be used for copying purposes.

Deep Copy

The copy module of python defines a deepcopy( ) function which allows the object to be copied into another object. Any changes made to the new object will not be reflected in the original object.

In the case of shallow copy, a reference of the object is copied into another object as a result of which changes made in the copy will be reflected in the parent copy. This is shown in the following code:

Python Interview Questions on Array Sequence chapter 9 img 6

Python Interview Questions on Array Sequence chapter 9 img 7

It is important to note here that shallow and deep copying functions should be used when dealing with objects that contain other objects (lists or class instances), A shallow copy will create a compound object and insert into it, the references the way they exist in the original object. A deep copy on the other hand creates a new compound and recursively inserts copies of the objects the way they exist in the original list.

Question 6.
What would be the result of the following statement? my list = [7]* 10?
Answer:
It would create a list named my list as follows:
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]

Python Interview Questions on Array Sequence chapter 9 img 8

All the 10 cells of the list my_list, refers to the same element which in this case is 10.

Question 7.
Have a look at the following piece of code:

>>> a = [1,2,3,4,5,6,7]
>>> b = a
>>>b [ 0 ] = 8
>>> b
[8, 2, 3, 4, 5, 6, 7]
>>> a
[8, 2, 3, 4, 5, 6, 7]
>>>

Here, we have used the assignment operator still on making changes to ‘b’ changes are reflected in ‘a’. Why?
Answer:
When you use an assignment operator you are just establishing a relationship between an object and the target. You are merely setting a reference to the variable. There are two solutions to this:

(I)

>>> a
[8,2,3, 4, 5, 6, 7]
>>>a = [ 1,2 3, 4,5 ,6, 7]
>>> b = a [:]
>>>b[0] = 9
>>> b
[9, 2, 3, 4, 5, 6, 7]
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>>

(II)

>>> a = [ 1,2 3, 4,5 6, 7]
>>> b = list (a)
>>>b
[1,2, 3, 4, 5, 6, 7]
>>>b [0] = 9
>>> b
[9, 2, 3, 4, 5, 6, 7]
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>>

Question 8.
Take a look at the following piece of code:

>>> import copy
>>> a = [1 9 9 4 5, 5]
>>> b = copy.copy(a)
>>> b
[l, 2, 3, 4, 5, 6]
>>>b [2] = 9
>>> b
[1.2, 9, 4, 5, 6]
>>> a
[1.2, 3, 4, 5, 6]
>>>

‘b’ is a shallow copy of ‘a’ however when we make changes to ‘b’ it is not reflected in ‘a’, why? How can this be resolved?
Answer:
List ‘a’ is a mutable object (list) that consists of immutable objects (integer).
A shallow copy would work with the list containing mutable objects.
You can use b=a to get the desired result.

Question 9.
Look at the following code:

>>> my_list = [["apples", "banana"], ["Rose", "Lotus"], ["Rice", "Wheat"]]
>>> copy_list = list (my_list)
>>> copy_list[2][0]="cereals"

What would happen to the content of my_list? Does it change or remains the same?
Answer:
Content of my_list will change:

>>> my list [['apples', 'banana'] , [ 'Rose', 'Lotus'],
['cereals', 'Wheat']]
>>>

Question 10.
Look at the following code:

>>> my_list = [ ["apples", "banana"], ["Rose", "Lotus"], ["Rice", "Wheat"]]
>>> copy_list = my_list.copy( )
>>> copy_list[2][0]="cereals"

What would happen to the content of my_list? Does it change or remains the same?
Answer:
Content of my_list would change:

>>> my_list
[ [ 'apples' , 'banana1' ] , [ 'Rose' , 'Lotus' ] ,
[ 'cereals', 'Wheat']]
>>>

Question 11.
When the base address of immutable objects is copied it is called_________________.
Answer:
Shallow copy

Question 12.
What happens when a nested list undergoes deep copy?
Answer:
When we create a deep copy of an object, copies of nested objects in the original object are recursively added to the new object. Thus, a deep copy will create a completely independent copy of not only of the object but also of its nested objects.

Question 13.
What happens when a nested list undergoes shallow copy?
Answer:
A shallow copy just copies references of nested objects therefore the copies of objects are not created.

Dynamic Arrays

As the name suggests dynamic array is a contiguous block of memory that grows dynamically when new data is inserted. It has the ability to adjust its size automatically as and when there is a requirement, as a result of which, we need not specify the size of the array at the time of allocation and later we can use it to store as many elements as we want.

When a new element is inserted in the array, if there is space then the element is added at the end else a new array is created that is double in size of the current array, so elements are moved from the old array to the new array and the old array is deleted in order to create some free memory space. The new element is then added at the end of the expanded array.

Let’s try to execute a small piece of code. This example is executed on 32-bit machine architecture. The result can be different from that of 64-bit but the logic remains the same.
For a 32-bit system 32-bits (i.e 4 bytes) are used to hold a memory address. So, now let’s try and understand how this works:
When we created a blank list structure, it occupies 36 bytes in size. Look at the code given as follows:

import sys
my_dynamic_list =[ ]
print("length = ",len(my_dynamic_list) , ".", "size in bytes = ", sys.getsizeof(my_dynamic_list),".")

Here we have imported the sys module so that we can make use of getsizeof( ) function to find the size, the list occupies in the memory.
The output is as follows:
Length = 0.
Size in bytes = 36 .
Now, suppose we have a list of only one element, let’s see how much size it occupies in the memory.

import sys
my_dynamic_list =[1]
print("length = ",len(my_dynamic_list),".", "size in bytes = ", sys.getsizeof(my_dynamic_list),".")
length = 1 . size in bytes = 40 .

This 36 byte is just the requirement of the list data structure on 32- bit architecture.
If the list has one element that means it contains one reference to memory and in a 32-bit system architecture memory, the address occupies 4 bytes. Therefore, the size of the list with one element is 36+4 = 40 bytes.
Now, let’s see what happens when we append to an empty list.

import sys
my_dynamic_list =[ ]
value = 0
for i in range(20):
print("i = ",i,".", "                                  Length of my_
dynamic_list = ",len(my_dynamic_list),".", " size in bytes = ", sys.getsizeof(my_dynamic_ list),".")
my_dynamic_list.append(value)
value +=1

Output
i = 0 .    Length of mydynamic list = 0 .      size in bytes =36
i = 1 .    Length of my_dynamic_list = 1 .    size in bytes = 52
i = 2 .    Length of my_dynamic list = 2 .    size in bytes = 52
i = 3 .    Length of my dynamic list = 3 .    size in bytes = 52
i = 4.     Length of my dynamic list = 4 .    size in bytes = 52
i= 5.      Length of my dynamic list = 5 .    size in bytes = 68
i = 6.     Length of my_dynamic_list = 6 .   size in bytes = 68
i = 7.     Length of my_dynamic_list = 7 .   size in bytes = 68
i = 8 .    Length of my_dynamic_list = 8 .   size in bytes = 68

i = 9.     Length of my_dynamic_list = 9 .   size in bytes = 100
i = 10.   Length of my dynamic list =10.    size in bytes = 100
i = 11 .  Length of my dynamic list =11.    size in bytes = 100
i = 12 .  Length of my_dynamic_list = 12 . size in bytes = 100
i = 13 .  Length of my dynamic list =13.    size in bytes = 100
i = 14.   Length of my_dynamic_list = 14 . size in bytes = 100
i = 15 .  Length of my dynamic list =15.    size in bytes = 100
i = 16.   Length of my dynamic list = 16.   size in bytes = 100
i = 17.   Length of my_dynamic_list =17.   size in bytes = 136
i = 18 .  Length of my dynamic list =18.    size in bytes = 136
i = 19.  Length of my_dynamic_list = 19.   size in bytes = 136

Now, lets have a look at how things worked here:

When you call an append( ) function for list, resizing takes place as per list_resize( ) function defined in Objects/listobject.c file in Python. The job of this function is to allocate cells proportional to the list size thereby making space for additional growth.
The growth pattern is : 0,4,8,16,25,35,46,58,72,88,

Amortization

Let’s suppose that there is a man called Andrew, who wants to start his own car repair shop and has a small garage. His business starts and he gets his first customer however, the garage has space only to keep one car. So, he can only have one car in his garage.

Python Interview Questions on Array Sequence chapter 9 img 9

Seeing a car in his garage, another person wants to give his car to him. Andrew, for the ease of his business, wants to keep all cars in one place. So, in order to keep two cars, he must look for space to keep two cars, move the old car to the new space and also move the new car to the new space and see how it works.

So, basically, he has to:

  1. Buy new space
  2. Sell the old space

Let’s say, this process takes one unit of time. Now, he also has to:

  1. Move the old car to a new location
  2. Move the new car to a new location Moving each car takes one unit of time.

Python Interview Questions on Array Sequence chapter 9 img 10

Andrew is new in the business. He does not know how his business would expand, also what is the right size for the garage. So, he comes up with the idea that if there is space in his garage then he would simply add the new car to space, and when the space is full he will get a new space twice as big as the present one and then move all cars there and get rid of old space. So, the moment he gets his new car, it’s time to buy a new space twice the old space and get rid of the old space.

Python Interview Questions on Array Sequence chapter 9 img 11

Now, when the fourth car arrives Andrew need not worry. He has space for the car.
Python Interview Questions on Array Sequence chapter 9 img 12
And now again when he gets the fifth car he will have to buy a space that is double the size of the space that he currently has and sell the old space.

So, let’s now take a look at the time complexity: Let’s analyze how much does it take to add a car to Andrew’s garage where there is n number of cars in the garage.

Here is what we have to see:

1. If there is space available, Andrew just has to move one car into a new space and that takes only one unit of time. This action is independent of the n (number of cars in the garage). Moving a car in a garage that has space is constant time i.e. O(1).

2. When there in spot and a new car arrives, Andrew has to do the following:

  • Buy a new space that takes 1 unit of time.
  • Move all cars into new space one by one and then move the new car into free space. Moving every car takes one unit of time.

So, if there were n cars already in the old garage, plus one car then that would take n+1 time units to move the car.
So, the total time taken in step two is 1+n+l and in Big O notation this would mean O(n) as the constant does not matter.

On the look of it, one may think this is too much of a task but every business plan should be correctly analyzed. Andrew will buy a new garage only if the space that he has, gets all filled up. On spreading out the cost over a period of time, one will realize that it takes a good amount of time only when the space is full but in a scenario where there is space, the addition of cars does not take much time.

Now keeping this example in mind we try to understand the amortization of dynamic arrays. We have already learned that in a dynamic array when the array is full and a new value has to be added, the contents of the array are moved on to the new array that is double in size, and then the space occupied by the old array is released.

 

Python Interview Questions on Array Sequence chapter 9 img 13

It may seem like the task of replacing the old array with a new one is likely to slow down the system. When the array is full, appending a new element may require O(n) time. However, once the new array has been created we can add new elements to the array in constant time O(1) till it has to be replaced again. We will now see that with the help of amortization analysis how this strategy is actually quite efficient.

As per the graph above, when there are two elements then on calling append, the array will have to double in size, same after 4th and 8th element. So, at 2, 4, 8, 16… append will be O(n) and for the rest of the cases, it will be 0(1).
The steps involved are as follows:

  1. When the array is full, allocate memory for the new array and the size of the new array should typically be twice the size of the old array.
  2. All contents from the old array should be copied to the new array.
  3. The space occupied by the old array should be released.

 

Python Interview Questions on Array Sequence chapter 9 img 14

The analysis would be as follows:
Python Interview Questions on Array Sequence chapter 9 img 15

JSP Implicit Objects: 9 Implicit Objects in JSP | Complete Tutorial on Implicit Objects in JSP

JSP Implicit Objects- 9 Implicit Objects in JSP

In the earlier tutorial, we have seen JSP Scripting Elements with Example. In this tutorial, we will discuss & understand JSP implicit objects with examples. Primarily, there are 9 implicit objects in JSP. Let’s learn all these implicit objects in detail. But first, learn what is JSP implicit objects?

This Implicit Objects in JSP Tutorial Contains: 

What are JSP Implicit Objects?

Implicit objects are the set of predefined objects readily available for use. These objects are created by the JSP container, while a JSP page translates into Servlet. Implicit Objects are being created inside the service() method so we can use implicit objects directly within scriptlets without initializing and declaring them. Total 9 Implicit objects are available in JSP.

Implicit Objects and their corresponding classes

out javax.servlet.jsp.JspWriter
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
exception javax.servlet.jsp.JspException
page java.lang.Object
pageContext javax.servlet.jsp.PageContext
config javax.servlet.ServletConfig

Also Check: 

How many Implicit Objects are available in JSP?

There are 9 types of implicit objects available in the container:

  1. out
  2. request
  3. response
  4. page
  5. pageContext
  6. config
  7. application
  8. session
  9. exception

Let’s check out one by one from the below sections:

1. out:

It is used for writing content to the client browser. It is an object of the JSP Writer. In servlet you need to write PrintWriter out = response.getWriter() for writing content to the browser, but in JSP you don’t need to write this.

2. request:

It is an object of HttpServletRequest.This object is created for each JSP request by the web container. The main purpose of this object is to get the data on a JSP page which is entered by the user. This object is used to get request information like a parameter, header information, content type, server name, etc.

JSP Implicit Objects 9 Implicit Objects in JSP 1

JSP Implicit Objects 9 Implicit Objects in JSP 2

JSP Implicit Objects 9 Implicit Objects in JSP 3

JSP Implicit Objects 9 Implicit Objects in JSP 4

3. response:

It is an object of HttpServletResponse. This object will be created by the container for each request. We can use the response object to set content type, adding cookies, and redirecting the request to another resource.

JSP Implicit Objects 9 Implicit Objects in JSP 5

JSP Implicit Objects 9 Implicit Objects in JSP 6

4. page:

JSP page implicit object is an object of java.lang.Object class. This object represents the current JSP page. It is rarely used. It provides a reference to the generated servlet class.

5. pageContext:

JSP pageContext object is an object of javax.servlet.jsp.PageContext class. It is used for accessing page, application, request and session scope.

JSP Implicit Objects 9 Implicit Objects in JSP 7

JSP Implicit Objects 9 Implicit Objects in JSP 8

JSP Implicit Objects 9 Implicit Objects in JSP 9

6. config:

JSP config implicit object is an instance of java.servlet.ServletConfig class. This object is created by the container for each JSP page. It is used to get the initialization parameter in the deployment descriptor(web.xml) file.

JSP Implicit Objects 9 Implicit Objects in JSP 10

JSP Implicit Objects 9 Implicit Objects in JSP 11

JSP Implicit Objects 9 Implicit Objects in JSP 12

7. application:

JSP application implicit object is an instance of java.servlet.servletContext class.It is used to obtain the context information and attributes in JSP.The servlet context obtained from the servlet configuration object by using the getServletConfig().getServletContext() method.One application object is created by the container for one JSP application when the application is deployed.

JSP Implicit Objects 9 Implicit Objects in JSP 13

JSP Implicit Objects 9 Implicit Objects in JSP 14

JSP Implicit Objects 9 Implicit Objects in JSP 15

8. session:

JSP Session implicit object is an instance of javax.servlet.http.HttpSession class.The session object is created for the requesting clients(if any). This variable is only valid for HTTP-based protocol. we can use this object to get, set, and remove an attribute from the session scope.

JSP Implicit Objects 9 Implicit Objects in JSP 16

JSP Implicit Objects 9 Implicit Objects in JSP 17

JSP Implicit Objects 9 Implicit Objects in JSP 18

JSP Implicit Objects 9 Implicit Objects in JSP 19

JSP Implicit Objects 9 Implicit Objects in JSP 20

JSP Implicit Objects 9 Implicit Objects in JSP 21

9. Exception:

JSP exception implicit object is an instance of java.lang.Throwable class. It is used for exception handling in JSP. It can be only used for the JSP error page.

Mechatronics and Microprocessor Vtu Notes | Syllabus, Reference Books and Important Questions

Mechatronics and Microprocessor Vtu Notes

Mechatronics and Microprocessor Vtu Notes: Candidates who are trying to get a hold of the Mechatronics And Microprocessor Vtu Notes Pdf can access it on this article. This article is a credible source which is going to enhance the preparation and revision process of the essential concepts. Students can refer to the Big Data Lecture Notes For CSE as per the latest and updated syllabus from this article.

The article on Mechatronics And Microprocessor Vtu Notes Pdf acts as the main source of the study material which can enhance and improve the knowledge of students, and This article provides a detailed view of all the important topics according to the latest syllabus.

The article on Mechatronics And Microprocessor Vtu Notes Pdf gives candidates a head start as they can access the latest and up to date study material. Students can access the latest syllabus, expert-recommended reference books, and list of all essential questions on Mechatronics And Microprocessor. Students will be able to score the best scores with the usage of the study material.

Candidates can access, download, and refer to Mechatronics And Microprocessor Vtu Notes Pdf and other study material from this article. It is going to help students prepare a better study strategy with the best study material and achieve the best scores.

Introduction to Mechatronics and Microprocessor

Mechatronics is a field that is a combination of various types of engineering. In Mechatronics, students will gain knowledge about electrical, computer and mechanical engineering. Students will learn about contemporary, advanced and automated manufacturing engineering. It is an important concept necessary for the growth in the sector of automation and manufacturing.

A microprocessor is the second important aspect of the course. The device is an integrated circuit. The microprocessor incorporates the core functions of the CPU.

Mechanical Engineering Mechatronics and Microprocessor Vtu Notes PDF Free Download

Students who are pursuing their Mechanical Engineering can access the Mechatronics And Microprocessor article and download the important and credible notes in pdf for free. Students can improve and better their preparation with the ultimate preparation tools to improve their approach and secure the best marks.

Students can download the Mechatronics And Microprocessor Study Material and notes and refer to them during the process of their preparation. The frequent utilisation and use of the Mechatronics And Microprocessor Vtu Notes Pdf as a source of reference are going to help candidates get a better understanding of the various topics.

Here is a list of a few important Mechatronics And Microprocessor Vtu Notes for a thorough preparation of the course programme:

  • Mechatronics and Microprocessor Vtu Notes for Mechanical Engineering PDF
  • Mechatronics and Microprocessor Vtu Notes PDF
  • Mechatronics and Microprocessor Vtu Handwritten Notes PDF
  • Introduction to Mechatronics And Microprocessor Vtu Notes PDF
  • Mechatronics and Microprocessor Vtu Programme Previous Year’s Question Paper PDF
  • Mechatronics and Microprocessor Vtu Lecture Notes PDF

Mechatronics and Microprocessor Reference Books

The best sources of information are reference books. It is a guide to students as it enhances and improves their knowledge and understanding of the various topics of a subject. Reference books are a source which is going to impart skills, knowledge, values and attitudes to the candidates about the subject.

Students can access and avail the best and important reference books for Mechatronics And Microprocessor according to the subject-experts’ recommendations. Candidates can refer and read through the Mechatronics And Microprocessor Reference Books during their preparation process.

The list of the best and most important books for Mechatronics And Microprocessor preparation are as follows. Candidates must select a book that meets their knowledge and requirements.

  • Principles, Concepts and Applications- Mechatronics
  • Mechatronics
  • Introduction to Mechatronics and Measurement Systems
  • A Textbook on Mechatronics
  • Mechatronics: Integrated Mechanical Electronic System
  • Mechatronics: Principles, Concepts and Applications
  • Introduction to Mechatronics
  • Microprocessors: Principles and Applications
  • Advanced Microprocessors and Peripherals

Mechatronics and Microprocessor Curriculum

The Mechatronics And Microprocessor curriculum is the most effective course planning tool that structures the preparation process of the students. One of the best ways to enhance and improve your preparation is by having an initial idea of the Mechatronics And Microprocessor syllabus.

The article on Mechatronics And Microprocessor Vtu Notes Pdf provides a comprehensive and detailed view of the Mechatronics And Microprocessor curriculum, taking into consideration every student’s requirements and preparation approach.

A planned course curriculum gives students a clear idea of what to study, how to study, and prepare for the examination. From this article, you can access the unit-wise segmentation of the important topics and concepts. Students should ensure they study all the topics carefully.

Students should cover all important topics before they attempt the Mechatronics And Microprocessor examination so that the paper is easy. Candidates must also remain aware of all the topics and concepts of the syllabus. When they know the topics, they will be able to avoid studying redundant and unnecessary topics.

Units Topics
Unit I Unit-1Introduction to Mechatronic Systems

Measurement and control systems

Their elements and functions

Microprocessor-based controllers.

Unit II Review of Transducers and Sensors

Definition and classification of transducers

Definition and classification of sensors

Principle of working and applications of light sensors

proximity sensors and Hall effect sensors.

Unit III Electrical Actuation Systems

Electrical systems

Mechanical switches

solid-state switches

solenoids

DC & AC motors

Stepper motors

their merits and demerits.

Unit IV Signal Conditioning

Introduction to signal to condition

The operational amplifier

Protection

Filtering

Wheatstone bridge

Digital signals Multiplexers

Data acquisition

Introduction to Digital system

Processing Pulse-modulation.

Unit V Introduction to Microprocessors

Evolution of Microprocessor

The organisation of Microprocessors (Preliminary concepts)

basic concepts of programming of microprocessors

Review of concepts

Boolean algebra

Logic Gates

Gate Networks

Binary & Decimal number systems

memory representation of positive and negative integers

maximum and minimum integers

Conversion of real

numbers

floating-point notation

representation of floating-point numbers

accuracy and range in floating-point representation

overflow and underflow

addition of floating-point numbers

character representations

Unit VI Logic Function

Data word representation

Basic elements of control systems 8085A

processor architecture terminologies such as CPU, memory and address

ALU

assembler data registers

Fetch cycle

write cycle

state

bus

interrupts. Micro Controllers

Difference between microprocessor and microcontrollers

Requirements for control and their implementation in microcontrollers

Classification of microcontrollers.

Unit VII Organisation & Programming of Microprocessors

Introduction to the organisation of INTEL 8085

Data and Address buses

The instruction set of 8085

programming the 8085

assembly language programming

Unit VIII Central Processing Unit of Microprocessors

Introduction

timing and control unit basic concepts

Instruction and data flow

system timing

examples of INTEL 8085 and INTEL 4004 register organisation.

List of Mechatronics And Microprocessor Important Questions

Candidates pursuing Mechanical Engineering can read through the list of all the important questions in the list below on Mechatronics And Microprocessor Vtu Notes Pdf. All the review questions aim at enhancing and improving the knowledge of students to excel in the examination and achieve better scores.

  • Write a short note on the basic functions of the control system.
  • What are the requirements of the control system? Explain in detail.
  • State some of the benefits of mechatronics?
  • With the help of the structure of a programmable logic controller, explain the function of each block.
  • Write a short note on the operation of a linear variable differential transducer.
  • Define the position sensors.
  • Please write a short note on the working go Hall effect sensors and its advantages.
  • With the help of a diagram, draw the microcontroller and mention the function of each block.
  • Diagrammatically explain the control unit.
  • What is meant by Fetch Cycle?

FAQs on Mechatronics and Microprocessor Vtu Notes

Question 1.
What are Mechatronics and Microprocessors?

Answer:
Mechatronics is a field that is a combination of various types of engineering. In Mechatronics, students will gain knowledge about electrical, computer and mechanical engineering. Students will learn about contemporary, advanced and automated manufacturing engineering. It is an important concept necessary for the growth in the sector of automation and manufacturing. A microprocessor is the second important aspect of the course. The device is an integrated circuit. The microprocessor incorporates the core functions of the CPU.

Question 2.
How is Mechatronics And Microprocessor Vtu Notes Pdf useful?

Answer:
The Mechatronics And Microprocessor Vtu Notes Pdf offer important and credible notes for students to download for free and refer to during their preparations. Mechatronics And Microprocessor Vtu Notes acts as the main tool of preparation for the students to improvise and enhance their study preparation.

Students can download these Mechatronics And Microprocessor Vtu Notes Pdf and refer to them when they are preparing for their examination. The frequent utilization and use of the Mechatronics And Microprocessor Vtu Notes Pdf as a source of reference will help candidates get a better hunch and a basic overview of the essential concepts.

Question 3.
List out some of the important reference books that students can refer to for Mechatronics And Microprocessor?

Answer: 
Here is a list of some of the important reference books that students can refer to for Mechatronics And Microprocessor:

  • Principles, Concepts and Applications- Mechatronics
  • Introduction to Mechatronics and Measurement Systems
  • A Textbook on Mechatronics
  • Microprocessors: Principles and Applications
  • Advanced Microprocessors and Peripherals

Question 4.
State some of the questions that students can review when they are studying for the Mechatronics And Microprocessor examination.

Answer:
Here are some of the questions that students can refer to when they are studying for the Mechatronics And Microprocessor examination:

  • Write a short note on the basic functions of the control system.
  • What are the requirements of the control system? Explain in detail.
  • State some of the benefits of mechatronics?
  • With the help of the structure of a programmable logic controller, explain the function of each block.
  • Write a short note on the operation of a linear variable differential transducer.
  • Define the position sensors.

Conclusion

The article on Mechatronics and Microprocessor Vtu Notes Pdf provides students with the most credible and reliable sources of reference and study material. The list of all the important notes and study materials pdf, reference books, and important questions on Mechatronics And Microprocessor Vtu Notes Pdf enlisted is to improve and enhance the knowledge of students. Students should remain updated during their preparation for their Mechatronics And Microprocessor examination. Candidates should refer to the latest notes, and study material pdf, reference sources like textbooks, update curriculum and practice the important questions from this article Mechatronics And Microprocessor Vtu Notes Pdf.

MYSQL Interview Questions for Freshers

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

MYSQL Interview Questions for Freshers

Question 1.
What is c#?
Answer:
C# is an object-oriented, type-safe, and managed language that is compiled by the .Net framework to generate Microsoft Intermediate Language.

Question 2.
Explain types of comments in C# with examples
Answer:

Single line 


Example:


//This is a single line comment


ii. Multiple line (/* */)


Example:


/*This is a multiple line comment


We are in line 2


Last line of comment*/


iii. XML Comments (///).


Eg: 


/// summary;


/// Set error message for multilingual language.


/// summary

Question 3.
Can multiple catch blocks be executed?
Answer:
No, Multiple catch blocks can’t be executed. Once the proper catch code is executed, the control is transferred to the final block, and then the code that follows the final block gets executed.

Question 4.
What is the difference between public, static, and void?
Answer:
Public declared variables or methods are accessible anywhere in the application. Static declared variables or methods are globally accessible without creating an instance of the class. Static members are by default not globally accessible it depends upon the type of access modified used. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created. And Void is a type modifier that states that the method or variable does not return any value.

Question 5.
What is an object?
Answer:
An object is an instance of a class through which we access the methods of that class. The “New” keyword is used to create an object. A class that creates an object in memory will contain information about the methods, variables, and behavior of that class.

Question 6.
What is a Class?
Answer:
A Class is an encapsulation of properties and methods that are used to represent a real¬time entity. It is a data structure that brings all the instances together in a single unit.

Question 7.
Define Constructors.
Answer:
A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

Question 8.
What is the difference between ref & out parameters?
Answer:
An argument passed as ref must be initialized before passing to the method whereas out parameter needs not be initialized before passing to a method.

Question 9.
What is the use of the ‘using’ statement in C#?
Answer:
The ‘using’ block is used to obtain a resource and process it is then automatically disposed of when the execution of the block is completed.

Question 10.
Can we use the “this” command within a static method?
Answer:
We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

Question 11.
What is the difference between constants and read-only?
Answer:
Constant variables are declared and initialized at compile time. The value can’t be changed afterward. Read-only is used only when we want to assign the value at run time.

Question 12.
What is an interface class? Give one example of it
Answer:
An Interface is an abstract class that has only public abstract methods, and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.

using System;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;
namespace DemoApplication 
{
interface Guru99lnterface
{
void SetTutorial(int pID, string pName);
String GetTutorial( );
}
class Guru99Tutorial: Guru99lnterface
{
protected int TutoriallD;
protected string TutorialName;

public void SetTutorial(int pID, string pName)
{
TutoriallD = pID;
TutorialName = pName;
}

public String GetTutorial( )
{
return TutorialName;
}
static void Main(string[ ] args)
{
Guru99Tutorial pTutor = new Guru99Tutorial( );

pTutor.SetTutorial(l,".Net by Guru99");

Console. WriteLine(pTutor.GetTutorial());

Console.ReadKey( );
}
}
}

Question 13.
The basis of comparison Between C# Interface vs Abstract Class C# Interface
Answer:
Access Specifier: In C#, Interface cannot have an access specifier for functions. It is public by default.
Implementation: In C#, an interface can only have a signature, not the implementation.
Speed: Interface is comparatively slow.
Instantiate: Interface is absolutely abstract and cannot be instantiated.
Fields: Interface cannot have fields.
Methods: Methods

C# Abstract Class

Access Specifier: In C#, an abstract class can have an access specifier for functions.
Implementation: An abstract class can provide a complete implementation.
Speed: An abstract class is fast.
Instantiate: An abstract class cannot be instantiated.
Fields: An abstract class can have defined fields and constants Methods: An abstract class can have non-abstract methods.
Basic Difference: Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.

Question 14.
What are value types and reference types?
Answer:
A value type holds a data value within its own memory space. Example

int a = 30;

Reference type stores the address of the object where the value is being stored. It is a pointer to another memory location.

string b = “Hello Guru99!l”;

Question 15.
What are Custom Control and User Control?
Answer:
Custom Controls are controls generated as compiled code (Dlls), those are easier to use and can be added to the toolbox. Developers can drag and drop controls to their web forms. Attributes can, at design time. We can easily add custom controls to Multiple Applications (If Shared Dlls). So, If they are private, then we can copy to dll to the bin directory of the web application and then add references and can use them.

User Controls are very much similar to ASP include files, and are easy to create. User controls can’t be placed in the toolbox and dragged – dropped from it. They have their design and code behind them. The file extension for user controls is ascx.

Question 16.
What are sealed classes in C#?
Answer:
We create sealed classes when we want to restrict the class to be inherited. The sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as a base class, then a compile-time error occurs.

Question 17.
What is method overloading?
Answer:
Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoked.

Question 18.
What is an Array? Give the syntax for a single and multi-dimensional array?
Answer:
An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.

For Example:

double numbers = new double[10];
int[] score = new int[4] {25,24,23,25};

A single-dimensional array is a linear array where the variables are stored in a single row. The above example is a single-dimensional array.
Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.

For Example. int[,] numbers = new int[3,2] {{1,2} ,{2,3},{3,4}};

Question 19.
Name some properties of Array.
Answer:

Properties of an Array include:

  • Length – Gets the total number of elements in an array.
  • IsFixedSize – Tells whether the array is fixed in size or not.
  • IsReadOnly – Tells whether the array is read-only or not.

Question 20.
What is an Array Class?
Answer:
An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace System.

Question 21.
What is the difference between Array and Arraylist?
Answer:
In an array, we can have items of the same type only. The size of the array is fixed when compared. An ArrayList is similar to an array, but it doesn’t have a fixed size.

Question 22.
What are Jagged Arrays?
Answer:
The Array which has elements of type array is called a jagged array. The elements can be of different dimensions and sizes. We can also call a jagged Array an Array of arrays.

Question 23.
Can a private virtual method be overridden?
Answer:
No, because they are not accessible outside the class.

Question 24.
Describe the accessibility modifier “protected internal”.
Answer:
Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived from this parent class.

Question 25.
What are the differences between System. String and System.Text.StringBuilder classes?
Answer:
System. The string is immutable. When we modify the value of a string variable, then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have a concept of a mutable string where a variety of operations can be performed without allocating separate memory locations for the modified string.

Question 26.
What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
Answer:
Using Clone() method, we create a new array object containing all the elements in the original Array and using the CopyToQ method. All the elements of the existing array copy into another existing array. Both methods perform a shallow copy.

Question 27.
How can we sort the elements of the Array in descending order?
Answer:
Using Sort( ) methods followed by reverse( )  method.

Question 28.
Write down the C# syntax to catch an exception ‘
Answer:
To catch an exception, we use try-catch blocks. Catch block can have a parameter of system. Exception type.

Eg:
try {
GetAllData( );
}
catch (Exception ex) {
}

In the above example, we can omit the parameter from the catch statement.

Question 29.
What is the difference between Finalize!) and Dispose!) methods?
Answer:
Dispose( ) is called when we want an object to release any unmanaged resources with them. On the other hand, Finalize!) is used for the same purpose, but it doesn’t assure the garbage collection of an object.

Dispose

It is used to free unmanaged resources at any time.
It is called by user code and the class which is implementing dispose method must have to implement an IDisposable interface.
It is implemented by implementing the IDisposable interface Dispose ( ) method.
There are no performance costs associated with Dispose method.

Finalize

It can be used to free unmanaged resources held by an object before that object is destroyed.
It is called by Garbage Collector and cannot be called by user code.
It is implemented with the help of Destructors
There are performance costs associated with Finalize method since it doesn’t clean the memory immediately and is called by GC automatically.

Question 30.
What are circular references?
Answer:
A circular reference is a situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.

Question 31.
What are generics in C#.NET?
Answer:
Generics are used to make reusable code classes to decrease code redundancy, increase type safety, and performance. Using generics, we can create collection classes. To create a generic collection, System.Collections.The generic namespace should be used instead of classes such as ArrayList in the System. Collections namespace. Generics promotes the usage of parameterized types.

Question 32.
What is an object pool in .NET?
Answer:
An object pool is a container having objects ready to be used. It tracks the object that is currently in use, the total number of objects in the pool. This reduces the overhead of creating and re-creating objects.

Question 33.
List down the commonly used types of exceptions in .net
Answer:
ArgumentException, ArgumentNullException, ArgumentOutOfRangeException, ArithmeticException, DivideByZeroException ,OverflowException, IndexOutOfRangeException ,lnvalidCastException JnvalidOperationException, lOEndOfStreamException , NullReferenceException , OutOfMemoryException , StackOverflowException etc.

Question 34. What are Custom Exceptions?
Answer:
Sometimes there are some errors that need to be handled as per user requirements. Custom exceptions are used for them and are used as defined exceptions.

Question 35.
What is a Delegate? Explain.
Answer:
A Delegate is a variable that holds the reference to a method. Hence it is a function pointer or reference type. All Delegates are derived from System. Delegate namespace. Both Delegate and the method that it refers to can have the same signature.
Declaring a delegate: public delegate void AddNumbers(int n);
After the declaration of a delegate, the object must be created of the delegate using the new keyword.
AddNumbers aril = new AddNumbers(number);
The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.

1 public delegate int myDel(int number);
2 public class Program
3 {
4 public int AddNumbers(int a)
5{ 
6 int Sum = a + 10;
7 return Sum;
8}
9 public void Start( )
10 {
11 myDel DelgateExample = AddNumbers;
12}
13}

In the above example, we have a delegate myDel which takes an integer value as a parameter. Class Program has a method of the same signature as the delegate, called AddNumbers( ).

If there is another method called Start( ) that creates an object of the delegate, then the object can be assigned to AddNumbers as it has the same signature as that of the delegate.

Question 36.
What are Events?
Answer:
Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress, and so on.

Programmatically, a class that raises an event is called a publisher and a class that responds/receives the event is called a subscriber. An event should have at least one subscriber else that event is never raised.

Delegates are used to declare Events.

Public delegate void PrintNumbers( );

Event PrintNumbers myEvent;

Question 37.
How to use Delegates with Events?
Answer:
Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.

Let us see an example:

Consider a class called Patient. Consider two other classes, Insurance, and Bank which requires Death information of the Patient from the patient class. Here, Insurance and Bank are the subscribers and the Patient class becomes the Publisher. It triggers the death event and the other two classes should receive the event.

1 namespace ConsoleApp2
2{
3 public class Patient
4{
5 public delegate void deathlnfo( );//Declaring a Delegate//
public event deathlnfo deathDate;//Declaring the
6
event//
7 public void Death( )
8{
9 deathDate();
10}
11} 
12 public class Insurance
13 {
14 Patient myPat = new Patient();
15 void GetDeathDetails( )
16 {
17 //----------Do Something with the deathDate event----------//
18}
19 void Main( )
21 //--------Subscribe the function GetDeathDetails----------//
22 myPat.deathDate += GetDeathDetails;
23}
24}
25 public class Bank
26 {
27 Patient myPat = new Patient( );
28 void GetPatlnfo ( )
29 {
30 //--------Do Something with the deathDate event--------//
31}
32 void Main( )
33 {
34 //--------Subscribe the function GetPatlnfo----------//
35 myPat.deathDate += GetPatlnfo;
36}
37}
38}

Question 38.
What are the different types of Delegates?
Answer:
The Different Types of Delegates are:

Single Delegate – A delegate which can call a single method.
Multicast Delegate – A delegate which can call multiple methods. + and – operators are used to subscribing and unsubscribing respectively.
Generic Delegate – It does not require an instance of the delegate to be defined. It is of three types, Action, Funcs, and Predicate.

  • Action- In the above example of delegates and events, we can replace the definition of delegate and event using the Action keyword. The Action delegate defines a method that can be called on arguments but does not return a result
Public delegate void deathlnfo( );

Public event deathlnfo deathDate;

//Replacing with Action//

Public event Action deathDate;

Action implicitly refers to a delegate.
  • Func- A Func delegate defines a method that can be called on arguments and returns a result.
    Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);
  • Predicate – Defines a method that can be called on arguments and always returns the bool.
    Predicate<string> myDel is same as delegate bool myDelfstring s);

Question 39.
What’s a multicast delegate?
Answer:
A delegate having multiple handlers assigned to it is called a multicast delegate. Each handler is assigned to a method. In other words
A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using the + and += operators.

Consider the Example from previous delegate question

There are two subscribers for death event, GetPatlnfo, and GetDeathDetails. And hence we have used += operator. It means whenever the myDel is called, both the subscribers get called. The delegates will be called in the order in which they are added.

Question 40.
Explain Publishers and Subscribers in Events.
Answer:
A Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but an Event as discussed in the above questions.

From the Example in Question 32, Class Patient is the Publisher class. It is generating an Event death event, which the other classes receive.

Subscribers capture the message of the type that it is interested in. Again, from the Example of Question 32, Class Insurance and Bank are Subscribers. They are interested in event death event of type void.

Question 41.
How do you inherit a class into another class in C#?
Answer:
Colon is used as an inheritance operator in C#. Just place a colon and then the class name, public class DerivedClass: BaseClass

Question 42.
What is the base class in .net from which all the classes are derived from?
Answer:
System.Object

Question 43.
What is the difference between method overriding and method overloading?
Answer:
In method overriding, we change the method definition in the derived class that changes the method behavior. Method overloading is creating a method with the same name within the same class having different signatures.

Question 44.
What are the different ways a method can be overloaded?
Answer:
Methods can be overloaded using different data types for a parameter, different order of parameters, and different numbers of parameters.

Question 45.
Why can’t you specify the accessibility modifier for methods inside the interface?
Answer:
In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That’s why they all are public.

Question 46.
How can we set the class to be inherited, but prevent the method from being over-ridden?
Answer:
Declare the class as public and make the method sealed to prevent it from being overridden.

Question 47.
What happens if the inherited interfaces have conflicting method names?
Answer:
The implement is up to you as the method is inside your own class. There might be a problem when the methods from different interfaces expect different data, but as far as the compiler cares you’re okay.

Question 48.
What is the difference between a Struct and a Class?
Answer:
Structs are value-type variables, and classes are reference types. Structs stored on the Stack cause additional overhead but faster retrieval. Structs cannot be inherited.

Class

Supports Inheritance
Class is Pass by reference (reference type)
Members are private by default
Good for larger complex objects
Can use waste collector for memory management

Struct

Does not support Inheritance
Struct is Pass by Copy (Value type)
Members are public by default
Good for Small isolated models
Cannot use Garbage collector and hence no Memory management

Question 49.
How to use nullable types in .Net?
Answer:
Value types can take either their normal values or a null value. Such types are called nullable types.

Int? somelD = null;
If(somelD.HasVAIue)
{
}

Question 50.
How we can create an array with non-default values?
Answer:
We can create an array with non-default values using Enumerable. Repeat.

Question 51.
What is the difference between “is” and “as” operators in c#?
Answer:
“is” operator is used to checking the compatibility of an object with a given type, and it returns the result as Boolean.
“as” operator is used for casting an object to a type or a class.

Question 52.
What are indexers in C# .NET?
Answer:
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the same way as an array.
Eg:
public int this[int index] // Indexer declaration

Question 53.
What is the difference between the “throw” and “throw ex” in .NET?
Answer:
The “Throw” statement preserves the original error stack whereas “throw ex” has the stack trace from their throw point. It is always advised to use “throw” because it provides more accurate error information.

Question 54.
What are C# attributes and their significance?
Answer:
C# provides developers a way to define declarative tags on certain entities, eg. Class, method, etc. are called attributes. The attribute’s information can be retrieved at runtime using Reflection.

Question 55.
How to implement a singleton design pattern in C#?
Answer:
In a singleton pattern, a class can only have one instance and provides an access point to it globally.

Eg:

Public sealed class Singleton

{

Private static readonly Singleton Jnstance = new Singleton();

}

Question 56.
What is the difference between direct cast and type?
Answer:
DirectCast is used to convert the type of object that requires the run-time type to be the same as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and the type.

Question 57.
What is Managed and Unmanaged code?
Answer:
Ans: Managed code is a code that is executed by CLR (Common Language Runtime) i.e all application code based on .Net Platform. It is considered as managed because of the
.Net framework which internally uses the garbage collector to clear up the unused memory.

Unmanaged code is any code that is executed by the application runtime of any other framework apart from .Net. The application runtime will take care of memory, security, and other performance operations.

Question 58.
Is C# code is managed or unmanaged code?
Answer:
C# is managed code because Common language runtime can compile C# code to Intermediate language.

Question 59.
What is a Console application?
Answer:
A console application is an application that can be run in the command prompt in Windows. For any beginner on .Net, building a console application is ideally the first step, to begin with.

Question 60.
Give an example of removing an element from the queue
Answer:
The dequeue method is used to remove an element from the queue,

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
class Program
{
static void Main(string[ ] args)
{
Queue qt = new Queue( );
qt.Enqueue(1);
qt.Enqueue(2);
qt.Enqueue(3);

foreach (Object obj in qt)
{
Console.WriteLine(obj);
}
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("The number of elements in the Queue " + qt.Count);
Console.WriteLine("Does the Queue contain " + qt.Contains(3));
Console.ReadKey( );
}
}
}

Question 61.
What are the fundamental OOP concepts?
Answer:
The four fundamental concepts of Object-Oriented Programming are:
• Encapsulation – The Internal representation of an object is hidden from the view outside the object’s definition. Only the required information can be accessed whereas the rest of the data implementation is hidden.
• Abstraction – It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details.
• Inheritance – It is the ability to create new classes from another class. It is done by accessing, modifying, and extending the behavior of objects in the parent class.
• Polymorphism – The name means, one name, many forms. It is achieved by having multiple methods with the same name but different implementations.

Question 62.
What are the different types of classes in C#?
Answer:
The different types of classes in C# are:

• Partial class – Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.

• Sealed class – It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword Sealed.

• Abstract class – It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword abstract.

• Static class – It is a class that does not allow inheritance. The members of the class are also static. It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.

Question 63.
Explain Code compilation in C#.
Answer:
There are four steps in code compilation which include:

  • Compiling the source code into Managed code by C# compiler.
  • Combining the newly created code into assemblies.
  • Loading the Common Language Runtime(CLR).
  • Executing the assembly by CLR.

Question 64.
What is the difference between the Virtual method and the Abstract method?
Answer:
A Virtual method must always have a default implementation. However, it can be overridden in the derived class, though not mandatory. It can be overridden using override keyword.

An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.

Question 65.
Explain Namespaces in C#.
Answer:
They are used to organize large code projects. “System” is the most widely used namespace in C#. We can create our own namespace and use one namespace in another, which are called Nested Namespaces.
They are denoted by the keyword “namespace”.

Question 66.
Explain Abstraction.
Answer:
Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hides unnecessary information.

Let us take an example of a Car:

A driver of the car should know the details about the Car such as color, name, mirror, steering, gear, brake, etc. What he doesn’t have to know is an Internal engine, Exhaust system.

So, Abstraction helps in knowing what is necessary and hiding the internal details from the outside world. Hiding of the internal information can be achieved by declaring such parameters as Private using tire private keyword.

Question 67.
Explain Polymorphism?
Answer:
Programmatically, Polymorphism means the same method but different implementations. It is of 2 types, Compile-time and Runtime.

Compile-time polymorphism is achieved by operator overloading.

Runtime polymorphism is achieved by overriding. Inheritance and Virtual functions are used during Runtime Polymorphism.

For Example. If a class has a method Void Add(), polymorphism is achieved by Overloading the method, that is, void Add(int a, int b), void Add(int add) are all overloaded methods.

Question 68.
What are C# I/O Classes? What are the commonly used I/O Classes?
Answer:
C# has System.10 namespace, consisting of classes that are used to perform various operations on files like creating, deleting, opening, closing, etc.

Some commonly used I/O classes are:

  • File – Helps in manipulating a file.
  • StreamWriter – Used for writing characters to a stream.
  • StreamReader – Used for reading characters to a stream.
  • StringWriter – Used for reading a string buffer.
  • StringReader – Used for writing a string buffer.
  • Path – Used for performing operations related to the path information.

Question 69.
What is the StreamReader/StreamWriter class?
Answer:
StreamReader and StreamWriter are classes of namespace System.10. They are used when we want to read or write charact90, Reader-based data, respectively.

Some of the members of StreamReader are: Close( ), Read( ), Readline( ).

Members of StreamWriter are: Close( ), Write( ), Writeline( ).

1 Class Programl
2{
3 using(StreamReader sr = new StreamReader(“C:\ReadMe.txt”)
4{
5 //——–code to read———//
6}
7 using(StreamWriter sw = new StreamWriter(“C:\ReadMe.txt”))
8{
9 //———Code to write——-//
10}
11}

Question 70.
What is a Destructor in C#?
Answer:
A Destructor is used to clean up the memory and free tire resources. But in C# this is done by the garbage collector on its own. System.GC.Collect( ) is called internally for cleaning up. But sometimes it may be necessary to implement destructors manually.
For Example:

~Car( )

{

Console.writeline("....");

}

Question 71.
What are Boxing and Unboxing?
Answer:
Converting a value type to reference type is called Boxing.

For Example:

int Valuel -= 10;
//——Boxing——–//
object boxedValue = Valuel;

Explicit conversion of the same reference type (created by boxing) back to value type is called Unboxing.

For Example:

//——-UnBoxing——–//
int UnBoxing = int (boxed value);

Question 72.
What is the difference between Continue and Break Statement?
Answer:
Break statement breaks the loop. It makes the control of the program exit the loop. Continue statement makes the control of the program exit only the current iteration. It does not break the loop.

Question 73.
What is the difference between the final and finalize blocks?
Answer:
finally block is called after the execution of try and catch block. It is used for exception handling. Regardless of whether an exception is caught or not, this block of code will be executed. Usually, this block will have a clean-up code.

finalize method is called just before garbage collection. It is used to perform clean-up operations of Unmanaged code. It is automatically called when a given instance is not subsequently called.

Question 74.
What is a String? What are the properties of a String Class?
Answer:
A String is a collection of char objects. We can also declare string variables in c#.

string name = “C# Questions”;

A string class in C# represents a string.

The properties of the String class are Chars and Length.
Chars get the Char object in the current String.
Length gets the number of objects in the current String.

Question 75.
What is an Escape Sequence? Name some String escape sequences in C#.
Answer:
An Escape sequence is denoted by a backslash (\). The backslash indicates that the character that follows it should be interpreted literally or it is a special character. An escape sequence is considered a single character.

String escape sequences are as follows:

\n – Newline character
\b- Backspace
\\- Backslash
\’ – Single quote
\” – Double Quote

Question 76.
What are Regular expressions? Search a string using regular expressions?
Answer:
Ans: Regular expression is a template to match a set of input. The pattern can consist of operators, constructs, or character literals. Regex is used for string parsing and replacing the character string.

For Example:

* matches the preceding character zero or more times. So, a*b regex is equivalent to b, ab, aab, aaab, and so on.

Searching a string using Regex
1 static void Main(string[ ] args)
2{
3 string}] languages = {"C#", "Python", "Java" };
4 foreach(string s in languages)
5{
6 if(System.Text.RegularExpressions.Regex.lsMatch(s,"Python"))
7{
8 Console.WriteLine("Match found");
9 }
10}
11}

The above example searches for “Python” against the set of inputs from the languages array. It uses Regex.IsMatch returns true in case if the pattern is found in the input. The pattern can be any regular expression representing the input that we want to match.

Question 77.
What are the basic String Operations? Explain.
Answer:
Some of the basic string operations are:

• Concatenate –Two strings can be concatenated either by using a System.String.Concat or by using + operator.
• Modify – Replace(a,b) is used to replace a string with another string. Trim( ) is used to trim the string at the end or at the beginning.
• Compare – System.StringComparison() is used to compare two strings, either a case-sensitive comparison or not case sensitive. Mainly takes two parameters, original string, and string to be compared with.
• Search – start with, EndsWith methods are used to search a particular string.

Question 78.
What is Parsing? How to Parse a Date Time String?
Answer:
Parsing is converting a string into another data type.

For Example:

string text = “500”; int num = int.Parse(text);
500 is an integer. So, Parse method converts the string 500 into its own base type, i.e int.

Follow the same method to convert a DateTime string.
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);

Question 79.
What are Synchronous and Asynchronous operations?
Answer:
Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time.
The asynchronous call waits for the method to complete before continuing with the program flow. Synchronous programming badly affects the Ul operations, when the user tries to perform time-consuming operations since only one thread will be used.
In Asynchronous operation, the method call will immediately return so that the program can perform other operations while the called method completes its work in certain situations.

Question 80.
What is Reflection in C#?
Answer:
Reflection is the ability of a code to access the metadata of the assembly during runtime. A program reflects upon itself and uses the metadata to inform the user or modify its behavior. Metadata refers to information about objects, methods.

The namespace System. Reflection contains methods and classes that manage the information of all the loaded types and methods. It is mainly used for windows applications, for example, to view the properties of a button in a windows form.
The Memberlnfo object of the class reflection is used to discover the attributes associated with a class.

Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as methods and properties.

To get the type of a class, we can simply use
Type my type = myClass.GetType( );
Once we have a type of class, the other information of the class can be easily accessed.
System.Reflection.Memberlnfo Info = mytype.GetMethod(“AddNumbers”);
Above statement tries to find a method with name AddNumbers in the class myClass.

Question 81.
Explain Get and Set Accessor properties?
Answer:
Get and Set are called Accessors. These are made use by Properties. The property provides a mechanism to read, write the value of a private field. For accessing that private field, these accessors are used.
Get Property is used to return the value of a property Set Property accessor is used to set the value.

Question 82.
What is a Thread? What is Multithreading?
Answer:
A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing. Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be created to execute the code in parallel with the original thread.

Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System. Threading is the namespace that needs to be included to create threads and use its members.

Threads are created by extending the Thread class. Start( ) method is used to begin thread execution.

//CallThread is the target method//

ThreadStart methodThread = newThreadStart(CallThread);

Thread childThread = new Thread(methodThread);

childThread.Start( );

C# can execute more than one task at a time. This is done by handling different processes by different threads. This is called MultiThreading.

There are several thread methods that are used to handle the multi-threaded operations:

Start, Sleep, Abort, Suspend, Resume and Join.

Most of these methods are self-explanatory.

Question 83.
Name some properties of Thread Class.
Answer:
Few Properties of thread class are:

  • IsAlive-contains value True when a thread is Active.
  • Wame – Can return the name of the thread. Also, can set a name for the thread.
  • Priority – returns the prioritized value of the task set by the operating system.
  • background – gets or sets a value that indicates whether a thread should be a background process or foreground.
  • ThreadState- describes the thread state.

Question 84.
What are the different states of a Thread?
Answer:
Different states of a thread are:

  • Unstarted – Thread is created.
  • Running- Thread starts execution.
  • WaitSleepJoin – Thread calls sleep, calls wait on another object and calls join on another thread.
  • Suspended – The thread has been suspended.
  • Aborted – Thread is dead but not changed to state stopped.
  • Stopped – Thread has stopped.

Question 85.
What are Async and Await?
Answer:
Async and Await keywords are used to create asynchronous methods in C.
Asynchronous programming means that the process runs independently of main or other processes.

  • Async keyword is used for the method declaration.
  • The count is of a task of type int which calls the method CalculateCount( ).
  • Calculatecount( ) starts execution and calculates something.
  • Independent work is done on my thread and then await count statement is reached.
  • If the Calculatecount is not finished, my method will return to its calling method, thus the main thread doesn’t get blocked.
  • If the Calculatecount is already finished, then we have the result available when the control reaches await count. So the next step will continue in the same thread. However, it is not the situation in the above case where a Delay of 1 second is involved.

Question 86.
What is a Deadlock?
Answer:
A Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for each other to finish. This usually occurs in multi-threading.

Here a Shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding the locked item is waiting for another process to complete.

Question 87.
Explain lock, Monitors, and Mutex Objects in Threading.
Answer:
Lock keyword ensures that only one thread can enter a particular section of the code at any given time. In the above Example, lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.

A Mutex is also like a lock but it can work across multiple processes at a time. WaitOne( ) is used to lock and ReleaseMutex( ) is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.

Monitor.Enter and Monitor. Exit implements lock internally, a lock is a shortcut for Monitors. lock(objA) internally calls.

Monitor. Enter(ObjA); try
{ 
}
Finally {Monitor.Exit(ObjA));}

Question 88.
What is a Race Condition?
Answer:
A Race condition occurs when two threads access the same resource and are trying to change it at the same time. The thread which will be able to access the resource first cannot be predicted.
If we have two threads, T1 and T2, and they are trying to access a shared resource called X., And if both the threads try to write a value to X, the last value written to X will be saved.

Question 89.
What is Thread Pooling?
Answer:
A Thread pool is a collection of threads. These threads can be used to perform tasks without disturbing the primary thread. Once the thread completes the task, the thread returns to the pool.

System.Threading.ThreadPool namespace has classes that manage the threads in the pool and its operations.

System.Threading.ThreadPool.QueuellserWorkltem(new
System.Threading.WaitCallback(SomeTask));

The above line queues a task. SomeTask methods should have a parameter of type Object.

Question 90.
What is Serialization?
Answer:
When we want to transport an object through a network, then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should implement ISerialize Interface. De-serialization is the reverse process of creating an object from a stream of bytes.

Another Explanation for this

Serialization is the process of converting a code to its binary format. Once it is converted to bytes, it can be easily stored and written to a disk or any such storage device. Serializations are mainly useful when we do not want to lose the original form of the code and it can be retrieved anytime in the future.

Any class which is marked with the attribute [Serializable] will be converted to its binary form.

The reverse process of getting the c# code back from the binary form is called Deserialization.

To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.

Question 91.
What are the types of Serialization?
Answer:
The different types of Serialization are XML serialization, SOAP, and Binary.

• XML serialization – It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.

• SOAP – Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that can be used by any system that understands SOAP.

• Binary Serialization – Allows any code to be converted to its binary form. Can serialize and restore public and non-public properties. It is faster and occupies less space.

Question 92.
What is an XSD file?
Answer:
An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have any tags, any attributes, and any elements.

Xsd.exe tool converts the files to XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.

 

OOPS and Core Java Interview Questions in Java

We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.

Java J2EE Interview Questions on OOPS and Core Java

Question 1.
Discuss the significance of the Java language.
Answer:
Java is the preeminent language of the Internet. Apart from this, many of its features are influencing upcoming languages such as C#. Java not only opened the door to immense possibilities on the Internet but is inherently suitable for administrative data processing (via database processing), for development using client/server architectures as well as for something it was tailor-made: industrial and loaded data processing.

Without any doubt, we can say that Java shall remain a popular programming language for many future years to come.

Question 2.
Elaborate briefly upon the evolution of Java.
Answer:
A research team at Sun Microsystems was working on the development of home automation applications that could be integrated into cellular telephones and real-time portable systems all of which were developed using C++. This type of development imposed certain restrictions due to the different hardware architectures, interconnection problems between different machines, etc. C++ was not particularly suitable for this kind of development as it is greedy on memory, lacks portability across processes, and pointer management risks the deletion of data vital to the operation of the application.

Given such problems, one of the team members, namely James Gosling endeavored to write a new programming language. Given its application domain, this language needed to be object-oriented, high performance-oriented, fast, and such to ensure portability between different types of hardware. At first, it was called C++–, then Oak, and finally Java – a slang term for “coffee” – due to the amount of coffee consumed by the developers.

Question 3.
Compare in brief C/C++, C#, and Java.
Answer:
Java derives its syntax from C. Many of the object-oriented features of Java were strongly influenced by C++. But, it would be improper to consider Java as the “Internet version of C++”. C# and Java are similar in the sense that they both share the same C++ syntax, support distributed programming, and both make use of the same object model. But, in spite of this, there are stark differences between the two.

We have already stated that Java is closely related to both C and C++, deriving its syntax from C and the object-oriented features from C++. Now, we shall see in what ways it differs from them in terms of programming.

Differences between Java & C:

  • Java does not have the C keywords: size, typedef, auto, extern, register, signed, unsigned.
  • Java adds new operators such as instanceof and >>> (unsigned right shift).
  • Java adds labeled break and continues statements.
  • Java does not support the data types struct and union.
  • Java does not have an explicit pointer type.
  • Java does not have a preprocessor and thus, does not support any preprocessor directive such as Refine, #include, #ifdef, etc.

Differences between Java & C++:

  • Java does not support operator overloading.
  • Java does not allow default arguments.
  • Java does not support multiple inheritances.
  • Although Java supports constructors, it does not have destructors. Instead, it has a finalize( ) function.
  • Java does not allow the goto.
  • Java does not have the delete operator.
  • Java does not support global variables/functions as all the code in a Java program is encapsulated within one or more classes.
  • The << and >> in Java are not overloaded for I/O operations.
  • In Java, objects are passed by reference only. In C++, they could be passed by reference as well as by value.
  • Java adds multithreading, packages, interfaces, a third comment type: the documentation comment that begins with /** and ends with */, and a built-in string type called String.
  • Java does not have C++ type libraries but has its own set of API (Application Program Interface) classes.
  • While both Java and C++ support a boolean data type, their implementation is different.
  • In C++, a nonzero value is true while a zero value is false. But, in Java, true and false are treated as predefined literals.
  • In a C++ class, the access operators apply to a group of statements while in Java, they apply only to the declarations they immediately precede.
  • Both Java and C++ support exception handling. But, in C++, there is no particular requirement that a thrown exception be necessarily caught as is the case in Java.

Question 4.
Elaborate on the main features of Java.
Answer:
Some of the main features of Java include the following:-

  • Simple and secure
  • Portable and architecture-neutral
  • Object-oriented
  • Robust and multithreaded
  • Interpreted and high performance
  • Distributed and dynamic

Question 5.
Name and enumerate the three Object-Oriented Programming (OOP) principles.
Answer:
The three object-oriented programmings (OOP) principles are:-

  • Encapsulation
  • Inheritance
  • Polymorphism

These three principles work together in unison.

Question 6.
Distinguish between “call-by-value” and “call-by-reference”.
Answer:
There are, in general, two ways that a computer language can pass an argument to a subroutine. The first way is referred to as “call-by-value” while the second is known as “call-by-reference”. In “call-by-value”, the method copies the value of an argument into the formal parameter of the subroutine, and whence, changes made to the parameter of the subroutine have no effect on the argument. In contrast to this, a reference to an argument, and, not the value of the argument is passed to the parameter in the “call-by-reference” approach. Inside the subroutine, this reference is then used to access the actual argument specified in the call so that changes made to the parameter will affect the argument used to call the subroutine.

In Java, when a simple type is passed to a method, it is done through “call-by-value” whereas objects are passed through “call-by-reference”.

Question 7.
What is recursion? Does Java support recursion?
Answer:
Recursion is the process of defining something in terms of itself. Java does support recursion as it allows a method to call itself. Such a method is said to be recursive. A classic case of recursion is computing the factorial of a number.

Question 8.
How can you determine the size of an array?
Answer:
The size of an array, that is to say, the number of elements it can hold is found in its length instance variable.

Question 9.
How are command-line arguments passed in Java?
Answer:
In Java, all command-line arguments are passed as strings only. If you wish to pass numeric values, they must be converted to their internal forms manually.

Question 10.
What is the difference between the prefix increment ++x and the postfix increment x++?
Answer:
The statement:-
y = y + x++;
adds the current values of x and y and assigns this result back to y. The value of x is only incremented after the value of y has been thus obtained.
On the other hand, the statement:-
y = y + ++x;
obtains the value of x, increments x, then adds that value to the current value of y, and this result is assigned to y.

You can see for yourself (by assigning some initial values to x and y) that simply changing ++x to x++ changes the results quite substantially when both of the above statements are run over a loop.

Question 11.
What is the use of short-circuit logical operators | | OR and && AND?
Answer:
Contrary to the normal counterparts | and &, the short. circuit operators | | and && evaluate the second operand only when necessary. That is to say, the result of the OR operation will always be true if the first operand is true irrespective of the second operand. Similarly, the result of the AND operation will always be false if the first operand is false irrespective of the second operand. In both these cases, | | and && do not evaluate the second operand unlike their normal counterparts I and &, which evaluate both the operands in all situations.

Question 12.
Can you name an operator in Java that takes three operands?
Answer:
The ternary operator with the most general form:-
exp1? exp2: exp3;

(if exp1 is true, exp2 becomes the value of the whole expression else exp3 becomes the value of the whole expression)

Question 13.
Can you create a ‘for’ loop without any conditional expressions? What does it amount to?
Answer:
Leaving the conditional expressions in a ‘for’ loop makes it an infinite loop that will run forever:-
for ( ; ; ) / / intentional infinite loop
{
……………….
………………
}

Question 14.
Can Objects be passed as parameters just like simple types?
Answer:
Yes! The answer to this query is in the affirmative.

Question 15.
What do the break and continue statements do? Bring out the main point of difference between them.
Answer:
The break statement causes early termination of the loop whereas the continue statement causes an early iteration of the loop.

Question 16.
Explain the use of the keyword new.
Answer:
The keyword new is used to create objects, e.g.
House building = new House ( );
Here, building by itself does not contain the object (House). Rather, it contains a reference to it.
On the other hand, consider:
int i = 100;
Here, i contains the value 100 since i is a variable of type int, which, in turn, is a value type.
Again, consider:
douse building1 = new House ( );
House building2 = new House ( );
building2 = building1;
House building3 = new House ( );
‘building2 = building3;

After the execution of this sequence, building2 refers to the same object (House) as building3. The object (House) referred to by building1 is unchanged.

Question 17.
What are the two uses of the keyword super?
Answer:

  • A subclass can call a constructor defined in its superclass by using the keyword super.
  • The second use of super relates to situations in which member names of a subclass hide members by the same name in the superclass. In such a case, you can refer to the superclass member by using super. member.

Question 18.
Point out the difference between C++ and Java as regards the release of previously allocated memory.
Answer:
In C++, the delete operator is used to free memory that was previously allocated. But, Java uses a different, more trouble-free approach, viz. garbage collection.

Question 19.
What is the purpose of the finalize( ) method in Java?
Answer:
We can define a method in Java that shall be called just prior to the object’s final destruction by the garbage collector. This method is known as the finalize( ) method, which can be used in some highly specialized situations to ensure that the object is destroyed/terminated cleanly.

Question 20.
What do you understand by ‘this’?
Answer:
When a method is called, it is, by itself, passed a reference to the invoking object, i.e. the object on which the method is called. This reference is referred to as ‘this’.

Question 21.
Can you elaborate on the concept of jagged arrays?
Answer:
In general, when we create a two-dimensional array, we are creating what is a rectangular array with the length of each row being the same for the entire array, e.g. a 2 x 3 array implies an array of two rows with three elements in each row. But, Java allows you to create a special two-dimensional array called a jagged array, which is an array of arrays, where the length of each array can differ. In this way, we can have a table where the lengths of the rows differ, e.g.

int jag [ ] [ ] = new int [4] [ ];
jag [0] = new int [10];  / / length of first array is ten
jag [1] = new int [2];   / / length of second array is two
jag [2] = new int [5];  / / length of third array is five
jag [3] = new int [8]; / / length of fourth array is eight

Question 22.
Can you point out the main difference between C/C++ strings and Java strings?
Answer:
In C/C++, strings are simply arrays of characters terminated by the ‘\0’ null character whereas, in Java, the string is a built-in data type. In fact, in Java, strings are objects and thus, reference types.

Question 23.
Can the contents of strings in Java be changed?
Answer:
No, strings in Java are immutable. This might seem to be a drawback but since unused string objects are automatically garbage-collected, you can simply create a new string with the desired changes. (Refer Q. 92 also)

Question 24.
What are Java’s access modifiers?
Answer:
In Java, member access control is achieved through three access modifiers, namely, public, private, and protected. The protected modifier applies only in the case of inheritance. When a member of a class is modified by the public specifier, then that member can be accessed by any code in your program. If a member of a class is specified to be private, it can then only be accessed by other members of its class so that methods in other classes will not be able to access a private member of another class.

Question 25.
Which feature of C/C++ is similar to overridden methods in Java?
Answer:
Overridden methods in Java are similar to virtual functions in C/C++.

Question 26.
Is it possible to have a variable number of arguments in Java?
Answer:
Yes, this is a recently added new feature to Java. It was added by JDK 5. The addition of this feature has enabled formatted output in Java akin to the print( ) family of functions in C.

We might also mention here that it is possible to have a normal parameter along with the variable-length parameter but in such cases, the variable-length parameter must be the last one in the method declaration. Moreover, you cannot have a method with more than one variable-length parameter.

Question 27.
Can you declare a class as both abstract and final?
Answer:
An abstract class is incomplete by itself and relies upon its subclasses to provide a complete implementation. Whence, it is illegal to declare a class as both abstract and final.

Question 28.
When do you declare an element as protected?
Answer:
In Java, if you want to allow an element to be visible outside your current package, but only to classes that subclass your class directly, then you declare that element as protected.

Question 29.
Where does the package statement occur in a Java source file?
Answer:
The package statement must be the first statement in a Java source file.

Question 30.
Where does the import statement occur in a Java source file?
Answer:
The import statement in a Java source file must occur immediately after the package statement, if any, and before any class definitions.

Question 31.
Specify the forms of the Main ( ) method available in Java.
Answer:
The following four versions of Main ( ) are currently available in Java:-

  • public static void main ( )
  • public static int main ( )
  • public static void main (String args[ ])
  • public static int main (String args[ ])

Question 32.
Elucidate the role of the keyword static.
Answer:
In general, a class member has to be accessed through an object of its instance. But, it is possible in Java to create a member that can be used by itself, without any reference to a specific instance. To create such a member, you have to precede its declaration with the keyword static.

Question 33.
Point out any four restrictions on static methods?
Answer:
First, a static method cannot have a ‘this’ reference. Second, a static method cannot refer to super in any way. Third, a static method can directly call only other static methods. Finally, a static method can have access only to static data.

Question 34.
Which feature of Java is akin to multiple inheritances in C++?
Answer:
Interfaces in Java provide most of the functionality associated with multiple inheritances in C++.

Question 35.
Can Java interfaces be inherited?
Answer:
The answer to this query is indeed in the affirmative.

Question 36.
Give a one-line definition of an exception. What do you mean by checked and unchecked exceptions?
Answer:
An exception is a run-time error. Most of the exceptions are directly available from the JVM (such as ArithmeticException, ArraylndexOutOfBoundsException, etc.) and need not be specified in the throws list of any method. All these exceptions are known as unchecked exceptions. Then, there are other exceptions such as IllegalAccessException defined by java. lang, which must be specified in the throws statement in case a method generates them but does not handle them by itself. Such exceptions are called checked exceptions.

Question 37.
Which class is at the top of the exception hierarchy?
Answer:
Throwable.

Question 38.
Which are the two important subclasses of Throwable?
Answer:
Exception and Error.

Question 39.
Can you name the all-important subclass of Exception?
Answer:
RuntimeException.

Question 40.
What is RuntimeException?
Answer:
RuntimeException is a subclass of Exception and includes such run-time programming error conditions such as divide-by-zero and invalid array index.

Question 41.
What does the throws clause do?
Answer:
A throws clause lists all the types of exceptions that a method might throw but does not handle them by itself.

Question 42.
How is java. Is lang related to exceptions?
Answer:
Inside its standard package java.lang, Java defines several exception classes. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java. lang is implicitly imported into all Java programs, most of the exceptions derived from RuntimeException are automatically available and need not be included in the throws list of any method. In terms of Java, these are known as unchecked exceptions since the Java compiler does not check to see if a method handles or throws these exceptions.

Question 43.
Can you create your own custom exceptions in Java?
Answer:
Although Java’s built-in exceptions are capable of handling the most common errors, there will still be occasions when you would like to create your own exception types specific to your applications. This is quite simply done by defining a subclass of Exception, which, in turn, is in fact a subclass of Throwable.

Question 44.
What do you understand by chained exceptions?
Answer:
Java 2, version 1.4 added the feature of chained exceptions to the exception subsystem of Java. This feature allows you to associate one exception with another where the second exception describes the cause of the first exception. For instance, take the case when an ArithmeticException occurred because of an attempt to divide by zero.

But, the actual cause of the problem was that an I/O error occurred, which caused the divisor to be set to zero. In such a scenario, the method must certainly throw an Arithmetic Exception but you also might want to let the calling code know that the underlying cause was an I/O error: chained exceptions allow you to do this and any similar situation where layers of exceptions exist, thus forming a chain.

Question 45.
Both the subclass and the superclass can have their own constructors. So, what constructor is responsible for building an object of the subclass – the one in the superclass, or the one in the subclass, or both?
Answer:
The constructor for the superclass constructs the superclass part of the object and the constructor for the subclass builds the subclass portion of the object.

Question 46.
How does a subclass call a constructor defined in its superclass?
Answer:
A subclass can call a constructor defined in its superclass by using the super keyword in the following manner-
super (Paramjit);
where Paramjit specifies any parameters required by the constructor in the superclass. Note that super must always be the first statement executed inside a subclass’ constructor.

Question 47.
In what order are constructors called in a class hierarchy?
Answer:
In a class hierarchy, constructors are called in their order of derivation, that is, from superclass to subclass.

Question 48.
What do you mean by method overriding?
Answer:
When a method in a subclass has the same name, return type, and signature as that in the superclass, it is said to override the method in the superclass and this phenomenon is referred to as method overriding in Java.

Question 49.
What do you understand by dynamic method dispatch?
Answer:
Dynamic method dispatch is the means by which a call to an overridden method is resolved at run-time rather than at compile time. It is important since Java implements run-time polymorphism this way.

Question 50.
Can you give one good reason for using overridden methods?
Answer:
Overridden methods are another way that Java implements the ‘one interface, multiple methods’ aspect of polymorphism. ’

Question 51.
Can an abstract method have a body? Can an abstract class have concrete methods (other than abstract ones)?
Answer:
While the answer to the first query is in the negative the answer to the second query is in the affirmative.

Question 52.
Can you create an object of an abstract class using new?
Answer:
An abstract class does not specify a complete implementation and whence, there can be no objects of an abstract class. Therefore, attempting to create an object of an abstract class using new will lead to a consequent compile-time error.

Question 53.
What are the three uses of the keyword final?
Answer:

  • You can use final to prevent a class from being inherited by preceding the class declaration with the keyword final.
  • You can use final to prevent further overriding of a method by preceding its declaration with the keyword final.
  • The keyword final can be used to create what is known as final named constants.

Question 54.
What do you mean or understand by type wrappers?
Answer:
In Java, simple types such as int or char are not part of the object hierarchy. They are passed by value to methods and cannot be directly passed by reference. Moreover, there is no way for two methods to refer to the same instance of an int. There will be occasions when you need to create an object representation for one of these simple types, e.g., there are the enumeration classes,

which deal only with objects, and thus, to store a simple type in one of these classes, you must wrap the simple type in a class. To take care of this need, Java provides classes that correspond to each of these simple types. These classes essentially encapsulate or wrap the simple types within a class and whence, they are commonly referred to as type wrappers.

Question 55.
What do you mean by autoboxing and auto-unboxing?
Answer:
Beginning with JDK 5, Java added two important features, namely, autoboxing and auto-unboxing. Auto-boxing is the process by which a primitive type is automatically encapsulated (“boxed”) into its equivalent type wrapper whenever an object of that type is required. There is thus, no need to construct an object explicitly as such.

Auto-unboxing is the process by means of which the value of a “boxed” object is automatically extracted (“unboxed”) from a type wrapper when its value is required. There is thus, no need to explicitly invoke a method such as intValue( ) or doubleValue( ), etc.

Question 56.
What is the Object class in Java?
Answer:
There is one special class, Object, defined by Java, which is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Moreover, since arrays are implemented as classes in Java, a variable of type Object can also refer to an array.

Question 57.
Define an interface in Java.
Answer:
An interface defines a set of methods that will be implemented by a class. An interface, by itself, does not implement any method. In this way, we see that an interface is a purely logical construct that describes functionality without defining any implementation whatsoever.

Question 58.
What is the similarity and difference between interfaces and abstract classes?
Answer:
Interfaces are syntactically similar to abstract classes. But, in an interface, no method can have a body. Thus, an interface does not provide any implementation at all. It tells what is to be done but is completely silent about how it is to be done. Once an interface is specified, any number of classes can implement it. Moreover, one class may implement any number of interfaces.

Question 59.
How will you choose between an interface and an abstract class?
Answer:
When you can fully describe the concept in terms of ‘what it does’ without any need to specify ‘how it does it’, you should use an interface. However, if you need to include at least some implementation details, you should use an abstract class to represent your concept.

Question 60.
What is an exception handler?
Answer:
As we have already stated in the answer to Q. 36, an exception is an error which occurs at run-time. Exception handling streamlines error handling by allowing the program to specify a block of code, called an exception handler, which is executed automatically in case of an error. Exception handler eliminates the need to manually check the success / failure of each specific operation or method call. In case an error occurs, it is processed / handled by the exception handler gracefully.

Question 61.
Can you elaborate on the consequences of an uncaught exception?
Answer:
In general, if your program does not catch an exception, it will be caught by the run-time system, which, in turn, will report an error and terminate the program abnormally / ungracefully.

Question 62.
What is the major benefit of exception handling?
Answer:
One of the major benefits of exception handling is that it enables your program to respond to an error and then continue running, that is, handle the error gracefully, and then continue further.

Question 63.
Can you have a try block followed by a finally block with no catch clauses?
Answer:
Syntactically, when a finally block follows a try block, no catch clauses are technically required. In such a case, the finally block gets executed after exit from the try block, but no exceptions are handled in such a case / event.

Question 64.
Explain the concept of an inner class.
Answer:
Classes present inside another class are termed inner classes. A point to note is that inner classes increase the complexity of code and must be used only if absolutely necessary. In this context, it would be worthwhile to mention that inner classes are used to implement adapters in an AWT program.

class X
      {
           
        int x;
        public void do( )
        {     }
        // Inner class
        Class Y
        {
      
            public void done( )
            {
                 /* can access the instance variables of the outer class */
                 x = 100;
            }
        }
      }

Question 65.
Explain the concept of anonymous classes.
Answer:
An anonymous class is an inner class without a name. An anonymous class, in general, makes the code difficult to read and understand. Its use must be limited to very small classes (with a method or two) and whose use is well understood such as in the case of the AWT event¬handling adapter classes.

Question 66.
What types of variables are allowed in an interface?
Answer:
All the variables in an interface must be public, static, and final, that is to say, constants.

Question 67.
Are there any restrictions imposed on interfaces vis-a-vis classes?
Answer:
An interface is akin to a class with a few restrictions including the following:-

  1. As mentioned in the previous problem, all variables in an interface must be public, static, and final, i.e. constants.
  2. All methods in an interface are implicitly declared public and abstract.

Another point to note is that a class can inherit multiple interfaces.

Question 68.
What is a stream in Java?
Answer:
Java programs perform Input / Output through streams. A stream is an abstraction that produces/consumes information. A stream is liked a physical device by the I/O system. It is useful to note that all streams behave in the same manner irrespective of the physical device they might be linked to.

Question 69.
Compare and contrast byte streams with character streams.
Answer:
The following four are the major points of difference between Byte Streams and Character Streams:-

  1. java.io.InputStream and java.io.OutputStream are the base byte streams while java.io.Reader and java.io. Writer are the base character streams.
  2. Byte streams are 8 bit streams while character streams are 16 bit Unicode streams.
  3. In byte streams, method names end with the suffix InputStream or OutputStream while in case of character streams, method names end with the suffix Reader or Writer.
  4. Since character streams are Unicode, they are internationalized and more efficient than byte streams.

Question 70.
Elucidate the benefits of the streams.
Answer:
The streaming interface to I/O in Java provides a clean abstraction for a complex and often cumbersome task. The composition of the filtered stream classes allows you to dynamically build the custom streaming interface to suit your data transfer requirements. Java programs written to adhere to the abstract, high-level InputStream, OutputStream, Reader, and Writer classes will function properly even in the future when new and improved concrete stream classes are invented.

This model works very well even when we switch from a file system-based set of streams to the network and socket streams. Moreover, serialization of objects is expected to play an increasingly important role in the future Java programming. In fact, Java’s serialization I/O classes provide a portable solution to this sometimes tricky task/proposition.

Question 71.
Name the predefined I/O streams in Java.
Answer:
System.in, System.out, and System.err are the three predefined I/O streams in Java. By default, System.in refers to the keyboard while System.out and System.err refer to the console.

Question 72.
Name the two byte streams and the two character streams related to File I/O in Java, respectively.
Answer:
File Input St ream & FileOutputStream are the two byte streams and FIleReader & FileWriter are the two character streams, respectively, related to File I/O in Java.

Question 73.
How is binary data read and written?
Answer:
Binary data is read and written using the DatalnputStream and DataOutputStream streams, respectively.

Question 74.
Name the two classes at the top of the byte stream classes.
Answer:
InputStream and OutputStream.

Question 75.
Name the two classes at the top of the character stream classes.
Answer:
Reader and Writer.

Question 76.
Does Java have a generalized console input formatter akin to the standard C function scanf() or the C++ input operators?
Answer:
Yes, added by JDK 5 recently Java has the Scanner class which reads formatted input and converts it into its binary form. The Scanner class is the complement of the Formatter class of Java which has made formatted output in Java very easy akin to the printfO style of functions in C/C++.

Question 77.
Elucidate the New I/O system.
Answer:
Java 2, version 1.4 added a new way to handle I/O operations. Called the new I/O APIs, it supports a channel-based approach to I/O operations. The new I/O (NIO) system is built on two foundational items, viz. buffers and channels. A buffer holds data. A channel represents an open connection to an 1/O device, such as a file or a socket. In general, to use the NIO system, you obtain a channel to an I/O device and a buffer to hold data. You then operate on the buffer, inputting / outputting data as needed. We must, at this stage, sound a caveat as to whether NIO is the future of 1/O handling? The channel/buffer based NIO approach is currently designed to supplement, and not supplant the traditional and standard stream-based I/O mechanisms.

Question 78.
What types of comments are supported by Java? Does it support documentation comments?
Answer:
Java supports three types of comments – the first two are // and /* */• The third type is called a documentation comment. A documentation comment begins with /** and ends with */. Using such documentation comments, you can embed information about your program into the program itself; and, later on, you can use the javadoc utility program to extract this information and put it into an HTML file.

Question 79.
Define a package.
Answer:
A package is a container for classes that is used to keep the class name space compartmentalized.

Question 80.
Can you create a hierarchy of packages?
Answer:
You can indeed create a hierarchy of packages. To do so, simply separate each package name from the one above it by using a period. The most general form of a multileveled package statement is as follows:-
package pkg1[.pkg2[.pkg3.[pkg4]]];

Note that a package hierarchy must be reflected in the file system of your Java development system.

Question 81.
What does the Math class contain?
Answer:
The Math class contains all the floating-point functions that are used for geometry and trigonometry such as sin( ), as well as several general-purpose methods such as sqrt( ).

Question 82.
What do you mean by generics?
Answer:
Generics imply parameterized types. They provide a streamlined and type-safe approach to deal with different data types as also promote reusability of code. Generics were introduced by JDK 5 and are somewhat similar to templates in C++.

Question 83.
How is java.util useful?
Answer:
The java.util package contains one of Java’s most powerful subsystems, viz. collections. In addition to collections, java.util contains a wide assortment of classes and interfaces, which support a broad range of functionality such as generating pseudorandom numbers, manipulating date and time, observing events, manipulating sets of bits, and tokenizing strings. These classes and interfaces are used throughout the core Java packages and are, of course, available for use in the programs you write.

Question 84.
Elucidate the utility of collections.
Answer:
Collections simplify many programs by providing off-the-shelf solutions to several common but at times difficult to develop data structures. For instance, there are built-in collections that support dynamic arrays, linked lists, stacks, queues, and hash tables.

Question 85.
On what principle does a Stack operate?
Answer:
Stack is a First-in, Last-out list. To visualize a stack, imagine a stack of plates on a table. The first plate put down is the last one to be retrieved.

Question 86.
What is the principle behind the Queue?
Answer:
Queue is a First-in, First-out list, i.e. the first item put in a queue is the first item retrieved from it. Queues are common in real life, e.g. lines at a bank or railway reservation center are queues.

Question 87.
What is a Hashtable?
Answer:
Hashtable creates a collection which uses a hash table for ‘storage (the hash table, in turn, stores information using a mechanism known as hashing).

Question 88.
What is the ArrayList class?
Answer:
The ArrayList class supports dynamic arrays, which can grow or shrink as per the user requirements.

Question 89.
Should collections be limited to “large jobs” such as corporate databases, inventory systems, or mailing lists?
Answer:
Collections need not be reserved for only the “large jobs” such as corporate databases, inventory systems, or mailing lists. They are equally effective when applied to smaller jobs, e.g., a TreeMap would be ideal to hold the directory structure of a set of files and a TreeSet would be an excellent choice for storing project-management information.

Question 90.
How can you obtain an Array from an ArrayList?
Answer:
When working with ArrayList, you might want to obtain an actual array, which contains the contents of the list. You can easily accomplish this by calling the toArrayi) method.

Question 91.
Are the == and the equals( ) method the same? If not, point out the difference between the two.
Answer:
It is important to understand that the equals( ) method and the = = operator perform two different operations. While the equals( ) method compares the characters inside a String object, the = = operator compares two object references to see whether they refer to the same instance.

Question 92.
How can you create a string in Java that is mutable?
Answer:
A mutable string in Java can be created by means of the StringBuffer class. In the StringBuffer class, characters can be inserted in the middle or appended to the end of a string.

Question 93.
Can an enumeration be used to control a switch statement?
Answer:
Yes, enumerations can easily be used to control a switch statement. Of course, all of the case statements must use constants from the same enum as that used by the switch expression.

Question 94.
Can you assign floating point values to integers in Java as in C/C++?
ANS.
No! Not at all!! This is due to the fact that Java is a very strongly typed language unlike C/C++.

Question 95.
How will you declare a three-dimensional array of shorts and a string variable called surname in Java? How will you determine the size of an array?
Answer:
A three-dimensional array of shorts can be declared in Java in the following manner:-
short s_arr[ ][ ][ ];
A string variable called surname can be declared as:-
String surname[ ];
In Java, the size of an array can be determined by means of the property called length.

Question 96.
Can variables in the inner scope have the same name as the ones in the outer scope in Java as in C/C++?
Answer:
No! Not at all!! In C/C++, there is no such restriction. However, the designers of Java opined that such “name hiding” could very well lead to programming errors and whence, disallowed it.

Question 97.
Does Java have a foreach loop like C#?
Answer:
JDK5 introduced thefor-each style loop as a simple enhanced version of the ‘for’ loop unlike C# which uses the foreach keyword. The major advantage of this is that no keyword is required and no pre-existing legacy code is broken.
The most general form of for-each style loop is:
for (var_type var_name : coll)
{
statement(s);
}

where, var_type and varjname specify the type and name of the iteration variable and the collection being cycled through is referred to by coll.

Question 98.
What are the two uses of the keyword ‘super’?
Answer:
The Java keyword, super, can be used in two distinct ways. Its first use is to call/ invoke a super class constructor. Its second use lies in accessing a member of the superclass that has been hidden by a member of the subclass having the same name.

A subclass can call a constructor defined in its immediate superclass by using super as given below:
super(argumentjist);

where, argumentJist specifies any arguments needed by the constructor in the superclass. Note that super() must be the first statement executed in the constructor of the subclass always. Also, note that since constructors can be overloaded, super() can be invoked using any form defined by the superclass. The constructor that matches the parameters/arguments shall be the one to get executed.

Now, we introduce you to the second use of super that acts in a manner similar to this except for the fact that it always refers to the superclass of the subclass in which it is used. The most general form of this usage is:

super.member

where, member can either be an instance variable or a method. This form of super applies mostly to cases in which member names of a subclass hide members by the same name in the superclass.

Question 99.
Does Java support formatted output akin to the printfO style function in C/C++? If yes, when did Java begin to have this facility and why it could not provide it earlier?
Answer:
With the release of JDK 5 (Java Development Kit 5), Java added a new capability, viz. the ability to easily create formatted output akin to the printfO style of functions in C/C++. This feature was implemented using the Formatter class of Java.

You might wonder why Java was not able to earlier provide such a facility. The simple reason was that the printfO style formatting requires the use of variable-length arguments (varargs), which Java did not support before JDK 5.

Once varargs became available with the release of JDK 5, it was easy pickings to add a general- purpose formatter. At the roots of Java’s formatted output is the Formatter class, which provides format conversions that let you display numbers, strings, date and time in almost every format as per your requirements very much similar in fashion to the printfO function of C/C++.

The Formatter class works by converting the binary form of data used by a program into formatted text. It stores this text in a buffer from where it can be obtained any time you need. The buffer may be supplied explicitly or you can let the Formatter supply it on its own. Formatter may be constructed in a variety of ways including the following:-

Formatter( )
Formatter(Appendable buf)
Formatter(String file) throws FileNotFoundException
Formatter(File outF) throws FileNotFoundException
Formatter(OutputStream outStrm)

where, buf specifies a buffer for the formatted output, file specifies the name of the file which shall receive the formatted output, outF specifies a reference to an output file that shall receive the output, and outStrm specifies a reference to an output stream which shall receive the output.

After creating the Formatter, you can use the following forma t( ) method to create a formatted string:-

Formatter format( String fmtString, Object… args)

where, fmtString contains either character which is copied as such to the output buffer or format specifiers such as %d for integers, %/for floating-point data and %s for strings.

An integer placed between the % sign and format conversion code acts as the minimum field-width specifier. The default padding is done with spaces. If you want to pad with 0’s, place a 0 before the field-width specifier, e.g., %05d will pad a number of less than five digits with 0’s so that its length is five.

By default, all output is right-justified. You can force output to be left-justified by placing a minus sign directly after the % sign, e.g., %-10.2f left-justifies a floating point number with two decimal places in a 10-character field.

When displaying large numbers, it is often useful to add a comma separator/flag, e.g., ‘ 4337788990.23 is more easily read as 4,337, 788,990.23. Formatter lets you achieve this very easily. Formatter also includes a very useful feature that lets you specify the argument to which a format % specifier applies. In other words, it allows you to use an argument index.

Question 100.
Can you elaborate on the ‘why’ of Java?
Answer:
Java serves both as a programming language as well as a platform. As a programming language, Java is simple, object-oriented, distributed, interpreted, robust, secure, architectnre- neutral, portable, high performance based, multithreaded and dynamic. By definition, a platform is a hardware/software environment in which a program can be run. The majority of present day
platforms are a combination of hardware (the machine) and software (the operating system).

The Java platform is quite different in the sense that it consists only of a software component that can be run on varying hardware. It consists of the Java Virtual Machine (JVM) and the Java Application Programming Interface (JAVAAPI).

Java is simple with syntax similar to that of C and C++ but without their semantic complexity that make them confusing and insecure. Thus, there is no need for pointer management etc. Java is object-oriented unlike C but-likewise C++.

Java is distributed in the sense that network access protocols like TCP/IP, UDP, HTTP, and — FTP are supplied with it that allows for the development of client/server model in order to access
data on a distant/remote machine. Once again, a Java program does not operate in the normal way.

Rather, it is interpreted by the JVM. Java achieves robustness by strict program checking during compilation as well as execution. The Java code is verified both during compilation and run-time by the interpreter making it free from errors and ensuring security.

Java is inherently architecture-neutral as the Java compiler produces Java bytecodes independent of any specific environment. The primary data in Java is primarily of the same size (generally IEEE754) ensuring portability across varying platforms. Although the Java program is interpreted resulting in it being slow to a degree but, still, Java uses JIT (Just In Time), a code interpretation optimizing technique resulting in almost the same performance as C++.

Java introduces multithreading, a concept that allows for many things/applications being run simultaneously and increases response time. Finally, in Java, one doesn’t have to edit links (mandatory in C++) resulting in executables having a lower memory size. Thus, Java is dynamic as well!

The Java Virtual Machine (JVM) is the base of the Java platform and is essential for running the Java programs. It is compatible with any type of computer machine. The JVM undertakes the loading of Java bytecodes, classes, memory management, security management and, if necessary, interfacing with native code such as C. The JAVAAPI package contains a collection of prefabricated software components that supply a number of functions like the management of graphical interface etc.

The Java Application Interface is organized as a collection of packages just as libraries in C/ C++. Each package has Java classes that are predefined language objects directly reusable. The Java platform consisting of the JVM and the JAVAAPI is the link between the hardware and the Java program.

To compile Java source code, we need to use the compiler dedicated to our machine. After compilation, the file remains independent of the hardware platform and the operating system. The interpreter rims Java programs.

To run Java applets, the interpreter is incorporated into Java compatible Web browsers such as Hotjava (refer Chapter 2), Netscape Navigator etc. To run independent stand alone Java applications, we need to run the virtual machine (JVM) supplied with the Java development Kit (JDK) or the Java runtime Environment (JRE).

OOPS and Core Java Interview Questions in Java Chapter 1 img 1

As discussed above, a Java program is independent of the operating system/platform on which it is run. This is achieved by means of the Java Virtual Machine (JVM) that converts the original source code into bytecodes (which is platform independent). Finally, the Java interpreter on the concerned operating system converts these bytecodes into machine code which can be run on that particular machine. Figure 1 illustrates all this.

Question 101.
Can you explain the difference between a .class file and an .exe file?
Answer:
There is basically one main point of difference between the two. While a .class file contains bytecodes for the JVM and is thus system independent, an .exe file contains machine language for the microprocessor and is thus system dependent.

Question 102.
What do you understand by an API document? Elucidate.
Answer:
An API document is essentially an .html file having complete details of all the features of a software/product/technology. It is very much handy for the users in using the relevant software/product/technology.

Question 103.
Can you explain the difference between the #include statement of C/C++ and the import statement of Java?
Answer:
The import statement of Java is a much better option than the #include statement of C/C++ since the import statement makes the JVM go to the standard Java library, run the code over there, and finally, substitute the result into the Java program thus avoiding any wastage of memory/processor’s time while the #include directive of C/C++ makes the compiler go to the standard C/C++ library and copy the code from the header files into the C/C++ program leading to a considerable increase in the program size, which, in turn, results in wastage of memory and the processor time.

Question 104.
Suppose, String args [ ] is not written in the main( ) method; will the program still run? Elucidate.
Answer:
Suppose, we write the main( ) method without String args [] as follows:-
public static void main( )
The compiler will not report any error in such a case but the Java Virtual Machine environment, which always looks for the main( ) method with String args [ ] as parameter, will not be able to recognize the main( ) method in such a case and, whence, the program shall not run/ execute.

Question 105.
Is it possible in Java to call the main( ) method of a class from another class? Elucidate.
Answer:
Yes! It is very much possible!! This is achieved by the use of the relevant clas$mme.main( ). Note that at the time of calling main( ), you will have to pass a string type array to it.

Question 106.
Is it possible in Java to compile and run a program without the main( ) method? Elucidate.
Answer:
Yes! It is very much possible!! This is achieved by the use of a static block in the relevant Java program.

Question 107.
Can you explain the difference between the float and double data types of Java?
Answer:
The float data type can store up to seven digits after the decimal point accurately; on the other hand, the double data type can store up to fifteen digits after the decimal point accurately.

Question 108.
Can you explain the difference between the return statement and the System. exit(0) statement of Java?
Answer:
The return statement can be used anywhere in a method to come out of it while System.exit(0) can be used anywhere in a method to come out of the Java program itself.

Question 109.
Can you explain the difference between the System. exit(1) statement and the System.exit(0) statement of Java?
Answer:
The System.exit(1) statement is used to exit the Java program abnormally because of some error encountered during its execution while System.exit(0) is used to exit the Java program normally without any error.

Question 110.
Can you explain the difference between the System.err and System.out?
Answer:
Although both System.out and System.err send messages to the monitor, by default, the difference lies in the fact that System.out displays normal output while System.err displays error messages.

Question 111.
What are the types of memory available in Java; incidentally, on which memory are arrays created in Java?
Answer:
There is no static memory in Java; there is only dynamic memory. As such, everything (objects, variables) as well as arrays are created on dynamic memory only.

Question 112.
Can you consider class as a data type?
Answer:
Yes! Indeed, a class is a user-defined data type.

Question 113.
What, according to you, is String – a class or a data type?
Answer:
String is a class in java.lang package. But as mentioned in the previous question, a class can be taken to be a data type as well. Whence, String can be considered as a data type too.

Question 114.
Can you explain the difference between the String class and the StringBuffer class of Java?
Answer:
There are two points of difference between String and StringBuffer classes of Java:-

  • String class objects are immutable so that their contents are not modifiable; StringBuffer class objects are mutable so that their contents are modifiable.
  • The methods that directly manipulate the contents of objects are available only in the StringBuffer class.

Question 115.
Can you explain the difference between the StringBuffer and StringBuilder classes of Java?
Answer:
StringBuilder is identical to StringBuffer with one important exception, viz. it’s not synchronized, which, in turn, implies that it’s not thread-safe. The main advantage and benefit of StringBuilder is faster performance. But, there is a caveat. In cases where you are using multithreading, you must make use of StringBuffer instead of StringBuilder since only StringBuffer is synchronized.

Question 116.
What do you understand by hash code? How can you determine the hash code of an object?
Answer:
Hash code is a unique identification number assigned to objects by the JVM. It is created based on the basis of the location of the object in memory and is unique for all objects with the sole exception of String objects. The hash code of an object can be determined using the hashCode( ) method of the Object class in java.lang package.

Question 117.
Can a class in Java be declared private?
Answer:
By declaring a class as private, it becomes unavailable to the Java compiler resulting in a compile-time error. However, inner classes can be declared to be private.

Question 118.
What do you understand by factory methods? Elucidate.
Answer:
A method that creates and returns an object to the class to which it belongs is known as a factory method. A single factory method can replace several different constructors in the class by accepting different options from the user while in the process of creating the object.

Question 119.
In what different ways can you create an object in Java?
Answer:
You can create an object in Java in any of the following ways:-

  • By the use of the new operator;
  • By cloning an already available object;
  • By the use of the newInstance( ) method; and,
  • By the use of factory methods.

Question 120.
What is the main point of difference between method overloading and method overriding?
Answer:
Writing two or more methods with the same name but different signatures is referred to as method overloading while writing two or more methods with the same name and the same signatures is referred to as method overriding.

Question 121.
Can you name the super class for all classes inclusive of your classes as well?
Answer:
The Object class.

Question 122.
Can you write an interface without any methods?
Answer:
YES!

Question 123.
Can you name the method used in cloning?
Answer:
The clone( ) method of the Object class.

Question 124.
What is an abstract method/class?
Answer:
An abstract method is simply a method without any body. It is generally used when the same method has to carry out different tasks based upon the object calling it. An abstract class is simply a class with one or more abstract methods.

Question 125.
Can you forcibly implement only the features of your class; if yes, how?
Answer:
This can be easily achieved by using an abstract class or by the use of an interface.

Question 126.
Can one interface be implemented from another?
Answer:
NO! Not at all!!

Question 127.
Do you think you need to write both the following statements:

  1. import java.awt.event.*;
  2. import java. awt. *;

Or, the second one alone is sufficient? Give appropriate reason(s) for your answer.
Answer:
event is a sub-package of java.awt package. However, when a package is imported, its sub-packages are not imported into the program by themselves. Whence, for every package or sub-package, you need to write a separate import statement. Therefore, if you want to import the classes and interfaces of both the java.awt.event and java.awt packages, you should include both the import statements in your program.

Question 128.
What do you understand by CLASSPATH? Elucidate.
Answer:
CLASSPATH is an environment variable which tells the Java compiler as to where to look for the class files to import.

Question 129.
What do you understand by a JAR file?
Answer:
A JAR or Java Archive file, as it is called, is a file containing compressed versions of different .class files, audio files, image files, and directories.

Question 130.
What is the scope of the default access specifier?
Answer:
Default members are available within the same package but not outside it.

Question 131.
Bring out the difference between an exception and an error.
Answer:
An exception is an error that can be handled gracefully but an error means a condition that cannot be handled and the program can do nothing to handle the situation.

Question 132.
Bring out the difference between throw and throws.
Answer:
throw is used to throw an exception explicitly and handle it using a try-catch block while throws is used to throw the exception out of a method without handling it there and then.

Question 133.
Can you name the Wrapper class with only one constructor?
Answer:
Character wrapper class.

Question 134.
Can a primitive data type be stored into a collection?
Answer:
NO! Not at all!! Collections can store only objects.

Question 135.
Bring out the major difference between ArrayList and Vector.
Answer:
ArrayList object is hot synchronized by default while Vector object is synchronized by default.

Question 136.
What do you understand by serialization? Are there any variables which cannot be serialized?
Answer:
Serialization is essentially the process of storing object contents into a file; static and transient variables cannot be serialized.

Question 137.
What do you understand by jenumerations?
Answer:
Enumerations were added to Java with the release of JDK 5. An enumeration is a way of assigning names to integer constants..

To give you a practical example of the need for enumerations, imagine a scenario where you wanted to represent the seasons of the year in a program. You could very well use the integers 0, 1,2, and 3 to represent spring, summer, autumn, and winter respectively. This solution would work but it is not very innovative, e.g., if you used the integer value 0 in the program code, it would not be very obvious that a particular 0 represented spring.

Furthermore, it would also not be a very robust solution to the problem, e.g., if you declare an integer variable called season, there is nothing to prevent you from assigning the variable season any legal integer value other than 0,1, 2, or 3. Enumerations offer a much better solution. You can create an enumeration (sometimes called an enum type), whose values would be limited to a set of symbolic names, e.g. in this particular case, it could be:

enum season!spring, summer, autumn, winter}

The most general form of an enumeration is:

enum enum_name {enumjist} // notice the keyword ‘enum’!

where enum_name is the name of the said enumeration and enumjist is a comma-separated list of identifiers.

Java enumerations are class types. Although an enum is not instantiated using new, it has more or less the same capabilities as other classes. This feature adds to the power of Java enumerations in a big way, e.g., you can give them constructors, add instance variables/methods, and even implement interfaces.

It is important to realize that each enum constant is an object of its enumeration type so that when you define a constructor for an enum, the constructor is invoked when each enum constant is created.

Question 138.
What do you understand by annotations?
Answer:
JDK 5 introduced a new feature into the Java language, viz. annotations (metadata) by means of which you could embed supplemental information into a source file.
In fact, this information is itself called an annotation, which leaves the semantics/actions of a program unchanged but can be used by various tools both during deployment and development, e.g., an annotation can be processed by a source-code generator.
An annotation is created by means of a mechanism based on the interface. To declare an annotation, say, MyAnnotation, we proceed as follows:

// A simple annotation type'
@interface MyAnnotation
{
String s( );
int value( );
}

Take note of the @ preceding the keyword interface. This indicates to the compiler that an annotation is being created. Now, take note of the two members, s( ) and value( ). All annotations

solely consist of method declarations. But, you don’t provide bodies for these methods; Java implements these methods instead. Also, the methods act much like fields as we shall see shortly.

Once an annotation is declared, it can be used to annotate any declaration, which means that any type of declaration can have an annotation associated with it, e.g., classes, methods, fields, parameters, and enum constants may be annotated. In fact, even an annotation may be annotated. In all cases, the annotation comes before the rest of the declaration. When applying an annotation, its members are given values, e.g., here is an example of MyAnnotation being applied to a method:

// Annotate a method
@MyAnnotation(s = "string”, value - 999)
public static void my Method( )
{
// ...............
}

Thus, MyAnnotation has linked with the method my Method( ). Take note of the annotation syntax. The name of the annotation, preceded by a @1, is followed by a parenthesized list of member initializations. Also, take note of the fact that no parentheses follow s or value in this assignment of initial values so that annotation members act like fields in this regard.

Question 139.
What do you understand by a generic type?
Answer:
A generic type is a class/interface which can act on any data type. In other words, it is type-safe.

Question 140.
Bring out the major difference between window and frame.
Answer:
A window is a frame without any borders/title while a frame does have borders/title.

Question 141.
Elucidate the MVC architecture in JFC/swing.
Answer:
MVC or Model-View-Controller, as it is called, is essentially a model used in swing components, wherein, Model is the data of the component, Vieiv is its appearance while Controller is a mediator between the. model and the view.

In other words, MVC is the separation of the model of an object from its view as well as how it is controlled.

Question 142.
Enumerate the various window panes available in the swing.
Answer:
The various window panes available in the swing are enumerated below:-

  • Content pane;
  • Glass pane;
  • Layered pane; and,
  • Root pane.

Question 143.
What do you understand by a layout manager?
Answer:
A layout manager essentially is a class helpful in arranging components (in a specific/ particular way) in a frame/container.

Question 144.
Consider the following Method whose sole purpose is to find out if the argument passed to it is odd:

public static boolean odd(int k)
{
return k % 2 ==1;
}
Does the Method work?

Does the Method work?
Answer:
An odd number is an integer that leaves 1 as the remainder when divided by 2. The expression k % 2 computes this remainder; so, it looks like that this Method ought to work. But, it returns the wrong answer one-quarter of the time. This is so since half of the integer values are negative and when half of these negative integer values are divided by 2, the remainder is -1, not 1.

Question 145.
Can you provide declarations for two variables z and k such that:
z+- k;
is legal while
z = z + k;
is illegal?
Answer:
Consider:
short z = 0;
int k – 1234;
The compound assignment:
z +- k;  // contains a hidden cast
// but compiles without error
ivhile the corresponding simple assignment:
z = z + k; // requires explicit cast
// and won’t compile
// due to possible loss of precision

Question 146.
Can you provide declarations for two variables z and k such that:
z+= k; is illegal
while
z = z + k; is legal?
Answer:
Consider:
Object z = “BE”;
String k = “YOURSELF ALWAYS!”;
The compound assignment:
z += k; // is illegal
// since LHS has an object reference type
// other than String
while the corresponding simple assignment:
z – z + k; I //is legal since RHS is of type String
// and String is an assignment
// compatible with-Ohject

Question 147.
Consider the following Program:

public class Hurrah
{
public static void main(String args [ ])
{
System.out.printlnC'H" + "A");
System.out.printlnCH' + 'A');
}
}

What does the Program print?
Answer:
HA
137

Question 148.
Consider the following Program:

public class Browser
{
public static void main(String args [ ])
}
System.out.printC explore":);
http://www.yahoo.mail;
System.out.printlnC -.maximize");
}
}

What does the program print?
Answer:
explore: :maximize

Question 149.
Consider the following Program:

public class Increase
{
public static void main(String args [ ])
{
int z = 0;
for (int y = 0; y < 100; y++)
z = z++;
System, out.println(z);
}
}

What does the Program print?
Answer:
0

Question 150.
Can you provide a declaration for a variable z such that the loop:
while (z != z + 0)
{ }
becomes an infinite loop (note that you are not allowed to declare z to be of type double or float)?
Answer:
z can be initialized to any value of type String:
String z = “BECOME YOURSELF ALWAYS!”;
The integer value 0 is converted to the string value “0” and appended to z. The resulting string is not equal to the original as computed by the equals() method; so, it can’t be surely identical, as computed by the == operator. Whence, the boolean expression:
(z != z + 0)
evaluates to true always and the loop never terminates.

Question 151.
Consider the following Program:

public class Indecision
{
public static void main(String args [])
}
System.out.println(indecisive( ));
}
static boolean indecisive( )
{
try
{
return false;
}
finally
{
return true;
}
}
}

What does the program print?
Answer:
true

Question 152.
Consider the following Program:

public class World
{
public static void main(String args [ ])
{
try
{
System.out.println(" Bye");
System.exit(0);
}
finally
{
System.out.println("Arunesh");
}
}
}

What does the Program print?
Answer:
Bye

Question 153.
Consider the following Program:

public class World
{
public static void main(String args [ ])
{
((null) null).Bye( );
}
public static void Bye( )
{
System.out.println("Arunesh");
}
}

What does the Program print?
Answer:
Arunesh

Question 154.
Consider the following Program:

public class World
{
public static void main(String args [ ])
{
System.out.println(Bye.Arunesh.Hello);
}
}
class Bye
{
static class Arunesh
{
static String Hello = "Arunesh";
}
static Z Arunesh = new Aruneshi);
}
class Z
{
String Hello = "Bye";
}

What does the Program print?
Answer:
Bye

Question 155.
Consider the following Program:

class World
{
public static final String ITEM = "10,000";
}
public class Hello extends World
{
public static final String ITEM - "1";
public static void main(String arg[ ])
{
The system, out.println (Hello. ITEM);
}
}

What does the Program print?
Answer:
1

Q. 156
Consider the following code:
for (int y = 0, int z = 0; y < 10; y++) { }
Will the code compile?
Answer:
No! You can declare the data type of at most one variable in the initialization section of the ‘for’ loop. The correct statement is:- for (int y – 0, z = 0; y < 10; y ++) { }

Question 157.
Consider the following Program:

class Hello
{
public static void main(String args[ ])
{
boolean b = 1;
System.out.println(b);
}
}

Will this program compile?
Answer:
No! Boolean variables can only take the values – true, false!!

Question 158.
Consider the following Program:

class Hello
{
public static void mainfString args[ ])
{
System.out.println(args[3]);
}
}

What does the Program print when run with the following command line?
java               Hello         VERY              GOOD           MORNING

  1. Hello
  2. VERY
  3. GOOD
  4. MORNING
  5. exception raised:java.lang.ArrayIndexOutOfBoundsException:3

Answer:
Unlike C/C++, java doesn’t start the parameter count with the program name. It does however start with zero. So, in this case, zero starts with VERY, GOOD would be l, MORNING would be 2 and there is no parameter 3; hence, an exception would be raised, and thus, the correct answer is:-

5. exception raised:javadang.ArrayIndexOutOfBoundsException:3

Question 159.
Which of the following statements is true?

  1. Methods cannot be overridden to be more private.
  2. static methods cannot be overloaded.
  3. Private methods cannot be overloaded.
  4. An overloaded method cannot throw exceptions which are not checked in the super/ base class.

Answer:

  1. Methods cannot be overridden to be more private.

Question 160.
Consider the following Program:

class base { }
class sub1 extends base { }
class sub2 extends base { }
public class cexcp
{
public static void main(String args[ ]>
{
base b = new base( );
sub1 s1 = (sub1) b;
}
}

What zoill happen if this program is compiled and executed?

  1. Compile and run without any error
  2. Compile-time exception is raised
  3. The run-time exception is raised

Answer:
3. Run-time exception is raised.

Question 161.
Consider the following Program:

class base
{
public void a_mthd(int z) { }
}
public class scope extends base
{
public static void main(String args[ ])
{
}
// Method HERE
}

Which of the following methods can be legally inserted in place of the comment //Method HERE?

  1. void a_mthd(int z) throws Exception {  }
  2. void a_mthd(long z) throws Exception { }
  3. void a_mthd(long z){ }
  4. public void a_mthd(int z) throws Exception { }

Answer:
2. void a_mthd(long z) throws Exception { }
3. void a_mthd(long z) { }

Question 162.
Consider the following Program:

public class Hello
{
public static void main(String args[ ])
{
/* Modifier at ZZ */ class InnerHello { }
}
}

What modifiers would be legal at ZZ in this program?

  1. public
  2. private
  3. static
  4. friend

Answer:

  1. public;
  2. private &
  3. static.

Question 163.
You need to create a class that will store unique object elements. You do not need to sort these elements but they must be unique.
What interface might be most suitable to satisfy this need?

  1. List
  2. Set
  3. Map
  4. Vector

Answer:
2. Set

Question 164.
Describe a java source file.
Answer:
A java source file must have “.java” extension. Also, it should have at least one top level public class definition and any number of non-public class definitions. The file name (without the extension) must match the public class name.

Question 165.
What is Bytecode?
Answer:
Every java program is converted into one or more class files. The content of each class file is a set of instructions referred to as Bytecode to be executed by the JVM. Java introduces Bytecode to produce platform independent program/code.

Question 166.
Why does the main method need a static identifier?
Answer:
The main method needs a static identifier since static methods and members do not require an instance of their class to invoke them and main is the first method that is called/’ invoked.

Question 167.
Will the program compile if the main method doesn’t have the static identifier?
Answer:
The program will still compile; but it can’t be executed or run.

Question 168.
Which is the default parent class for a Java class?
Answer:
java.lang.Object. By default, all java classes extend java.lang.Object unless they have their own parent class. Moreover, the package named java.lang is imported (by default) into all java files.

Question 169.
How are java objects passed to a method?
Answer:
Java passes both the primitive types and objects by value. During object passing, the object’s reference is copied.

Question 170.
What are native methods?
Answer:
Native methods are methods implemented in some other programming language such as C/C++. The Java Native Interface (JNI) is the API to invoke these native methods from a class in java.

Question 171.
What is the order of declaring class, package and import statements within a java.
file?
Answer:
The order should be the following:-

  1. package
  2. import statements
  3. class definition

Question 172.
Can a variable be an unsigned integer?
Answer:
No! Not at all!!
In java, all data types are signed numeric numbers.

Question 173.
Can a private method be static?
Answer:
YES!
A private method can indeed be static.

Question 174.
Enumerate and elucidate the various bit wise operators.
Answer:
The various bit wise operators are:-

  1.  ∼a           complement
  2.  a&b         bitwise AND
  3.  a | b         bit wise OR
  4.  a Λ b        bit wise exclusive OR (XOR)
  5.  a<<n       left shift n places
  6.  a>>n       right shift n places
  7.  a>>>n    ussigned right shift n places

Question 175.
Explain the use of ‘instanceof’ operator.
Answer:
The ‘instanceof’ operator verifies whether its first operand is an instance of its second operand.
Op1 instance of Op2 (Op1 must be the name of an object and Op2 must be the name of a class/interface/array type)
An object is considered to be an instance of a class if that object descends from that class directly/indirectly.
Example
Code:

class X
{ }
class Y extends class X
{   }
X x = new Y( );
if (x instance of X)
{
System.out.println("Instance of X");
}
if (x instance of Y)
{
System. out.println("Instance of Y");
}

Output:
An instance of X
Instance of Y

Question 176.
What are the access modifiers available for a class, method, and variable?
Answer:
public, private, protected, and default access.

Question 177.
Elucidate widening and narrowing conversions.
Answer:
A widening conversion occurs when we try to cast an object of lesser size to an object of larger size, e.g. short to long. A narrowing conversion, on the other hand, occurs when we try to cast an object of larger size to an object of lesser size, e.g. long to short.

Question 178.
How do you create Java API documentation?
Answer:
Java API documentation can be created using the javadoc utility which parses the declarations and documentation comments in a set of Java source files and produces a corresponding set of HTML pages describing (by default) the public and protected classes, nested classes (but not anonymous inner classes), interfaces, constructors, methods, and fields.

Question 179.
Explain the concept of jar, war and ear files.
Answer:
jar is Java Archive File used to package classes, property files etc. as a single file. To create a jar file we can use the Jar command just like the zip command in windows, e.g. to create a jar file with all class files under the current directory, we can use:-

jar -cvf jarfilenatne.jar *.class

war is a Web Archive File used to package a web application, i.e. classes, JSP’s, property files etc. as a single file.

ear is an Enterprise Archive File. This format is used to package EJB, JSP, Servlets, property files etc. It is generally used to package an entire enterprise application. It can consist of multiple war files.

Each war and ear will have its own deployment descriptor which is a XML based file.

Question 180.
How many JVM’s can run on a single machine?
Answer:
A JVM is like any other process. Whence, there is no limit on the number of JVM’s which can run on a single machine.,

Question 181.
Explain the Just-In-Time (JIT) compiler.
Answer:
The Java interpreter on any platform will interpret the compiled bytecode into instructions understandable by the particular hardware. However, the JVM handles one bytecode instruction at a time. The java JIT (Just-In-Time) compiler compiles the bytecode into the particular machine code as if the program had been compiled initially on that platform. Once the code has been (re)-compiled by the JIT compiler, it will, in general, run more quickly on that system.

Question 182.
Can you retrieve Java code from Bytecode?
Answer:
YES!
Class files can be decompiled using utilities such as JAD, which takes the class file as an input and generates a java file. This feature comes especially handy when you are confused as to which version of the java file was used to generate the class file in a multi-user environment.

Question 183.
Explain the concept of garbage collector.
Answer:
When an object is no longer required and its reference count is zero, it needs to be cleaned up and freed. The garbage collector does exactly this.
In fact, the garbage collector is a thread running as a part of the JVM process. This thread scans the ‘ program for objects that will never again be accessed and releases their resources back to the system. The basic garbage collector uses the mark and sweep algorithm (which marks all the unused variables whose reference count is zero and sweeps them).

Question 184.
Can you force the garbage collector to run?
Answer:
NO!
There is no way that guarantees that the garbage collector will indeed run. It runs as and when appropriate.

Question 185.
Bring out the difference between:

  1. String si = new StnngCxyz”);
  2. String s2 = “xyz”;

Answer:
“xyz” is known as a string literal.

In the first case, a new memory space is allocated in the heap on account of the ‘new’ and also allocated in the string pool on account of the literal “xyz” * In the second case, when the statement is being compiled, a pointer to the string literal “xyz”
is stored in s2.

Question 186.
When intern( ) method on a String object is invoked, what happens?
Answer:
Interned strings avoid duplicate strings. There is only one copy of each String that has been interned, no matter how many references point to it. The process of converting duplicated strings to shared ones is called interning and is accomplished by means of the intern( ) method.

Question 187.
Bring out the purpose of the StringTokenizer class.
Answer:
The StringTokenizer class allows an application to break a string into tokens. The StringTokenizer methods do not distinguish between identifiers, numbers, and quoted strings, nor do they recognize and skip comments. The set of delimiters (the characters which separate tokens, one from the other) can be specified either at creation time or on a pre-token basis.
Example

Code:
StringTokenizer strtok = new StringTokenizer ("Testing IT OUT!");
while (sfrfok.hasMoreTokens( )
{
System.out.println(strtok.nextToken( ));
}

Output:
Testing
IT
OUT!

Question 188.
Which collection sorts data?
Answer:
TreeMap.

Question 189.
Bring out the difference between Hashtable and HashMap.
Answer:
The main point of difference between Hashtable and HashMap is that while in a Hashtable, methods are synchronized and thus thread safe, in a HashMap, methods are not synchronized, not thread safe, making it faster.

Question 190.
Bring out the difference between Enumeration and Iterator interface.
Answer:
The main point of difference between Iterators and Enumerations is that Iterators allow the caller to remove elements from the underlying collection during the iteration but Enumerations do not allow any such provision.

Question 191.
What do you understand by the Throwable class?
Answer:
The Throwable class is the superclass of all errors/exceptions in the Java language so that only objects that are instances of the Throwable class or one of its subclasses are thrown by the JVM. Thus, only the Throwable class or one of its subclasses can be the argument type in a catch clause.

Question 192.
How can you write your own customized exceptions?
Answer:
Customized exceptions can be written by extending the java.lang. Exception class. In this context, it would be worthwhile to mention that the toString( ) method should be overridden to print an appropriate error message.

Question 193.
Suppose an exception goes uncaught; what happens in such a case?
Answer:
An uncaught exception results in the uncaughtException( ) method of the thread’s ThreadGroup being called, which ultimately causes the termination of the program in which it is thrown.

Question 194.
What gets printed when the printStackTrace( ) method is invoked?
Answer:
public void printStackTrace( )
Prints this.throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of this output contains the result of the toString( ) method for this object while the remaining lines represent data previously recorded by the filllnStackTrace( ) method.

The exact format of all this information is implementation dependent but the following may be regarded as a typical case:-

java.lang.NullPointerException
at Cls.muchjCls.java: 9)
at Cls.lunch(Cls.java: 6)
at Cls.main(Cls.java: 3)
The above output was produced by executing the following program:-

class Cls
{
public static void main(string args[ ])
{
lunch(null);
}
static void lunch(int [ ] x)
{
much(x);
}
static void lunch(int [ ] y)
{
System.out.println(y[0]);
}
}

Question 195.
How do you use these ( ) and super( ) methods with constructors? Bring out the difference between their use.
Answer:
this( ) method within a constructor is used to invoke another constructor in the same class while the super( ) method within a constructor is used to invoke its immediate superclass constructor.

Question 196.
Does java support operator overload?
Answer:
No! Not at all!!
However, java internally supports operator overloading in the form of performing String concatenation using the ‘+’ operator.

Question 197.
Compare and contrast Interfaces with Abstract classes.
Answer:
In this context, consider the following main points:-

(1) Neither interfaces nor abstract classes can be instantiated.

(2) Direct multiple inheritance is not allowed in Java unlike C++. But, java provides for interfaces to take care of this problem. A class can implement any number of interfaces, but can extend only one class.

(3) An interface has all public members and no implementation whatsoever. An abstract class is a class which may have the usual features of class members such as private, protected etc. but has some abstract methods.
(4) Interfaces should be used as much as possible and an abstract class must be used only when you want to provide some but not complete implementation.

Question 198.
Can you instantiate an abstract class? Elaborate.
Answer:
As mentioned in the previous problem, we cannot instantiate an abstract class. In order to declare an abstract class, we use the modifier or keyword abstract before the class keyword in our class definition, e.g.

abstract public class Form
{
.....................
.....................
}
class Circle extends Form
{    }

If you try to create an instance of the abstract class Form, the compiler reports an error!

Question 199
Can you declare an abstract class as final? If not, why not?
Answer:
An abstract class cannot be declared as final.
The purpose of having an abstract class is that its subclasses can extend its functionality and this very purpose of declaring an abstract class will be defeated in case an abstract class is allowed to be declared as final.

Question 200.
Bring out the use of the ‘transient’ keyword. ,
Answer:
On Object Serialization, if any of the object’s members need not be serialized, they must be declared as transient.