Qboops Java
Qboops Java
COLLEGE
(An Autonomous Institution)
DEPARTMENT OF
INFORMATION
TECHNOLOGY
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.
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];
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
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
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
Mutable Variables
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
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
„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.
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.
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.
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?
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?
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.
String trim(): It returns the copy of the string with leading and trailing of the whitespace omitted.
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.
Java has a concise, cohesive set of features that makes it easy to learn and use.
Secure :
Portable :
Java programs can execute in any environment for which there is a Java run-time system.(JVM)
Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
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.
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.
fields
methods
constructors
blocks
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
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);
}
}
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 Definitions:
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);
}
}
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
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.
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;
Syntax
a, b − formal parameters
Syntax
modifier − It defines the access type of the method and it is optional to use.
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;
}
}
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 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.
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 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.
class Student9{
int rollno;
String name;
static String college = "ITS";
s1.display();
s2.display();
s3.display();
}
}
There are many types of operators in java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Assignment Operator.
UNIT –II
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.
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.
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.
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.
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();
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 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.
abstract class
MyClass{ public void
disp(){
System.out.println("Concrete method of parent class");
}
abstract public void disp2();
}
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:
return-type method-name2(parameter-
return-type method-nameN(parameter-list);
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.
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:
{ // 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
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();
MyClass implements B {
{ System.out.println("Implement meth1()."); }
} classIFExtend {
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.
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.
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.
void add(int index, Object It is used to insert the specified element at the
element) specified position index in a list.
Creating a String
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:
In this case compiler would create two different object in memory having the same string.
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.
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.
2 public ThrowablegetCause()
Returns the cause of the exception as represented by a Throwable object.
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.
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");
}
}
}
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");
}
}
}
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.
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);
}
}
}
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();
}
}
}
}
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'); } }
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.
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
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
2) Runnable
The thread is in runnable state after invocation of start() method, but the 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
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.
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 ( );
}
}
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
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:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
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...");
}
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.
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.
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(){
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.
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.
There are many methods in ThreadGroup class. A list of important methods are given below.
3) void destroy() destroys this thread group and all its sub groups.
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
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
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 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.
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.
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:
{ def re = real
def im = imaginary