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

Qboops Java

The document is a question bank for the Object Oriented Programming course (231ITC302T) at Easwari Engineering College for the academic year 2023-2024. It covers fundamental concepts of OOP and Java, including principles, features, data types, and programming constructs. The content is structured into units with various questions aimed at assessing understanding of the subject matter.

Uploaded by

jayapriya060226
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Qboops Java

The document is a question bank for the Object Oriented Programming course (231ITC302T) at Easwari Engineering College for the academic year 2023-2024. It covers fundamental concepts of OOP and Java, including principles, features, data types, and programming constructs. The content is structured into units with various questions aimed at assessing understanding of the subject matter.

Uploaded by

jayapriya060226
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 84

EASWARI ENGINEERING

COLLEGE
(An Autonomous Institution)

Bharathi Salai, Ramapuram, Chennai-89

DEPARTMENT OF
INFORMATION
TECHNOLOGY

ACADEMIC YEAR: 2023-2024

ODD SEMESTER

QUESTION BANK
(REGULATION – 2023)

231ITC302T
OBJECT ORIENTED
PROGRAMMING

THIRD SEMSTER
B.Tech – Information Technology

Prepared by:
Mrs.S.ANUSHA HOD-IT

1
UNIT 1 Introduction to OOPS and Basics of Java
OOPS concepts- Introduction to Java: History of Java-Features of Java-Java Development Kit (JDK) - -
Basics of Java programming-Data types-Variables-Operators-Control structures including selection,
Looping-Overloading- Arrays in java. Working of Java; Including Comments; Using Classes in Java-
Constructors-Access specifiers- Declaring Methods in Java- The main() Method, Invoking a Method in
Java- Saving, Compiling and Executing Java Programs-Packages.
UNIT-I / PART-A
1 What are the OOP Principles?
The principles of object-oriented programming is Class inheritance , interface
implementation, abstraction of data and behavior, encapsulation of data and class
implementation, polymorphism and virtual methods.
2 What are the four cornerstones of OOP?
Abstraction: Can manage complexity through abstraction. Gives the complete
overview of a particular task and the details are handled by its derived classes.
Example : Car.
Encapsulation: Nothing but data hiding, like the variables declared under private of a
particular class is accessed only in that class and cannot access in any other the class.
Inheritance: Is the process in which one object acquires the properties of another object,
ie., derived object.
Polymorphism: One method different forms, ie., method overriding and interfaces are
the examples of polymorphism.
3 What are the features of Object Oriented Programming?
 Emphasis is on data rather than procedure.
 Programs are divided into objects.
 Data structures are designed such that they characterize the objects.
 Functions that operate on the data of an object are tied together.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can easily be added whenever necessary.
 Follows bottom-up approach.
4 What are the features of Java Language?
The features of Java Language are Simple, Object-Oriented, Portable, Platform
independent, Secured, Robust, Architecture neutral, Dynamic, Interpreted, High
Performance, Multithreaded and Distributed.
5 How Java supports platform independency?
 The meaning of platform independent is that, the java source code can run on all
operating systems. a compiler is a program that translates the source code for
another program from a programming language into executable code.
 This executable code may be a sequence of machine instructions that can be
executed by the CPU directly, or it may be an intermediate representation that is
interpreted by a virtual machine. This intermediate representation in Java is the
Java Byte Code.
 It is the Bytecode that makes it platform independent. This adds to an
important feature in the JAVA language termed as portability. Every system has
its own JVM which gets installed automatically when the jdk software is installed.
For every operating system separate JVM is available which is capable to read
the .class file or byte code. An important point to be noted is that while JAVA is
platform-independent language, the JVM is
platform-dependent

2
6 Give the contents of Java Environment (JDK).
The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets.
It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler
(javac), an archiver (jar), a documentation generator (javadoc) and other tools needed
in Java
development.
7 What is Java Interpreter?
It is a Java Virtual Machine. An interpreter is a program that reads in as input a
source program, along with data for the program, and translates the source
program instruction by instruction. For example, the Java interpreter java
translate a .class file
into code that can be executed natively on the underlying machine.
8 Give any 4 differences between C and Java.
C Java
C is a procedural Language Java is Object Oriented Language
C is a compiled language. Java is an Interpreted language
C uses the top-down {sharp & JAVA uses the bottom-up {on the
smooth} approach rocks} approach.
C does not support overloading JAVA supports Method Overloading
9 Give any 4 differences between C++ and Java.
C++ Java
C++ generates object code and the Java is interpreted for the most part and
same code may not run on different hence platform independent.
platforms. Java does not support pointers, templates,
C++ supports structures, unions, unions, operator overloading, structures
templates, operator overloading, etc.
pointers and pointer arithmetic.
C++ support destructors, which Java support automatic garbage
is automatically invoked when collection. It does not support destructors
the object is destroyed. as C++ does.
10 Distinguish between procedure oriented programming (POP) and Object
oriented
programming.(OOP)
POP OOP
In POP, program is divided into In OOP, program is divided into parts called
small parts called functions. objects.
POP does not have any access specifier. OOP has access specifiers named Public, Private,
Protected, etc.
POP does not have any proper OOP provides Data Hiding so provides
way for hiding data so it is less more security.
secure.
In POP, Overloading is not possible. In OOP, overloading is possible in the form of
Function Overloading and Operator Overloading.
In POP, Most function uses Global In OOP, data cannot move easily from
data for sharing that can be function to function, it can be kept public or
accessed freely from function to private so we can control the access of data.
function in the system. Example of Example of OOP are : C++, JAVA, VB.NET,
POP are : C, VB, FORTRAN, C#.NET.
Pascal
3
11 What are the data types supported in Java?
Operator in java is a symbol that is used to perform operations like +, -, *, / etc.
There are many types of operators in java which are Unary Operator, Arithmetic
Operator, Shift Operator, Relational Operator, Bitwise Operator, Logical Operator,
Ternary Operator and, Assignment Operator.

4
12 Define Abstraction.
Abstraction refers to the act of representing the essential features without including
the background details or explanations. It reduces the complexity and increases the
efficiency. Small programs can be easily upgraded to large programs. Software
complexity can easily be
managed.
13 What is Polymorphism?
Polymorphism is the ability to take more than one form and refers to an operation
exhibiting different behavior instances. Object oriented programs use
polymorphism to carry out the same operation in a manner customized to the
object. It allows a single name/operator to be associated with different operation
depending on the type of data passed to it.
14 Define Objects and Classes in Java
 Class is a collection of data and the function that manipulate the data.The data
components of the class are called data fields and the function components of
the class are called member functions or methods. The class that contains main
function is called mainclass.
 Object is an instance of a class. The objects represent real world entity. The
objects are used to provide a practical basis for the real world. Objects are
used to understand the real world. The object can be declared by specifying
the name of the class.
15 Write the syntax for declaration of class and creation of objects?
A class is declared using class keyword. A class contains both data and method that
operate on that data. Thus, the instance variables and methods are known as class
members. When creating an object from a class
Declaration − A variable declaration with a variable name with an object type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This
call initializes the new object.
class Student
{
String name;
int rollno;
int age;
}
Student std=new Student();
 std is instance/object of Student class.
 new keyword creates an actual physical copy of the object and assign it to the std
variable.
 The new operator dynamically allocates memory for an object.
16 Define Encapsulation (Apr/May 2012) (Apr 2017)
The wrapping up of data and functions into a single unit is known as data
encapsulation. Here the data is not accessible to the outside the class. The data
inside that class is accessible by the function in the same class. It is normally not
accessible from the outside of the component.

7 What is Inheritance? What are its types?


 Inheritance is a mechanism of reusing the properties and extending existing
classes without modifying them, thus producing hierarchical relationships
between them.
 Inheritance is a property by which the new classes are created using the old
classes.
 The old classes are referred as base classes and the new classes are
referred as derived classes. That means the derived classes inherit the
properties of base class.
 extends and implements keywords are used to describe inheritance in Java.
Types of inheritance are: Single inheritance, Multi-level inheritance, Hierarchical
inheritance, Hybrid inheritance.
Syntax :
class Subclass-name extends Superclass-name
{ //methods and fields }
19 Define class[NOV/DEC 2011]
Class is a template for a set of objects that share a common structure and a common
behavior.
20 What do you mean by Dynamic Initialization?
Java is a flexible programming language which allows the dynamic
initialization of variables. In other words, at the time of declaration one can
initialize the variables. In java we can declare the variable at any place
before it is used. Example: int a=10; float d=2.34f;
21 What do you mean by Variable? What are the rules for variable
declaration? Variable is a fundamental unit of storage in java. The variables
are used in combination with identifiers, data types, operators and some value
for initialization.
The syntax of variable declaration will be: data_type
name_of_variable[=initialization];
22 What are the steps for exection of a java program?
A program is written in JAVA, the javac compiles it. The result of the JAVA
compiler is the .class file or the bytecode and not the machine native code
(unlike C compiler).
The bytecode generated is a non-executable code and needs an interpreter to
execute on a machine. This interpreter is the JVM and thus the Bytecode is
executed by the JVM.
And finally program runs to give the desired output.

23 What do you mean by Bytecode? What is JVM and JIT?


Bytecode is an intermediate form of java programs.We get bytecode after
compiling the java program using a compiler called javac. The bytecode is to be
executed by java runtime environment which is called as Java Virtual
Machine(JVM). The programs that are running on JVM must be compiled into a
binary format which is denoted by .class files. The JVM executes
.class or .jar files, by either interpreting it or using a just-in-time compiler (JIT).
The JIT is used for compiling and not for interpreting the file. It is used in most
JVMs today to achieve greater speed.
24 What is difference between Methods and Constructor?
A constructor is a member function of a class that is used to create objects of that
class. It has the same name as the class itself, has no return type, and is invoked using
the new operator.
A method is an ordinary member function of a class. It has its own name, a return
type (which may be void), and is invoked using the dot operator.
25 What are the different datatypes in java?
TYPE SIZE RANGE SYNTAX
byte 8 bits -128 to 127 byte i,j;
short 16 bits -32768 to 32767 short a,b;
int 32 bits -2,147,483,648 to int i,j;
long 64 bits 2,417,483,647 long x,y;
float 32 bits -9,223,372,036,854,775,808 to float p,q;
9,223,372,036,854,775,807
double 64 bits 1.4e-045 to 3.4e+038 double a,b;
char 16 bits 4.9e-324 to 1.8e+308 char a;
boolean 1 bit true or false true or false
26 What is Garbage collection?
Objects are dynamically allocated by using the new operator, dynamically allocated
objects must be manually released by use of a delete operator. Java takes a
different approach; it handles deallocation automatically this is called garbage
collection. When no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed. Garbage
collection only occurs sporadically (if at all) during the execution of your program.
It will not occur simply because one or more objects exist that are no
longer used.
27 What is difference between Methods and Constructor?
A constructor is a member function of a class that is used to create objects of that
class. It has the same name as the class itself, has no return type, and is invoked using
the new operator.
A method is an ordinary member function of a class. It has its own name, a return
type (which may be void), and is invoked using the dot operator.
28 What is passed by reference?
Objects are passed by reference.In java we can create an object pointing to a
particular location ie NULL location by specifying : <class name> <object
name>;and also can create object that allocates space for the variables declared
in that particular class by specifying
Syntax:<object name > = new <class name>();
29 What is Constructors in Java? What are its types?
A constructor is a special method that is used to initialize an object. The name of
the constructor and the name of the class must be the same. A constructor does not
have any return type. The constructor invoked whenever an object of its associated
class is created. It is called constructor because it creates the values for the data
fields of the class.
A constructor has same name as the class in which it resides. Constructor in
Java cannot be abstract, static, final or synchronized. These modifiers are not
allowed for constructors.
Class Car
{
String name;
String model;
Car() //Constructor
{
name=””;
model=””;}}
There are two types of Constructor
Default Constructor
Parameterized
constructor
Each time a new object is created at least one constructor will
be invoked. Car c=new Car(); //Default constructor invoked
Car c=new Car(name); //Parameterized constructor invoked

30 What is array? How to declare array and how to allocate the memory to for array?
Java array contains elements of similar data type. It is a data structure where we
store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
data_type array_name []; and to allocate the memory-
array_name=new data_type[size];where array_name represent name of the
array, new is a keyword used to allocate the memory for arrays, data_type specifies
the data type of array elements and size represents the size of an array. For
example:int a=new int[10];

31 Explain how to declare Two Dimensional array?


The two dimensional arrays are the arrays in which elements are stored in rows as
well as columns. For example:
The two dimensional array can be declared and initialized as follows
Syntax: data_type array_name=new data_type[size];For example: int a[][]=new int[3][3];
32 Whatis methodinjava? Howto define andcallthemethod?
Method is a programming construct used for grouping the statement together
to build a function. There are two ways by which the method is handled.
1. Defining a method 2. Calling a method
Here is example that helps to understand the concept of method defining and
calling. public class methDemo {
public static void main(String
args[]) { int a=10;int b=20;int
c=sum(a,b);
System.out.println(“The sum of “+a”+” and “+b+” is=”+c);
}
public static int sum(int num1,int num2)
{
int ans=num1+num2;
return ans;}}

33 What are public static void main(String args[]) and System.out.println() ?


Public keyword is an access specifier. Static allows main() to be called without
having to instantiate a particular instance of class. Void does not return any value.
Main() is the method where java application begins.String args[] receives any
command line arguments during runtime.System is a predefined class that
provides access to the system. Out is output stream connected to console.println
displays the output.
34 What are types of Constructors?
Default Constructor, Parameterized Constructor, Copy Constructors
35 What's the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which is not allowed in an
interface. With abstract classes, you have to inherit your class from it and Java
does not allow multiple inheritance. On the other hand, you can implement multiple
interfaces in your class.
36 Explain about Static?
When a member is declared as static it can be accessed before any objects of its
class are created and without any reference to any object. these are global
variables, no copy of these variables
can be made. static can also be declared for methods. and cannot refer to this or
super.
37 List any four Java Doc comments. [NOV/DEC 2011]
A Javadoc comment is set off from code by standard multi-line comment tags /* and
*/. The opening tag, however, has an extra asterisk, as in /**.The first paragraph is
a description of the method documented. Following the description are a varying
number of descriptive tags, signifying: The parameters of the method
(@param),What the method returns (@return) and any exceptions the method may
throw (@throws)
38 What are the access specifiers/modifiers for classes in Java?
Java Access Specifiers (also known as Visibility Specifiers) regulate access to
classes, fields and methods in java. These specifiers determine whether a field or
method in c lass, can be used or invoked by another method in another class or
sub-class. Access Specifiers can be used to restrict access.There are 4 types of
java access modifiers: Private, Default, Protected and Public
39 What is a package?
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package. There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
40 What is static methods in Java?
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 Static method can access static data member and can change the value of it.
 There are two main restrictions for the static method is that the static
method cannot use non static data member or call non-static method
directly.
41 What are the control flow statements in java?
A programming language uses control statements to control the flow of execution
of program based on certain conditions. These are used to cause the flow of
execution to advance and branch based on changes to the state of a program.
Java‟ s Selection statements:
• if
• if-else
• nested-if
• if-else-if
• switch-case
• jump – break, continue, return
These statements allow you to control the flow of your program‟ s execution
based upon conditions known only during run time.
42 What is static variables in Java?
The static keyword in java is used for memory management mainly. We can apply
java static keyword with variables, methods, blocks and nested class. The static
keyword belongs to the class than instance of the class. If you declare any variable
as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees, college name of
students etc. The static variable gets memory only once in class area at the time of
class loading. Advantage - It makes your program memory efficient (i.e it saves
memory).
UNIT II INHERITANCE AND INTERFACES
Inheritances-Super class and Sub Class-Types of Inheritance-Types of Relationships- The Abstract
Class, CLASSPATH; Interface, Defining an Interface, Interfaces versus Abstract Classes-Extending
and Implementing Interfaces-Array Lists-Strings.

UNIT-II / PART-A
1 What is meant by Inheritance and what are its advantages?
Inheritance is a relationship among classes, wherein one class shares the structure or
behavior defined in another class. This is called Single Inheritance. If a class
shares the structure or behavior from multiple classes, then it is called Multiple
Inheritance. Inheritance defines “is-a” hierarchy among classes in which one
subclass inherits from one or more generalized super classes. The advantages of
inheritance are reusability of code and accessibility of variables and methods of the
super class by subclasses.
2 Brief about super ( ).
This is used to initialize constructor of base class from the derived class and also
access the variables of base class like super.i = 10.
3 What is the difference between superclass and subclass?
A super class is a class that is inherited whereas sub class is a class that does the
inheriting.
4 Differentiate between a Class and an Object?
The Object class is the highest-level class in the Java class hierarchy. The Class
class is used to represent the classes and interfaces that are loaded by a Java
program. The Class class is used to obtain information about an object's design. A
Class is only a definition or prototype of real life object. Whereas an object is an
instance or living representation of real life object. Every object belongs to a class
and every class contains one or more related objects.
5 Define super class and subclass?
Super class is a class from which another class inherits.Subclass is a class that
inherits from one or more classes.
6 What are the four types of access modifiers?
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
7 What is protected class in Java?
A private member is only accessible within the same class as it is declared. A
member with no access modifier is only accessible within classes in the same
package. A protected member is accessible within all classes in the same package
and within subclasses in other packages.
8 What is protected function?
Protected members that are also declared as static are accessible to any
friend or member function of a derived class. Protected members that are not
declared as static are

accessible to friends and member functions in a derived class only through


a pointer to, reference to, or object of the derived class.
9 What is protected method?
A protected method can be called by any subclass within its class, but not by
unreleated classes. Declaring a method protected defines its access level. The
other options for declaring visibility are private and public. If undeclared, the
default access level is package.
10 What is final modifier?
The final modifier keyword makes that the programmer cannot change the value
anymore. The actual meaning depends on whether it is applied to a class, a
variable, or a method.
final Classes- A final class cannot have subclasses.
final Variables- A final variable cannot be changed once it is
initialized. final Methods- A final method cannot be overridden
by subclasses.
11 What is a constructor in a class?
In class-based object-oriented programming, a constructor is a special type of
subroutine called to create an object. It prepares the new object for use,
often accepting arguments that the constructor uses to set required member
variables.
12 Why creating an object of the sub class invokes also the constructor of the
super class? When inheriting from another class, super() has to be called first in
the constructor. If not, the compiler will insert that call. This is why super
constructor is also invoked when a Sub object is created. This doesn't create two
objects, only one Sub object. The reason to have super constructor called is that if
super class could have private fields which need to be initialized by its
constructor.
13 What is an Abstract Class?
Abstract class is a class that has no instances. An abstract class is written with the
expectation that its concrete subclasses will add to its structure and behavior,
typically by implementing its abstract operations.
14 What are inner class and anonymous class?
Inner class: classes defined in other classes, including those defined in methods are
called inner classes. An inner class can have any accessibility including private.
Anonymous class: Anonymous class is a class defined inside a method without a
name and is instantiated and declared in the same place and cannot have explicit
constructors.
15 What is an Interface?
Interface is an outside view of a class or object which emphasizes its abstraction
while hiding its structure and secrets of its behavior.
16 What is a base class?
Base class is the most generalized class in a class structure. Most applications
have such root classes. In Java, Object is the base class for all classes.

17 What is meant by Binding, Static binding, Dynamic binding?


Binding: Binding denotes association of a name with a class. Static binding: Static
binding is a binding in which the class association is made during compile
time. This is also called as Early binding. Dynamic binding: Dynamic binding is a
binding in which the class association is not made until the object is created at
execution time. It is also called as Late binding.
18 What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at
runtime and dynamically manipulate at run time. This is supported using Reflection
API with built-in classes like Class, Method, Fields, Constructors etc. Example:
Using Java Reflection API we can get the class name, by using the getName
method.
19 What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with
instances of the class's outer class. A static inner class does not have any
object instances.
20 What is the difference between abstract class and interface?
ABSTRACT CLASS INTERFACE
1.Abstract class must have at All the methods declared
least one abstract method and inside an interface are
others may be concrete or abstract
abstract
2. In abstract class, key word Interface we need not use that
abstract must be used for the keyword for the methods.
methods
3. Abstract class must have subclassesInterface can‟ t have subclasses
21 Can you have an inner class inside a method and what variables can you
access?
Yes, we can have an inner class inside a method and final variables can be accessed.
22 What is interface and state its use?
Interface is similar to a class which may contain method‟ s signature only but not
bodies and it is a formal set of method and constant declarations that must be
defined by the class that implements it. Interfaces are useful for: a) Declaring
methods that one or more classes are expected to implement b) Capturing
similarities between unrelated classes without forcing a class relationship. c)
Determining an object‟ s programming interface without revealing the actual body
of the class.
23 Difference between class and interface.
CLASS INTERFACE
1.Class are used to create new Interface are used to create new
reference types reference types
2. A class is a collection of An interface has fully abstract methods
fields and methods that i.e. methods with nobody
operate on fields
3. Class can be instantiated Interface can never be instantiated
24 What is extending interface?
An interface can extend another interface in the same way that a class can extend
another class. The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.
Syntax: interface
interface_name{ Public void
method1():
Public void method2(): }
25 What modifiers may be used with top-level class?
Public, abstract and final can be used for top-level class.
26 What are the methods provided by the object class?
The Object class provides five methods that are critical when writing
multithreaded Java programs:
 notify
 notify All
 wait (three versions)
27 Define Package.
To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to
the specified package. The package statement defines a name space in which
classes are stored. If you omit the package statement, the class names are put into
the default package, which has no name.
28 How interfaces can be extended?
One interface can inherit another by use of the keyword extends. The syntax is the
same as for inheriting classes. When a class implements an interface that inherits
another interface, it must provide implementations for all methods required by the
interface inheritance chain.
29 Define Array list class.
The ArrayList class extends AbstractList and implements the List interface.
ArrayList is a generic class that has this declaration:
class ArrayList<E>
Here, E specifies the type of objects that the list will hold.
An ArrayList is a variable-length array of object references. That is, an ArrayList
can dynamically increase or decrease in size. Array lists are created with an initial
size. When this size is exceeded, the collection is automatically enlarged. When
objects are removed, the array can be shrunk.
UNITIII Exception and File Handling
Exception Handling: Definition of an Exception-Exception Classes- Common Exceptions;
Exception Handling Techniques-Throwing and catching exceptions-Creating own exceptions-
Streams-Byte Stream and Character stream-Files-Reading and writing files.
UNIT-III/ PART-A
1 What are the types of errors?
 Compile time errors
 Run time errors
2 Define Java Exception.
A Java exception is an object that describes an exceptional (that is, error) condition
that has occurred in a piece of code. When an exceptional condition arises, an
object representing that exception is created and thrown in the method that
caused the error.
3 State the five keywords in exception handling.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
4 Draw the exception hierarchy.
The top-level exception hierarchy is shown here:

5 Name any four java built in exceptions.


Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Arithmetic Exception Array index is out-of-
bounds. ArrayStoreException Assignment to an array element of an
incompatible type. ClassCastException Invalid cast
6 What is chained exception?
Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception. For example, consider a
situation in which a method throws an ArithmeticException because of an
attempt to divide by zero but the actual cause of exception was an I/O error which
caused the divisor to be zero.

7 Compare throw and throws.


 Throw is used to throw an exception & throws is used to declare an exception.
 Throw is used in method implementation & throws is used in method signature.
 Using throw keyword we can throw only 1 exception at a time & throws
can declare multiple exceptions at a time.
8 What is the use of try and catch exception?
Try-catch block is used for exception handling in the progam code. try is the start
of the block and catch is at the end of try block to handle the exceptions. A
Program can have multiple catch blocks with a try and try-catch block can be
nested also. catch block requires a parameter that should be of type Exception.
9 What is the use of finally exception?
Finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that
will not get closed, so we can use finally block. finally block gets executed always,
whether exception occurrs or not.
10 How to write custom exception in Java?
Extend Exception class or any of its subclasses to create our custom exception
class. The custom exception class can have its own variables and methods and one
can use to pass error codes or other exception related information to the exception
handler.
11 What is OutOfMemoryError in Java?
OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it‟ s
thrown by JVM when it ran out of heap memory.
12 What is difference between final, finally and finalize in Java?
Final and finally are keywords in java whereas finalize is a method.
Final keyword can be used with class variables so that they can‟ t be
reassigned, with class to avoid extending by classes and with methods to avoid
overriding by subclasses.
Finally keyword is used with try-catch block to provide statements that will
always gets executed even if some exception arises, usually finally is used to
close resources. finalize() method is executed by Garbage Collector before
the object is destroyed, it‟ s great
way to make sure all the global resources are closed. Out of the three, only
finally is related to java exception handling.
13 What happens when exception is thrown by main method?
When exception is thrown by main() method, Java Runtime terminates the
program and print the exception message and stack trace in system console.
14 Can we have an empty catch block?
We can have an empty catch block but it‟ s the example of worst programming.
We should never have empty catch block because if the exception is caught by that
block, we will have no information about the exception and it will be a nightmare
to debug it.
15 How Java Exception Hierarchy categorized?
Java Exceptions are hierarchical and inheritance is used to categorize different
types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy
and it has two child objects – Error and Exception. Exceptions are further divided
into checked exceptions and runtime exception.
16 What are input and output streams?
An I/O Stream represents an input source or an output destination. A stream can
represent many different kinds of sources and destinations, including disk files,
devices, other programs, and memory arrays.
17 What is a byte stream in java?
Programs use byte streams to perform input and output of 8-bit bytes. All byte
stream classes are descended from InputStream and OutputStream.
There are many byte stream classes. The file I/O byte streams,
are FileInputStream and FileOutputStream.
19 Define stream.
A stream can be defined as a sequence of data. There are two kinds of Streams
 InputStream − The InputStream is used to read data from asource.
 OutputStream − The OutputStream is used for writing data to a destination.
20 What is character stream?
Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most
frequently used classes are, FileReader and FileWriter.
21 What are directories in Java?
A directory is a File which can contain a list of other files and directories. You use
File object to create directories, to list down files available in a directory.
22 What are the two useful methods to create directories?
There are two useful File utility methods, which can be used to create directories
 The mkdir( ) method creates a directory, returning true on success and
false on failure. Failure indicates that the path specified in the File object
already exists, or that the directory cannot be created because the entire
path does not exist yet.
 The mkdirs() method creates both a directory and all the parents of the
directory.
23 State the use of java.io.Console.
The java.io.Console class which provides convenient methods for reading input
and writing output to the standard input (keyboard) and output streams (display)
in command-line.
24 What is the use of java console class?
The Java Console class is be used to get input from console. It provides methods to
read texts and passwords. If you read password using Console class, it will not be
displayed to the user. The java.io.Console class is attached with system console
internally.
25 State the classes used to read file in java.
The classes are:
 FileReader for text files in your system's default encoding
 FileInputStream for binary files and text files that contain 'weird' characters.
UNIT-IV / PART-A
1 How Threads are created in Java?
Threads are created in two ways. They are by extending the Thread class and by
implementing Runnable interface.
2 Define Thread?
A thread is a single sequential flow of control within program. Sometimes, it is
called an execution context or light weight process. A thread itself
is not a program. A thread cannot run on its own. Rather, it runs within a
program. A program can be divided into a number of packets of code, each
representing a thread having its own separate flow of control.
3 What is Multi-threading?
Multithreading is a conceptual programming concept where a program(process) is
divided into two or more subprograms(process), which can be implemented at the
same time in parallel. A multithreaded program contains two or more parts that
can run concurrently. Each part of such a program is called a thread, and each
thread defines a separate path of execution.
4 What is meant by Multitasking?
Multitasking, in an operating system, is allowing a user to perform more than one
computer task (such as the operation of an application program) at a time. The
operating system is able to keep track of where you are in these tasks and go from
one to the other without losing information. Multitasking is also known as
multiprocessing.
5 Difference between multi-threading and multi-tasking?
Multi-threading Multi-tasking
In any single process, multiple threads is It refers to having multiple
allowed and again, can run (programs, processes, tasks, threads)
simultaneously. running at the same time.
It is sharing of computing resources(CPU,
It is sharing of computing resources memory, devices, etc.) among processes
among threads of a single process.
6 What do you mean by Thread
Scheduling?
Execution of multiple threads on a single CPU in some order is called scheduling.
The Java runtime environment supports a very simple, deterministic scheduling
algorithm called fixed- priority scheduling. This algorithm schedules threads on the
basis of their priority relative to other Runnable threads.
7 What is Thread Pool?
A thread pool is a managed collection of threads that are available to perform
tasks. Thread pools usually provide:
 Improved performance when executing large numbers of tasks due to
reduced per-task invocation overhead
 A means of bounding the resources, including threads, consumed when
executing a collection of tasks.
8 What is Synchronization thread?
When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread
synchronization.
9 What is thread priority?
Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled. Java priorities are in the range between
MIN_PRIORITY(a constant of 1) and MAX_PRIORITY( a constant of 10). By default,
every thread is given priority NORM_PRIORITY(a constant of 5)
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread priorities
cannot guarantee the order in which threads execute and very much platform
independent.
10 List out the methods of object class to perform inter thread communication?
 wait() – This method make the current thread to wait until another
thread invokes the notify() method.
 notify() – This method wakes up a thread that called wait() on same object.
 notifyAll() – This method wakes up all the thread that called wait() on
same object. Wakes up all threads that are waiting on this object‟ s
monitor.
Above all three methods have been implemented as final method in Object class,
so that they are available in all the classes in java world.
11 What are the various states of a thread?
The following figure shows the states that a thread can be in during its life
and illustrates which method calls cause a transition to another state.

12 Why do we need run() and start() method both? Can we achieve it with only run method?
 The separate start() and run() methods in the Thread class provide two ways to
create threaded programs. The start() method starts the execution of the new
thread and calls the run() method. The start() method returns immediately and
the new thread normally continues until the run() method returns.
 The Thread class' run() method does nothing, so sub-classes should override the
method with code to execute in the second thread. If a Thread is instantiated
with a Runnable argument, the thread's run() method executes the run() method
of the Runnable object in the new thread instead.
 Depending on the nature of your threaded program, calling the Thread run() method
directly can give the same output as calling via the start() method, but in the
latter case the code is actually executed in a new thread.
13 What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the
back ground doing the garbage collection operation for the java runtime system.
setDaemon method is used to create a daemon thread.
14 Write short note on isAlive() and join()?
isAlive() and join() methods are used to determine whether a thread has finished
or not.
First, you can call isAlive() on the thread. This method is defined by Thread, and
its general form is:
final Boolean isAlive()
The isAlive() method returns true if the thread upon which it is called is still
running. It returns false otherwise.
While isAlive() is occasionally useful, the method that you will more
commonly use to wait for a thread to finish is called join(). The general form is:
final void join() throws InterruptedException
This method waits until the thread on which it is called terminates
15 Define Deadlock and When it will occur?
Deadlock describes a situation where two or more threads are blocked forever, waiting
for each
other. Deadlock occurs when multiple threads need the same locks but obtain them
in different order. A Java multithreaded program may suffer from the deadlock
condition because the synchronized keyword causes the executing thread to
block while waiting for the lock, or monitor, associated with the specified object.
16 Define thread group?
Every Java thread is a member of a thread group. Thread groups provide a
mechanism for collecting multiple threads into a single object and manipulating
those threads all at once, rather than individually. For example, you can start
or suspend all the threads within a group with a single method call.
17 Why do we need generics in Java?
Code that uses generics has many benefits over non-generic code: Stronger
type checks at compile time. A Java compiler applies strong type checking to
generic code and issues errors if the code violates type safety. Fixing compile-time
errors is easier than fixing runtime errors, which can be difficult to find.
18 State the two challenges of generic programming in virtual machines.
 Generics are checked at compile-time for type-correctness. The generic type
information is then removed in a process called type erasure.
 Type parameters cannot be determined at run-time
19 When to use bounded type parameter?
There may be times when you want to restrict the types that can be used as type
arguments in a parameterized type. For example, a method that operates on numbers
might only want to accept instances of Number or its subclasses. This is what bounded
type parameters are for.
20 What is daemon thread?
A daemon thread is a thread that does not prevent the JVM from exiting when the
program finishes but the thread is still running. An example for a daemon thread is the
garbage collection.
21 What is erasure in Java?
Generics were introduced to the Java language to provide tighter type checks at
compile time and to support generic programming. To implement generics, the
Java compiler applies
UNIT V Scala Programming

Overview-Scala versus Java-Features of Scala-Environment Setup-Basic Syntax-Data


Types- Variables-classes & Objects-Access Modifiers-Operators-Control statements and
Looping Statements- Strings-Arrays-Functions-Exceptions handling.
Unit –V/Part A
1 What is Scala?
Scala is a Java-based Hybrid programming language which is the fusion of both
Functional and Object-Oriented Programming Language features. It can
integrate itself with Java Virtual Machine and compile the code written.

2 Explain how Scala is both Functional and Object-oriented Programming Language?

Scala treats every single value as an Object which even includes Functions. Hence,
Scala is the fusion of both Object-oriented and Functional programming features.
3 Write a few Frameworks of Scala
Some of the Frameworks supported by Scala are as follows:

o Akka Framework
o Spark Framework

o Play Framework

o Scalding Framework
o Neo4j Framework
o Lift Framework
o Bowler Framework

4 Explain Streams in Scala.


In simple words, we define Stream as a Lazy list which evaluates the elements only
when it needs to. This sort of lazy computation enhances the Performance of the
program.
5 Mention the types of Variables in Scala? And What is the difference between them?

The Variables in Scala are mainly of two types:

Mutable Variables

 Declare Mutable Variables by using the var keyword.


 The values in the Mutable Variables support

Changes Immutable Variables

 declare Immutable Variables using the val keyword.


 The values in Immutable Variables do not support changes

6 Write down the advantages of scala programming.

Some of the major Advantages of Mention the Advantages of Scala Scala are as follows:
o It is highly Scalable
o It is highly Testable
o It is highly Maintainable and Productive
o It facilitates Concurrent programming
o It is both Object-Oriented and Functional
o It has no Boilerplate code
o Singleton objects are a cleaner solution than Static
o Scala Arrays use regular Generics
o Scala has Native Tuples and Concise code

7 Explain the Operators in Scala

The following are the Operators in Scala:

o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators

8 What is Recursion tail in Scala?

„Recursion‟ is a function that calls itself. For example, a function „A‟ calls function
„B‟ , which calls the function „C‟ . It is a technique used frequently in Functional
programming. In order for a Tail recursive, the call back to the function must be
the last function to be performed.

9 Explain the use of Tuples in Scala?

Scala tuples combine a Finite number of items together so that the programmer can Pass a tuple
around as a Whole. Unlike an Array or List, a tuple is Immutable and can hold objects with
different Datatypes.
10 How is a Class different from an Object?

Class combines the data and its methods whereas an Object is one particular Instance in a class.
11 What are Higher-order functions?

A Higher-order function is a function that does at least one of the following: takes one or more
Functions as Arguments, returns a Function as its result.
12 Explain the scope provided for variables in Scala.
Ans: There are three different scopes depending upon their use. Namely:
Fields:
 Fields are variables declared inside an object and they can be accessed anywhere
inside the program depending upon the access modifiers. Fields can be declared
using var as well as val.
Method Parameters:
 Method parameters are strictly Immutable. Method parameters are mainly used to
Pass values to the methods. These are accessed inside a method, but it is possible to
access them from outside the method provided by a Reference.
Local Variables:
 Local variables are declared inside a method and they are accessible only inside the
method. They can be accessed if you return them from the method.
13 Explain implicit classes with syntax

Implicit classes allow Implicit conversations with the class’s Primary constructor when the
class is in scope. Implicit class is a class marked with the “implicit” keyword. This feature
was introduced in with Scala 2.10 version.
1//Syntax:
2 object {
3 implicit class Data type) {
4 def Unit = xyz
5 }
6 }
14 Mention the Identifiers in Scala.

There are four types of Scala Identifiers:

 Alphanumeric identifiers
 Operator identifiers
 Mixed identifiers
 Literal identifiers
15 Why Scala prefers Immutability?

Scala prefers Immutability in design and in many cases uses it as default. Immutability can help
when dealing with Equality issues or Concurrent programs.
16 What are the Scala variables?

Values and variables are two shapes that come in Scala. A value variable is constant and cannot be
changed once assigned. It is immutable, while a regular variable, on the other hand, is mutable,
and you can change the value.

The two types of variables are

var myVar : Int=0;

val myVal: Int=1;


17 Mention the difference between an object and a class ?

A class is a definition for a description. It defines a type in terms of methods and composition of
other types. A class is a blueprint of the object. While, an object is a singleton, an instance of a
class which is unique. An anonymous class is created for every object in the code, it inherits from
whatever classes you declared object to implement.
18 What is the difference between var and value?

In scala, you can define a variable using either a, val or var keywords. The difference between val
and var is, var is much like java declaration, but val is little different. We cannot change the
reference to point to another reference, once the variable is declared using val. The variable defined
using var keywords are mutable and can be changed any number of times.
19 How can you format a string?

To format a string, use the .format () method, in scala you can

use Val formatted= “%s %i”.format (mystring.myInt)


20 What is the difference between Scala and Java?

Answer: The difference between Scala and Java include the following.

Scala Java
All the values in Scala are treated as All the values in Java are not treated as Objects.
Objects.
It supports closures It does not support closures
It has Type-inference It does not have Type-inference
It supports nested functions It does not support nested functions
It supports concurrency It does not concurrency
It has different traits It does not support traits
It has Domain-Specific Language or DSL It does not have Domain Specific Language or DSL
support. support.
21 What are the procedures to compile Scala code?

The procedure to compile Scala Code starts with the writing of the Code in Scala IDE or Scala
REPL, which is later converted into the Byte Code and thereby transferred to Java Virtual
Machine or JVM for compilation purpose.
22 Define Null, Nill, None, and Nothing in Scala?

Null, Nill, None, and Nothing in Scala can be defined as follows.

1. Null denotes the absence of a value.


2. Nil represents the end of a List.
3. None is the value of an option that has no value.
4. Nothing is the lowest type in the type system.

23 What are the different Loops in Scala?

There are three different types of Loops in Scala.

1. While Loop helps in repeating the statement or group of the statement when
the condition comes out to be true, this way, it tests the conditions before the
execution of the Loop body.
2. Do-While helps in testing the condition at the end of the Loop body.
3. For, helps in executing a sequence of statement number of times and
abbreviates the code that manages in the Loop variable.
4. Break acts as a Loop control statement that terminates the Loop statement
and transfers the execution to the statement that soon follows the Loop.

24 What are the different String Methods?

There are five different String Methods which include,

String trim(): It returns the copy of the string with leading and trailing of the whitespace omitted.

1. String to Uppercase: It converts all of the features in the String to the


Uppercase using the given Locale rules.
2. Char[] to CharArray(): It converts the string to a new character array.
3. String[] split(String regext): It splits the string around the matches
of the given regular expression.
4. Int length(): It returns the length of the string.

25 What is Pattern Matching in Scala?

Pattern Matching in Scala consists of various sequences of alternatives that start with the Keyword
case. Each of the alternatives available uses Pattern and Expressions. Scala evaluates these
Patterns when they match, and the arrow symbol "=>" is used to separate it from the expressions.
16 MARKS WITH
ANSWERS UNIT
1. Explain OOP Principles. I
OOP is defined as object oriented programming.
Basic Concepts of OOP
Class
Object
Method
Inheritance
Data Abstraction
Data
Encapsulation
Polymorphism
Message Passing
Defining the Class:
A class is defined by the user is data type with the template that helps in defining the properties.
Once the class type has been defined we can create the variables of that type using declarations that
are similar to the basic type declarations. In java instances of the classes which are actual objects
Eg:
classclassname [extends superclassname]
{
[fields declarations;]
[methods declaration;]
}
Field Declaration
Data is encapsulated in a class by placing data fields inside the body of the class definition. These
variables are called as instance variables.
Class Rectangle
{
int
length;
int width;
}
Method Declaration
A Class with only data fields has no life, we must add methods for manipulating the data contained in the
class. Methods are declared inside the class immediate after the instance variables declaration.
Eg:
class Rectangle
{
int length; //instance
variables int width;
Void ge
tData(int x, int y) // Method Declartion
{
Length
=x;
Width = y;
}
}
Creating the objects:
An object in java essentially a block of memory, which contains space to store all the instance
variables. Creating an object is also referred as instantiating an object. Object in java are created using
the new operator.
Eg:
Rectangle rec1;
// Declare the object
Rec1 = new Rectangle //instantiate the object
The above statements can also be combined as follows
Rectangle rec1 = new Rectangle;
Methods:
Methods are similar to functions or procedures that are available in other programming languages.
Difference B/w methods and functions
Difference b/w method and function is method declared inside class, function can be declared anywhere
inside are outside class
Writing methods in java
if we had to repeatedly output a header such as:

System.out.println("GKMCET");
System.out.println ("Allapakkam");
System.out.println ("Meppedu Road");
We could put it all in a method like this:
public
static void printHeader()
{
System.out.println("GKMCET");
System.out.println("Allapakkam");
System.out.println("Meppedu Road");
}
Inheritance:
Inheritance is the process of forming a new class from an existing class or base class. The base class is also
known as parent class or super class, the new class that is formed is called derived class.
Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code
size(reusability) of the program, which is an important concept in object oriented programming.
Data Abstraction:
Data abstraction increases the power of programming language by creating user defined data types. Data
abstraction also represents the needed information in the program without presenting the details.
Data Encapsulation:
Data encapsulation combines data and functions into a single unit called class. When using Data
Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the
class. Data encapsulation enables the important concept of data hiding possible.
Polymorphism:
Polymorphism allows routines to use variables of different types at different times. An operator or
function can be given different meanings or functions. The ability of objects to respond differently to the
same message or function call.
Message passing:
A message passing system provides primitives for sending and receiving messages using objects.
These primitives may by either synchronous or asynchronous or both.

2. Explain the features of java programming language ?


Simple :

Java is Easy to write and more readable

Java has a concise, cohesive set of features that makes it easy to learn and use.

Secure :

Java program cannot harm other system thus making it secure.


Java provides a secure means of creating Internet applications.

Java provides secure way to access web applications.

Portable :

Java programs can execute in any environment for which there is a Java run-time system.(JVM)

Java programs can be run on any platform (Linux,Window,Mac)

Java programs can be transferred over world wide web (e.g applets)

Object-oriented :

Java programming is object-oriented programming language.

Like C++ java provides most of the object oriented features.

Java is pure OOP. Language. (while C++ is semi object

oriented)

Robust :

Java encourages error-free programming by being strictly typed and performing run-time checks.

Multithreaded :
Java provides integrated support for multithreaded
programming. Architecture-neutral :
Java is not tied to a specific machine or operating system architecture.
Machine Independent i.e Java is independent of hardware .
Interpreted :
Java supports cross-platform code through the use of Java bytecode.
Bytecode can be interpreted on any platform by JVM.
High performance :
Bytecodes are highly optimized.
JVM can executed them much faster
. Distributed :
Java was designed with the distributed environment.
Java can be transmit,run over internet.
Dynamic :
Java programs carry with them substantial amounts of run-time type information that is used to verify and
resolve accesses to objects at run time.
3. Describe the Structure of Java Program ?

A package is a collection of classes, interfaces and sub-packages. A sub package contains collection of
classes, interfaces and sub-sub packages etc. java.lang.*;
package is imported by default and this package is known as default package.
Class is keyword used for developing user defined data type and every java program must start with a
concept of class.
"ClassName" represent a java valid variable name treated as a name of the class each and every class
name in java is treated as user-defined data type.
Data member represents either instance or static they will be selected based on the name of the class.
User-defined methods represents either instance or static they are meant for performing the
operations either once or each and every time.
Each and every java program starts execution from the main() method. And hence main() method is
known as program driver.
Since main() method of java is not returning any value and hence its return type must be void.
Since main() method of java executes only once throughout the java program execution and hence its
nature must be static.
Since main() method must be accessed by every java programmer and hence whose access specifier
must be public.
Each and every main() method of java must take array of objects of String.
Block of statements represents set of executable statements which are in term calling user-defined methods
are containing business-logic.
The file naming conversion in the java programming is that which-ever class is containing main() method,
that class name must be given as a file name with an extension .java.

4. Explain the concept of class in java?

A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

fields

methods

constructors
blocks

nested class and interface

Syntax to declare a class:


class <class_name>
{
field;
method;
}

Instance variable in Java

A variable which is created inside the class but outside the method, is known as instance variable. Instance
variable doesn't get memory at compile time. It gets memory at run time when object(instance) is created.
That is why, it is known as instance variable.

Method in Java

In java, a method is like function i.e. used to expose behavior of an object.

Advantage of Method

Code Reusability

Code Optimization

new keyword in

Java

The new keyword is used to allocate memory at run time. All objects get memory in Heap memory area.

class Student{
int id;//field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

5. Explain the concept of objects and how to create objects in java ?

An entity that has state and behavior is known as an object

An object has three characteristics:


state: represents data (value) of an object.

behavior: represents the behavior (functionality) of an object

identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the
external user. But, it is used internally by the JVM to identify each object uniquely.

Object is an instance of a class. Class is a template or blueprint from which objects

are created. So object is the instance(result) of a class.

Object Definitions:

Object is a real world entity.

Object is a run time entity.

Object is an entity which has state and behavior.

Object is an instance of a class.

Creating Objects

Using new keyword is the most basic way to create an object. This is the most
Common way to create an object in java.

public classNewKeywordExample
{
String name = "hello";
public static void main(String[] args)
{
NewKeywordExampleobj = new NewKeywordExample();
System.out.println(obj.name);
}
}

6. Explain Constructors with


examples. Constructor:
Constructors are the method. It is used to give initial values to instance variables of the objects.
Itis automatically called at the time of object creation.
Syntax :
Constructor name(arguments)
{
Statements;
Initial
values;
}
Rules:
A constructor has the same name as the class.
A class can have more than one constructor.
A constructor can take zero ,one ,or more parameters.
A constructor has no return value.
A construc
tor is always called with the new operator.
Example program:
Class complex:
{
Float
rp;
Float
ip;
Complex(float x,float y) //Defining Constructor
{
Rp=x;
Ip=y;
}
Void print()
{
System.out.println(“Real part”=rp);
System.out.println(“Imaginary part”+ip);
}
Void sum(complex a,complex b)
{
Rp=a.rp+b.rp;
Ip=a.ip=b.ip;
}
}
Class demo
{
Public static void main(str
ingargs[]);
{
Complex a,b,c;
a=new complex(5,6);
//Calling Constructor
b=new
complex(8,9); c=new
complex();
c.sum(a,b);
c.print();
}
}

7. Explain Packages in
detail. Packages
Packages are java‟s way of grouping a variety of classes and/or interfaces together. Packages are
container for the classes.
It is the header file in c++.
It is stored in a hierarichical manner.
If we want to use the packages in a class, we want to import it.
The two types of packages are:
System package.
User defined package.
Uses of Packages:
Packages reduce the complexity of the software because a large number of classes can be grouped into
a limited number of packages.

We can create classes with same name in different packages.Using packages we can hide classes.

We may like to use many of the classes contained in a package.it can be achieved by
Import packagename .classname
OR
Import packagename.*
Creating the package

To create our own packages


packagefirstpackage;// package declaration
public class FirstClass //class definition
{.....
(body of class)
.......}
The file is saved as FirstClass.java,located at firstpackage directory. when it is compiled .class file will
be created in same ditectory.
Access a package
The import statement can be used to search a list of packages for a particular class. The general form
of import statement for searching class is a as follows.

Import package1 [.package2] [.package3].classname;


Using the package
package package1 ;
public class classA
{
public void displayA()
{
System.out.println(“class A”);
}
}
Adding a class to package
Define the class and make it public
Place the package statement
Package P1
Before the class definition as follows
Package p1;
Public class
B Package
name
{
// body of B
}
Example:
Package
college Class
student
{
intregno;
String name;
Student(intr,stringna);
{
Regno=r
Name=na
}
Public void print()
{
System.out.println(“Regno”+regno )
;
System.out.println(“Name”+name );
}
}
Package Course
Class engineering
{
Intregno;
String branch;
String year;
Engineering(int r, string br, string yr)
{
Regno=br;
Branch=br;
Year=yr;
}
public void print()
{
Systems.out.println(“Regno”+regno);
Systems.out.println(“
Branch”+branch);
Systems.out.println(“Year”+year);
}
}

8. What is Array?.How to declare array?Discuss the methods under


Array Class.

An array is a data structure that stores a collection of values of the same type. You
access each individual value through an integer index.
Array Name [index]
Integer constant, variable, or expression
For Instance we can definean array name salary to represent a set of salaries of a group of employees.
A particular value is indicated by writing a number called index in brackets after the array name.
salary [10]
it represents the salary of the 10th employee.
Types of arrays
One dimensional arrays
Two dimensional arrays
One Dimensional
arrays
A list of items can be given one variable name using only one subscript and such a variable is called
single - subscripted of one dimensional array. The subscript can also start from 0. ie x[0]. If we want to
represent a set of five numbers, say (35,40,20,57,19) by an array variable number, then we have to
create the variable number as follows
int number [ ] = new int [5 ];
The value to the array elements can be assigned as follows
Number [0] =35;
Number [1] =40;
Number [2] =20;
Number [3] =57;
Number [4] =19;
This would cause the array number to store the values shown as follows;
 Creating an array
 Declaring the array
 Creating memory locations
 Putting values into the memory locations.

Array in java can be declared in two forms


Form 1
typearrayname [ ];
Form 2 type [ ] arrayname;
Creation of arrays
arrayname = new type [ size
]; Eg;
number = new int [5] ;
average = new float[10];
it is alsopossible to combine declaration and creation.
int number [ ] = new int [5];

Initialization of arrays
The final step is to put values into the array created. This process is known as initialization using the
array subscripts as shown below.
arrayname[subscript] = value ;
Eg
number[0] = 15;
we can also initialize by following way
typearrayname [ ] = { list of values }
Array Length
All array store the allocated size in an variable named length. We can obtain the length of array a using
a.length
Eg:
intasize = a.length;

Two Dimensional arrary:


Usage :
IntmyArray [ ] [ ];
myArray= new int [3]
[4];
OR
initmyArray [ ] [ ] = new int [3][4]
This creates a table that can store 12 integer values, four across and three down.
Strings:
Series of characters represents a string, and easiest way to represent the string is array
Eg:
Char charArray [ ] = new char [2] ;
charArray[0] = „j‟ ;
charArray[1] = „a‟ ;
String can be declared and created in the following way
stringstringname;
stringname = new string (“string”);
Operations on string
int m = stringname.length() //will return the length of the string
string city = “New” + “Delhi”// will return New Delhi

9. Explain in detail how to create methods in java ?


A Java method is a collection of statements that are grouped together to perform an operation
CreatingMethod
Considering the following example to explain the syntax of a method

Syntax

public static intmethodName(int a, int b) {


// body
}
Here,

public static − modifier

int − return type

methodName − name of the method

a, b − formal parameters

int a, int b − list of parameters

Method definition consists of a method header and a method body.

Syntax

modifierreturnTypenameOfMethod (Parameter List) {


// method body
}
The syntax shown above includes −

modifier − It defines the access type of the method and it is optional to use.

returnType − Method may return a value.

nameOfMethod − This is the method name. The method signature consists of the method name and
the parameter list.

Parameter List − The list of parameters, it is the type, order, and number of parameters of a method.
These are optional, method may contain zero parameters.

method body − The method body defines what the method does with the statements.

Method Calling
For using a method, it should be called. There are two ways in which a method is called i.e., method
returns a value or returning nothing (no return value).

When a program invokes a method, the program control gets transferred to the called method. This
called method then returns control to the caller in two conditions, when the return statement is
executed.it reaches the method ending closing brace

Following is the example to demonstrate how to define a method and how to call it

Example
publicclassExampleMinNumber{ pu
blicstaticvoid main(String[]args)
{ int a =11;
int b =6;
int c =minFunction(a, b);
System.out.println("Minimum Value = "+ c);
}
/** returns the minimum of two numbers */
publicstaticintminFunction(int n1,int n2)
{ int min;
if(n1 > n2)
min= n2;
else
min= n1;
return
min;
}
}

10. Explain static variable and static methods in java?

The static keyword in java is used for memory management. We can apply java static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:

 variable (also known as class variable)


 method (also known as class method)
 block
 nested class

1) Java static variable

If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not unique for each
object)

The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes program memory efficient (i.e it saves memory).

Example of static variable

class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n)
{ rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{ Student8 s1 = new
Student8(111,"Karan"); Student8 s2 = new
Student8(222,"Aryan"); s1.display();
s2.display();
}
}
2) Java static method

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an instance of a class.

static method can access static data member and can change the value of it.

Example of static method


//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change()


{ college = "BBDIT";
}
Student9(int r, String n)
{ rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9
(111,"K"); Student9 s2 = new
Student9 (222,"A"); Student9 s3 =
new Student9 (333,"S");

s1.display();
s2.display();
s3.display();
}
}

11. Explain the different categories of operators in java ?

Operator in java is a symbol that is used to perform operations.

There are many types of operators in java which are given below:

Unary Operator,

Arithmetic Operator,

Shift Operator,

Relational Operator,

Bitwise Operator,

Logical Operator,

Ternary Operator and

Assignment Operator.
UNIT –II

1. ExplainSingle Inheritance in Java

Single Inheritance is the simple inheritance of all, When a class extends another class(Only one class)
then we call it as Single inheritance.

The below diagram represents the single inheritance in java where Class B extends only one
class Class A.

Class B will be the Sub class and Class A will be one and only Super class.

Single Inheritance Example

publicclassClassA
{
publicvoiddispA()
{
System.out.println("disp() method of ClassA");
}
}
publicclassClassBextendsClassA
{
publicvoiddispB()
{
System.out.println("disp() method of ClassB");
}
publicstaticvoid main(Stringargs[])
{
//Assigning ClassB object to ClassB reference
ClassB b =newClassB();
//call dispA() method of ClassA
b.dispA();
//call dispB() method of ClassB
b.dispB();
}
}
2. How will you achieve multiple inheritance in java ?

Multiple Inheritance is nothing but one class extending more than one class.

Multiple Inheritance is basically not supported by many Object Oriented Programming languages
such as Java, Small Talk, C# etc.. (C++ Supports Multiple Inheritance).

As the Child class has to manage the dependency of more than one Parent class. But you can achieve
multiple inheritance in Java using
Interfaces.

3. Explain Multilevel Inheritance in java ?

In Multilevel Inheritance a derived class will be inheriting a parent class and as well as the derived
class act as the parent class to other class. As seen in the below diagram. ClassBinherits the property
of ClassA and again ClassB act as a parent for ClassC. In Short ClassAparent
for ClassB and ClassB parent for ClassC.

MultiLevel Inheritance Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}

4. Explain Hierarchical Inheritance in java ?

In Hierarchical inheritance one parent class will be inherited by many sub classes. As per the below
example ClassA will be inherited by ClassB, ClassC and ClassD.

ClassA will be acting as a parent class for ClassB, ClassC and ClassD.

Hierarchical Inheritance Example

public class
ClassA{ public void
dispA() {
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
public void dispB() {
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{ public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{ public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();

//Assigning ClassC object to ClassC reference


ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();

//Assigning ClassD object to ClassD reference


ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}

5. Explain abstract class in java with example?

A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A normal
class(non-abstract class) cannot have abstract methods.

Abstract class declaration


An abstract class outlines the methods but not necessarily implements all the methods.

//Declaration using abstract keyword


abstract class A{
//This is abstract method
abstract void myMethod();

//This is concrete method with body


voidanotherMethod(){
//Does something
}
}
A class derived from the abstract class must implement all those methods that are declared as
abstract in the parent class.

Abstract class cannot be instantiated which means you cannot create the object of it. To use this class,
you need to create another class that extends this this class and provides the implementation of abstract
methods

If a child does not implement all the abstract methods of abstract parent class, then the child class must
need to be declared abstract as well.

Example of Abstract class and method

abstract class
MyClass{ public void
disp(){
System.out.println("Concrete method of parent class");
}
abstract public void disp2();
}

class Demo extends


MyClass{ public void disp2()
{
System.out.println("overriding abstract method");
}
public static void main(String args[])
{ Demo obj = new Demo();
obj.disp2();
}}
6. How will you define interface in java?

Using the keyword interface, you can fully abstract a class‟ interface from its implementation. That is, using
interface, you can specify what a class must do, but not how it does it.

Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared
without any body. In practice, this means that you can define interfaces that don‟t make assumptions about
how they are implemented.

Once it is defined, any number of classes can implement an interface. Also, one class can implement any
number of interfaces.
To implement an interface, a class must create the complete set of methods defined by the interface.
However, each class is free to determine the details of its own implementation.

By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple methods”
aspect of polymorphism.

Interfaces are designed to support dynamic method resolution at run time. Normally, in order for a method to
be called from one class to another, both classes need to be present at compile time so the Java compiler can
check to ensure that the method signatures are compatible

Defining an Interface

An interface is defined much like a class. This is a simplified general form of an interface:

access interface name { return-type method-name1(parameter-list);

return-type method-name2(parameter-

list); type final-varname1 = value;

type final-varname2 = value;

return-type method-nameN(parameter-list);

type final-varnameN = value; }

When no access modifier is included, then default access results, and the interface is only available
to other members of the package in which it is declared. When it is declared as public, the interface
can be used by any other code.

7. Explain with example about implementation of interface ?

Once an interface has been defined, one or more classes can implement that interface.

To implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface.

The general form of a class that includes the implements clause looks like this:

classclassname [extends superclass] [implements interface [,interface...]]

{ // class-body }

If a class implements more than one interface, the interfaces are separated with a comma.

If a class implements two interfaces that declare the same method, then the same method will be used
by clients of either interface.
The methods that implement an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the interface definition

class Client implements Callback

{ public void callback(int p)

{ System.out.println("callback called with " + p); }

8. Explain with example how Interfaces can be extended ?

One interface can inherit another by use of the keyword

extends. The syntax is the same as for inheriting classes.

When a class implements an interface that inherits another interface, it must provide

implementations for all methods defined within the interface inheritance chain.

EXAMPLE

interface A

{ void

meth1(); void

meth2();

interface B extends A { void meth3(); }

MyClass implements B {

public void meth1()

{ System.out.println("Implement meth1()."); }

public void meth2() { System.out.println("Implement meth2()."); }

public void meth3() { System.out.println("Implement meth3()."); }

} classIFExtend {

public static void main(String arg[]) {

MyClassob = new MyClass();

ob.meth1();

ob.meth2();

ob.meth3(); }

}
12. Explain the methods in array list with example ?

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and
implements List interface.

The important points about Java ArrayList class are:

Java ArrayList class can contain duplicate elements.

Java ArrayList class maintains insertion order.

Java ArrayList class is non synchronized.

Java ArrayList allows random access because array works at the index basis.

In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.

Hierarchy of ArrayList class

As shown in above diagram, Java ArrayList class extends AbstractList class which implements List
interface. The List interface extends Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration

Let's see the declaration for java.util.ArrayList class.

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable


, Serializable

Constructors of Java ArrayList


Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection It is used to build an array list that is initialized with


c) the elements of the collection c.
ArrayList(int It is used to build an array list that has the
capacity) specified initial capacity.

Methods of Java ArrayList


Method Description

void add(int index, Object It is used to insert the specified element at the
element) specified position index in a list.

booleanaddAll(Collection It is used to append all of the elements in the


c) specified collection to the end of this list, in the
order that they are returned by the specified
collection's iterator.

void clear() It is used to remove all of the elements from this


list.

intlastIndexOf(Object o) It is used to return the index in this list of the last


occurrence of the specified element, or -1 if the
list does not contain this element.

Object[] toArray() It is used to return an array containing all of the


elements in this list in the correct order.

Object[] toArray(Object[] It is used to return an array containing all of the


a) elements in this list in the correct order.

boolean add(Object o) It is used to append the specified element to the


end of a list.

booleanaddAll(int It is used to insert all of the elements in the


index, Collection c) specified collection into this list, starting at the
specified position.

Object clone() It is used to return a shallow copy of an ArrayList.

intindexOf(Object o) It is used to return the index in this list of the first


occurrence of the specified element, or -1 if the
List does not contain this element.

void trimToSize() It is used to trim the capacity of this ArrayList


instance to be the list's current size.
Java ArrayList
Example import
java.util.*; class
TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext())
{ System.out.println(itr.next());
} } }

13. Explain String Class and its methods with examples ?


String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java,
string is an immutable object which means it is constant and can cannot be changed
once it has been created.

Creating a String

There are two ways to create a String in Java

1. String literal
2. Using new keyword

String literal

In java, Strings can be created like this: Assigning a String literal to a String instance:

String str1 ="Welcome";


String str2 ="Welcome";

Using New Keyword

String str1 = new String("Welcome");


String str2 = new String("Welcome");

In this case compiler would create two different object in memory having the same string.

A Simple Java String Example

public class Example{


public static void main(String args[]){
//creating a string by java string literal
String str = "Beginnersbook";
chararrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string
str2 String str2 = new String(arrch);
//creating another java string str3 by using new keyword
String str3 = new String("Java String Example");
//Displaying all the three strings
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Java String Methods

Here are the list of the methods available in the Java String class.

1. charcharAt(int index): It returns the character at the specified index. Specified index value should
be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>=
length of String.
2. boolean equals(Object obj): Compares the string with the specified string and returns true if
both matches else false.
3. booleanequalsIgnoreCase(String string): It works same as equals method but it doesn‟t consider
the case while comparing strings. It does a case insensitive comparison.
4. intcompareTo(String string): This method compares the two strings based on the Unicode value of
each character in the strings.
5. intcompareToIgnoreCase(String string): Same as CompareTo method however it ignores the case
during comparison.
6. booleanstartsWith(String prefix, int offset): It checks whether the substring (starting from the
specified offset index) is having the specified prefix or not.
7. booleanstartsWith(String prefix): It tests whether the string is having specified prefix, if yes then it
returns true else false.
8. booleanendsWith(String suffix): Checks whether the string ends with the specified suffix.
9. inthashCode(): It returns the hash code of the string.
10. intindexOf(intch): Returns the index of first occurrence of the specified character ch in the string.
11. intindexOf(intch, intfromIndex): Same as indexOf method however it starts searching in the string
from the specified fromIndex.
12. intlastIndexOf(intch): It returns the last occurrence of the character ch in the string.
13. intlastIndexOf(intch, intfromIndex): Same as lastIndexOf(intch) method, it starts search from
fromIndex.
14. intindexOf(String str): This method returns the index of first occurrence of specified substring str.
15. intlastindexOf(String str): Returns the index of last occurrence of string str.
16. String substring(intbeginIndex): It returns the substring of the string. The substring starts with the
character at the specified index.
17. String substring(intbeginIndex, intendIndex): Returns the substring. The substring starts with
character at beginIndex and ends with the character at endIndex.
18. String concat(String str): Concatenates the specified string “str” at the end of the string.
19. String replace(char oldChar, char newChar): It returns the new updated string after changing all the
occurrences of oldChar with the newChar.
20. boolean contains(CharSequence s): It checks whether the string contains the specified sequence of
char values. If yes then it returns true else false. It throws NullPointerExceptionof „s‟ is null.
21. String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined
by specified locale.
22. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
23. public String intern(): This method searches the specified string in the memory pool and if it is
found then it returns the reference of it, else it allocates the memory space to the specified string and
assign the reference to it.
24. publicbooleanisEmpty(): This method returns true if the given string has 0 length. If the length of
the specified Java String is non-zero then it returns false.
25. public static String join(): This method joins the given strings using the specified delimiter
and returns the concatenated Java String

UNIT III
1. Explain how exception is handled in java?
Exception is an error event that can happen during the execution of a program and disrupts its normal flow
Java being an object oriented programming language, whenever an error occurs while executing a
statement, creates an exception object and then the normal flow of the program halts.
When the exception occurs in a method, the process of creating the exception object and handing it over to
runtime environment is called “throwing the exception”..
Once runtime receives the exception object, it tries to find the handler for the exception. Exception
Handler is the block of code that can process the exception object
The handler is said to be “catching the exception”. If there are no appropriate exception handler found
then program terminates printing information about the exception.
Java Exception handling is a framework that is used to handle runtime errors only, compile time errors are
not handled by exception handling in java.
Java provides specific keywords for exception handling purposes.

1. throw – We know that if any exception occurs, an exception object is getting created and then Java
runtime starts processing to handle them. Sometime we might want to generate exception explicitly
in our code, for example in a user authentication program we should throw exception to client if the
password is null.throw keyword is used to throw exception to the runtime to handle it.
2. throws – When we are throwing any exception in a method and not handling it, then we need to
use throws keyword in method signature to let caller program know the exceptions that might be
thrown by the method. The caller method might handle these exceptions or propagate it to it‟s caller
method using throws keyword. We can provide multiple exceptions in the throws clause and it can
be used with main() method also.
3. try-catch – We use try-catch block for exception handling in our code. try is the start of the block
and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with
a try and try-catch block can be nested also. catch block requires a parameter that should be of type
Exception.
4. finally – finally block is optional and can be used only with try-catch block. Since exception halts
the process of execution, we might have some resources open that will not get closed, so we can use
finally block. finally block gets executed always, whether exception occurred or not.

import java.io.*;
publicclassExcepTest{

publicstaticvoid main(Stringargs[]){
try{
int a[]=newint[2];
System.out.println("Access element three :"+ a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :"+
e);
}
System.out.println("Out of the block");
}
}
CatchingExceptions
A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following −

Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception occurs, that
exception occurred is handled by catch block associated with it. Every try block should be immediately
followed either by a catch block or finally block.

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs
in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.

2. Explain exception hierarchy in java?

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is derived
from the Throwable class.

Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java
programs. Errors are generated to indicate errors generated by the runtime environment. Normally,
programs cannot recover from errors.

The Exception class has two main subclasses: IOException class and RuntimeException Class.

ExceptionsMethods
Following is the list of important methods available in the Throwable class.

Sr.No. Method & Description

1 public String getMessage()


Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.

2 public ThrowablegetCause()
Returns the cause of the exception as represented by a Throwable object.

3 public String toString()


Returns the name of the class concatenated with the result of getMessage().

4 public void printStackTrace()


Prints the result of toString() along with the stack trace to System.err, the error
output stream.

5 public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The element at index
0 represents the top of the call stack, and the last element in the array represents
the method at the bottom of the call stack.

6 public ThrowablefillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to
any previous information in the stack trace.

3. Write a java program to handle division by zero ?

classJavaException {
public static void main(String args[]){
try{
int d = 0;
int n =20;
int fraction = n/d;
}
catch(ArithmeticException e){
System.out.println("In the catch clock due to Exception = "+e);
}
finally{
System.out.println("Inside the finally block");
}
}
}

4. Describe the types of Exception in Java with Examples ?

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Below is the list of important built-in exceptions in Java.
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size of the
string
Examples of Built-in Exception:
 Arithmetic exception
// Java program to demonstrate ArithmeticException
classArithmeticException_Demo
{
publicstaticvoidmain(String args[])
{
try{
inta = 30, b = 0;
intc = a/b; // cannot divide by zero
System.out.println ("Result = "+ c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
 ArrayIndexOutOfBounds Exception

classArrayIndexOutOfBound_Demo
{
publicstaticvoidmain(String args[])
{
try{
inta[] = newint[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println ("Array Index is Out Of Bounds");
}
}
}

5. How to create User Defined Exception in Java?

User Defined Exception or custom exception is creating your own exception class and throws that
exception using „throw‟ keyword. This can be done by extending the class Exception.

Example of User defined exception in Java

classMyExceptionextendsException{
String str1;
MyException(String str2)
{
str1=str2;
}
publicStringtoString(){
return("MyException Occurred: "+str1);
}
}

classExample1{
publicstaticvoid main(Stringargs[])
{ try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
thrownewMyException("This is My error Message");
}
catch(MyExceptionexp){
System.out.println("Catch
Block"); System.out.println(exp);
}
}
}

6. Explain byte streams and character streams in java ?


The java.io package contains nearly every class you might ever need to perform input and output (I/O) in
Java. All these streams represent an input source and an output destination.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −

 InPutStream − The InputStream is used to read data from a source.

 OutPutStream − The OutputStream is used for writing data to a destination.


Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes
related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of these two
classes to copy an input file into an output file −

Example
import java.io.*;
publicclassCopyFile{
publicstaticvoid
main(Stringargs[])throwsIOException{ FileInputStrea
min=null;
FileOutputStreamout=null;
try{
in=newFileInputStream("input.txt");
out=newFileOutputStream("output.txt");
int c;
while((c =in.read())!=-1){
out.write(c);
}
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close(); } } } }
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams
are used to perform input and output for 16-bit unicode. Though there are many classes related to
character streams but the most frequently used classes are, FileReader and FileWriter.

Example
import java.io.*;
public class
CopyFile {
public static void main(String args[]) throws
IOException { FileReader in = null;
FileWriter out =
null; try {
in = new
FileReader("input.txt"); out =
new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

7. Write a program to get the input from the user using InputStreamReader?
import java.io.*;
public class ReadConsole {
public static void main(String args[]) throws IOException
{ InputStreamReadercin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');

importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
publicclassTest
{
publicstaticvoidmain(String[] args) throwsIOException
{
//Enter data using BufferReader
BufferedReader reader = newBufferedReader(newInputStreamReader(System.in));
// Reading data using readLine

}finally {
if (cin != null)
{ cin.close();
}
}
}
}

8. Explain the different ways to read and write to console in java


? Ways to read input from console in Java
1. Using Buffered Reader Class
String name = reader.readLine();
// Printing the read line
System.out.println(name);
}
}

2. Using Scanner Class


Importjava.util.Scanner;

ClassGetInputFromUser
{
Publicstaticvoidmain(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = newScanner(System.in);

String s = in.nextLine();
System.out.println("You entered string "+s);

inta = in.nextInt();
System.out.println("You entered integer "+a);

Floatb = in.nextFloat();
System.out.println("You entered float "+b);
}
}
3. Using Console Class
PublicclassSample
{
Publicstaticvoidmain(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();
System.out.println(name);
}
}
Java Write to Console Output

The PrintStream is an output stream derived from the OutputStream, it also implements the low-level
method write(). Thus, write() can be used to write to the console. The simplest form of write() defined
by the PrintStream is shown below :
void write(intbyteval)

classWriteConsoleOutput {
public static void main(String args[])

{ int y;
y = 'X';
System.out.write(y);
System.out.write('\n'); } }

9. Write a program to perform reading nad writing from a file ?


Writing data in a file

class Test
{
public static void main( String args[])
{
FileOutputStreamfo=new FileOutputStream("prog.txt");
String s1="Welcome to Codesdope";
byte b1[]=s1.getBytes(); //converting string into byte array
fo.write(b1);
fo.close();
}
}
Here, byte b1[ ]=s1.getBytes(); is converting string(character array) into byte array.
Then by writing fo.write(b1);, we are writing the data in a file named prog.txt because fo is the object
of the FileOutputStream class.

Reading data from a file

class Test1
{
public static void main( String args[])
{
FileInputStream fi=new
FileInputStream("prog.txt"); int n=0;
while((n=fi.read())!=-1){

System.out.println((char)n);
}
fin.close(); }}
UNIT IV
1. Explain the life cycle of thread in
Java? Thread States

A thread can be in one of the five states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the

invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread

scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

2. Explain how to create thread by using runnable interface?

The easiest way to create a thread is to create a class that implements the runnable interface. After
implementing runnable interface, the class needs to implement the run() method, which is of form,
publicvoidrun()

 run() method introduces a concurrent thread into your program. This thread will end when
run() method terminates.
 You must specify the code that your thread will execute inside run() method.
 run() method can call other methods, can use other classes and declare variables just like any
other normal method.

To call the run() method, start() method is used. On calling start(), a new stack is provided to the thread
and run() method is called to introduce the new thread into the program.
Note: If you are implementing Runnable interface in your class, then you need to explicitly create a
Thread class object and need to pass the Runnable interface implemented class object as a parameter in
its constructor.
To make a class runnable, we can implement java.lang.Runnable interface and provide implementation
in public void run() method.

To use this class as Thread, we need to create a Thread object by passing object of this runnable class and
then call start() method to execute the run() method in a separate thread.

Java thread example by implementing Runnable interface

public class HeavyWorkRunnable implements Runnable

{ public void run() {


System.out.println("Doing heavy processing - START
"+Thread.currentThread().getName());
try {
Thread.sleep(1000);
//Get database connection, delete unused data from DB
doDBProcessing();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Doing heavy processing - END
"+Thread.currentThread().getName());
}
private void doDBProcessing() throws InterruptedException {
Thread.sleep(5000);
}
}

3. How to Create Threads in Java by Extending Thread Class?

The first way to create a thread is to create a subclass of the Thread class. This class must override the
run( ) method as discussed above and it may override the other methods too. Then the class that needs the
thread can create an object of the class that extends thread class

class PrintString1
{
public static void main(String args[])
{
StringThread1 t = new StringThread1 ("Java",50);
t.start ( );
}
}

class StringThread1 extends Thread


{
private String str;
privateintnum;

StringThread1 (String s, int n)


{
str=new String (s);
num=n;
}

public void run ( )


{
for (int i=1; i<=num; i++)
System.out.print(str + " ");
}
}
4. Explain interthread communication in Java?

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its


critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It
is implemented by following methods of Object class:

o wait()
o notify()
o notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes the notify() method
or the notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.

Method Description

public final void wait()throws waits until object is notified.


InterruptedException

public final void wait(long waits for the specified amount of


timeout)throws InterruptedException time.
2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object,
one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the
lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

Example of inter thread communication in java


class Customer{
int amount=10000;

synchronized void withdraw(int amount)


{ System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw
completed...");
}

synchronized void deposit(int amount)


{ System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}

5. Explain Daemon thread in Java with example ?

Daemon thread is a low priority thread (in context of JVM) that runs in background to perform tasks such
as garbage collection (gc) etc., they do not prevent the JVM from exiting (even if the daemon thread itself
is running) when all the user threads (non-daemon threads) finish their execution.
JVM terminates itself when all user threads (non-daemon threads) finish their execution, JVM does not
care whether Daemon thread is running or not, if JVM finds running daemon thread (upon completion of
user threads), it terminates the thread and after that shutdown itself.

Properties of Daemon threads:

1. A newly created thread inherits the daemon status of its parent. That‟s the reason all threads created
inside main method (child threads of main thread) are non-daemon by default, because main thread
is non-daemon. However you can make a user thread to Daemon by using setDaemon() method of
thread class.

When the JVM starts, it creates a thread called “Main”. Your program will run on this thread,
unless you create additional threads yourself. The first thing the “Main” thread does is to look for
your static void main (String args[]) method and invoke it. That is the entry-point to your program.
If you create additional threads in the main method those threads would be the child threads of main
thread.

2. Methods of Thread class that are related to Daemon threads:

public void setDaemon(boolean status): This method is used for making a user thread to Daemon
thread or vice versa. For example if I have a user thread t then t.setDaemon(true) would make it
Daemon thread. On the other hand if I have a Daemon thread td then by calling td.setDaemon(false)
would make it normal thread(user thread/non-daemon thread).
publicbooleanisDaemon(): This method is used for checking the status of a thread. It returns true if
the thread is Daemon else it returns false.

3. setDaemon() method can only be called before starting the thread. This method would throw
IllegalThreadStateException if you call this method after Thread.start() method.
DAEMON THREAD EXAMPLES

Example 1: DaemonThreadExample1.java
This example is to demonstrate the usage of setDaemon() and isDaemon() method.

publicclassDaemonThreadExample1extendsThread{
publicvoid run(){

// Checking whether the thread is Daemon or not


if(Thread.currentThread().isDaemon()){
System.out.println("Daemon thread executing");
}
else{
System.out.println("user(normal) thread executing");
}
}
publicstaticvoid main(String[]args){
DaemonThreadExample1
t1=newDaemonThreadExample1();
DaemonThreadExample1 t2=newDaemonThreadExample1();

t1.setDaemon(true);

t1.start();
t2.start();
}
}

Example 2: DaemonThreadEx2.java
If you call the setDaemon() method after starting the thread (start() method), it would throw
IllegalThreadStateException. This clearly means that you can call setDaemon() method only before
starting a thread.

public class DaemonThreadEx2 extends Thread

{ public void run(){


System.out.println("Thread is running");
}

public static void main(String[] args){


DaemonThreadEx2 t1=new DaemonThreadEx2();
t1.start();
// It will throw
IllegalThreadStateException
} t1.setDaemon(true);
}

6. Difference between Daemon threads and non-Daemon thread (user thread)

The main difference between Daemon thread and user threads is that the JVM does not wait for Daemon
thread before exiting while it waits for user threads, it does not exit until unless all the user threads
finish their execution.
7. Explain the concept of ThreadGroup in Java with example ?

Java provides a convenient way to group multiple threads in a single object. In such way, we can suspend,
resume or interrupt group of threads by a single method call.

Java thread group is implemented by java.lang.ThreadGroup class.

Constructors of ThreadGroup class

There are only two constructors of ThreadGroup class.

No. Constructor Description

1) ThreadGroup(String name) creates a thread group with given name.

2) ThreadGroup(ThreadGroup parent, String creates a thread group with given parent


name) group and name.

Important methods of ThreadGroup class

There are many methods in ThreadGroup class. A list of important methods are given below.

No. Method Description

1) intactiveCount() returns no. of threads running in current group.

2) intactiveGroupCount() returns a no. of active group in this thread group.

3) void destroy() destroys this thread group and all its sub groups.

4) String getName() returns the name of this group.

5) ThreadGroupgetParent() returns the parent of this group.

6) void interrupt() interrupts all threads of this group.

7) void list() prints information of this group to standard console.

THREADGROUP EXAMPLE
public class ThreadGroupDemo implements
Runnable{ public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1, runnable,"one");
t1.start();
Thread t2 = new Thread(tg1, runnable,"two");
t2.start();
Thread t3 = new Thread(tg1, runnable,"three");
t3.start();
System.out.println("Thread Group Name: "+tg1.getName());
tg1.list();
}
}

UNIT V
1. Explain the features of Scala in detail.

Features of Scala

There are following features of scala:

o Type inference
o Singleton object
o Immutability
o Lazy computation
o Case classes and Pattern matching
o Concurrency control
o String interpolation
o Higher order function
o Traits
o Rich collection set
Type Inference

In Scala, you don't require to mention data type and function return type explicitly. Scala is enough smart
to deduce the type of data. The return type of function is determined by the type of last expression present
in the function.

Singleton object

In Scala, there are no static variables or methods. Scala uses singleton object, which is essentially class
with only one object in the source file. Singleton object is declared by using object instead of class
keyword.

Immutability

Scala uses immutability concept. Each declared variable is immutable by default. Immutable means you
can't modify its value. You can also create mutable variables which can be changed.

Immutable data helps to manage concurrency control which requires managing data.

Lazy Computation

In Scala, computation is lazy by default. Scala evaluates expressions only when they are required. You can
declare a lazy variable by using lazy keyword. It is used to increase

performance. Case classes and Pattern matching

Scala case classes are just regular classes which are immutable by default and decomposable through
pattern matching.

All the parameters listed in the case class are public and immutable by default.

Case classes support pattern matching. So, you can write more logical code.

Concurrency control

Scala provides standard library which includes the actor model. You can write concurrency code by using
actor. Scala provides one more platform and tool to deal with concurrency known as Akka. Akka is a
separate open source framework that provides actor-based concurrency. Akka actors may be distributed or
combined with software transactional memory.

String Interpolation

Since Scala 2.10.0, Scala offers a new mechanism to create strings from your data. It is called string
interpolation. String interpolation allows users to embed variable references directly in processed string
literals. Scala provides three string interpolation methods: s, f and raw.

Higher Order Functions

Higher order function is a function that either takes a function as argument or returns a function. In other
words, we can say a function which works with another function is called higher order function.

Higher order function allows you to create function composition, lambda function or anonymous function
etc.
Traits

A trait is like an interface with a partial implementation. In Scala, trait is a collection of abstract and non-
abstract methods. You can create trait that can have all abstract methods or some abstract and some non-
abstract methods.

Traits are compiled into Java interfaces with corresponding implementation classes that hold any methods
implemented in the traits.

Rich Set of Collection

Scala provides rich set of collection library. It contains classes and traits to collect data. These collections
can be mutable or immutable. You can use it according to your requirement. Scala.collection.mutable
package contains all the mutable collections. You can add, remove and update data while using this
package.

2. Explain in detail about classes and functions in scala with example.

Classes

Scala is an object-oriented language, and as such it has a concept of class. (For the sake of completeness, it
should be noted that some object-oriented languages do not have the concept of class, but Scala is not one
of them.) Classes in Scala are declared using a syntax which is close to Java‟s syntax. One important
difference is that classes in Scala can have parameters. This is illustrated in the following definition of
complex numbers.
class Complex(real: Double, imaginary: Double)
{ def re() = real
def im() = imaginary
}
This Complex class takes two arguments, which are the real and imaginary part of the complex number.
These arguments must be passed when creating an instance of class Complex, as follows: new
Complex(1.5, 2.3). The class contains two methods, called re and im, which give access to these two parts.
It should be noted that the return type of these two methods is not given explicitly. It will be inferred
automatically by the compiler, which looks at the right-hand side of these methods and deduces that both
return a value of type Double.
The compiler is not always able to infer types like it does here, and there is unfortunately no simple rule to
know exactly when it will be able to. In practice, this is usually not a problem since the compiler
complains when it is not able to infer a type which was not given explicitly. As a simple rule, beginner
Scala programmers should try to omit type declarations which seem to be easy to deduce from the context,
and see if the compiler agrees. After some time, the programmer should get a good feeling about when to
omit types, and when to specify them explicitly.
Methods without arguments
A small problem of the methods re and im is that, in order to call them, one has to put an empty pair
of parenthesis after their name, as the following example shows:
object ComplexNumbers {
def main(args: Array[String]): Unit =
{ val c = new Complex(1.2, 3.4)
println("imaginary part: " + c.im())

} }

It would be nicer to be able to access the real and imaginary parts like if they were fields,
without putting the empty pair of parenthesis. This is perfectly doable in Scala, simply
by defining them as
methods without arguments. Such methods differ from methods with zero arguments in
that they don‟ t have parenthesis after their name, neither in their definition nor in their
use. Our Complex class can be rewritten as follows:

class Complex(real: Double, imaginary: Double)

{ def re = real
def im = imaginary

Inheritance and overriding

All classes in Scala inherit from a super-class. When no super-class is specified, as in


the Complex example of previous section, scala.AnyRef is implicitly used.
It is possible to override methods inherited from a super-class in Scala. It is however mandatory to
explicitly specify that a method overrides another one using the override modifier, in order to avoid
accidental overriding. As an example, our Complex class can be augmented with a redefinition of
the toString method inherited from Object.
class Complex(real: Double, imaginary: Double)
{ def re = real
def im = imaginary
override def toString() =
"" + re + (if (im >= 0) "+" else "") + im + "i"
}
We can call overridden toString method as below.
object ComplexNumbers {
def main(args: Array[String]): Unit =
{ val c = new Complex(1.2, 3.4)
println("Overridden toString(): " + c.toString)
}}

You might also like