UNIT-I
1. Core OOPS concepts are
1)Class
The class is a group of similar entities. It is only a logical component and not the physical entity.
For example, if you had a class called “Expensive Cars” it could have objects like Mercedes,
BMW, Toyota, etc. Its properties (data) can be price or speed of these cars. While the methods
may be performed with these cars are driving, reverse, braking etc.
2) Object
An object can be defined as an instance of a class, and there can be multiple instances of a class
in a program. An Object contains both the data and the function, which operates on the data. For
example - chair, bike, marker, pen, table, car, etc.
3) Inheritance
Inheritance is an OOPS concept in which one object acquires the properties and behaviors of the
parent object. It‟s creating a parent-child relationship between two classes. It offers robust and
natural mechanism for organizing and structure of any software.
4) Polymorphism
Polymorphism refers to the ability of a variable, object or function to take on multiple forms. For
example, in English, the verb “run” has a different meaning if you use it with “a laptop,” “a foot
race, and ”business.&rdquo Here, we understand the meaning of “run” based on the other words
used along with [Link] same also applied to Polymorphism.
5) Abstraction
An abstraction is an act of representing essential features without including background details. It
is a technique of creating a new data type that is suited for a specific application. For example,
while driving a car, you do not have to be concerned with its internal working. Here you just
need to concern about parts like steering wheel, Gears, accelerator, etc.
6) Encapsulation
Encapsulation is an OOP technique of wrapping the data and code. In this OOPS concept, the
variables of a class are always hidden from other classes. It can only be accessed using the
methods of their current class. For example - in school, a student cannot exist without a class.
7) Association
Association is a relationship between two objects. It defines the diversity between objects. In this
OOP concept, all object have their separate lifecycle, and there is no owner. For example, many
students can associate with one teacher while one student can also associate with multiple
teachers.
8) Aggregation
In this technique, all objects have their separate lifecycle. However, there is ownership such that
child object can‟t belong to another parent object. For example consider class/objects department
and teacher. Here, a single teacher can‟t belong to multiple departments, but even if we delete
the department, the teacher object will never be destroyed.
9) Composition
A composition is a specialized form of Aggregation. It is also called "death" relationship. Child
objects do not have their lifecycle so when parent object deletes all child object will also delete
automatically. For that, let‟s take an example of House and rooms. Any house can have several
rooms. One room can‟t become part of two different houses. So, if you delete the house room
will also be deleted.
1.2 Advantages of OOPS:
1. OOP offers easy to understand and a clear modular structure for programs.
2. Objects created for Object-Oriented Programs can be reused in other programs. Thus it
saves significant development cost.
3. Large programs are difficult to write, but if the development and designing team follow
OOPS concept then they can better design with minimum flaws.
4. It also enhances program modularity because every object exists independently.
2. Write the description of primitive data types
There are majorly two types of languages. First one is Statically typed language where each
variable and expression type is already known at compile time. Once a variable is declared to be
of a certain data type, it cannot hold values of other data types. Example: C,C++, Java. Other,
Dynamically typed languages: These languages (Ruby, Python) can receive different data types
over the time.
Java is statically typed and also a strongly typed language because in Java, each type of data
(such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of
the programming language and all constants or variables defined for a given program must be
described with one of the data types.
Java has two categories of data:
• Primitive data (e.g., number, character)
• Object data (programmer created types)
boolean: boolean data type represents only one bit of information either true or false . Values of
type boolean are not converted implicitly or explicitly (with casts) to any other type. But the
programmer can easily write conversion code.
// A Java program to demonstrate boolean data type class
GeeksforGeeks
{
public static void main(String args[])
{
boolean b = true;
if (b == true)
[Link]("Hi Geek");
}
}
byte: The byte data type is an 8-bit signed two‟s complement integer. The byte data type is
useful for saving memory in large arrays.
• Size: 8-bit
• Value: -128 to 127
// Java program to demonstrate byte data type in Java class
GeeksforGeeks
{
public static void main(String args[])
{
byte a = 126;
// byte is 8 bit value
[Link](a);
a++;
[Link](a);
// It overflows here because
// byte can hold values from -128 to 127
a++;
[Link](a);
// Looping back within the range
a++;
[Link](a);
}
} short: The short data type is a 16-bit signed two‟s complement integer. Similar to byte, use a
short to save memory in large arrays, in situations where the memory savings actually matters.
• Size: 16 bit
• Value: -32,768 to 32,767 (inclusive) int
It is a 32-bit signed two‟s complement integer.
• Size: 32 bit
• Value: -231 to 231-1
Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer,
which has value in range [0, 2 32-1]. Use the Integer class to use int data type as an unsigned
integer.
long: The long data type is a 64-bit two‟s complement integer.
• Size: 64 bit
• Value: -263 to 263-1.
Note: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long,
which has a minimum value of 0 and a maximum value of 2 64-1. The Long class also contains
methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for
unsigned long.
Floating point Numbers : float and double float: The float data type is a single-precision 32-
bit IEEE 754 floating point. Use a float (instead of double) if you need to save memory in large
arrays of floating point numbers.
• Size: 32 bits
• Suffix : F/f Example: 9.8f double: The double data type is a double-precision 64-bit IEEE
754 floating point. For decimal values, this data type is generally the default choice.
Note: Both float and double data types were designed especially for scientific calculations,
where approximation errors are acceptable. If accuracy is the most prior concern then, it is
recommended not to use these data types and use BigDecimal class instead. Please see this
for details: Rounding off errors in Java char
The char data type is a single 16-bit Unicode character. A char is a single character.
• Value: „\u0000‟ (or 0) to „\uffff‟ 65535
// Java program to demonstrate primitive data types in Java class
GeeksforGeeks
{
public static void main(String args[])
{
// declaring character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i=89;
// use byte and short if memory is a constraint
byte b = 4;
// this will give error as number is
// larger than byte range
// byte b1 = 7888888955;
short s = 56;
// this will give error as number is
// larger than short range
// short s1 = 87878787878;
// by default fraction value is double in java
double d = 4.355453532;
// for float use 'f' as suffix
float f = 4.7333434f;
[Link]("char: " + a);
[Link]("integer: " + i);
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("float: " + f);
[Link]("double: " + d);
}
}
3. Give an overview of java arrays
Normally, an array is a collection of similar type of elements that have a contiguous memory
location.
Java array is an object which contains elements of a similar data type. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array. Array
in java is index-based, the first element of the array is stored at the 0 index.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
There are two types of array.
Single Dimensional Array
Multidimensional Array
1. EXAMPLE ARRAY INITALIZATION (single dimension)
Passing Array to Method in Java
4. Write notes on selection statements
A program executes from top to bottom except when we use control statements, we can
control the order of execution of the program, based on logic and values. In Java, control
statements can be divided into the following three categories:
Selection Statements Iteration Statements Jump Statements \
Selection statements can be divided into the following categories:
1. The if statements
2. The if-else statements
3. The if-else-if statements
4. The switch statements
a) if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statements is executed otherwise not.
if(condition)
{
// Statements to execute if
// condition is true
}
Ex:
import [Link].*;
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link]("Inside If block");
[Link]("10 is less than 15");
[Link]("I am Not in if");
}
}
b) if-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if the
condition is false? Here comes the else statement. We can use the else statement with the if
statement to execute a block of code when the condition is false.
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Ex:
import [Link].*;
class IfElseDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}
c) if-else-if : Here, a user can decide among multiple [Link] if statements are executed from the
top down. As soon as one of the conditions controlling the if is true, the statement associated with
that ‘if’ is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the
final else statement will be executed. There can be as many as ‘else if’ blocks associated with one
‘if’ block but only one ‘else’ block is allowed with one ‘if’ block.
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
else
statement;
Ex:
import [Link].*;
class ifelseifDemo {
public static void main(String args[])
{
int i = 20;
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
}
}
d) Switch: Using the switch statement, one can select only one option from more number of options
very easily. In the switch statement, we provide a value that is to be compared with a value
associated with each option. Whenever the given value matches the value associated with an
option, the execution starts from that option. In the switch statement, every option is defined as
a case.
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
statementDefault;
}
Ex:
import [Link].*;
class GFG {
public static void main (String[] args) {
int num=20;
switch(num){
case 5 : [Link]("It is 5");
break;
case 10 : [Link]("It is 10");
break;
case 15 : [Link]("It is 15");
break;
case 20 : [Link]("It is 20");
break;
default: [Link]("Not present");
}
}
}
5. Give an overview of iteration statements
Repeating the same code fragment several times until a specified condition is satisfied is called
iteration. Iteration statements execute the same set of instructions until a termination condition is
met.
Java provides the following loop for iteration statements:
• The while loop
• The for loop
• The do-while loop
• The for each loop
Example while loop
public class WhileDemo
{
public static void main( String[] args )
{
int i = 0;
while ( i < 5 )
{
[Link]( "Value :: " + i );
i++;
}
}
}
Example do while
public class DoWhileDemo
{
public static void main( String[] args )
{
int i = 0;
do
{
[Link]( "value :: " + i );
i++;
}
while ( i < 5);
}
}
FOR loop Example
public class ForDemo
{
public static void main( String[] args )
{
for ( int var = 0; var < 5; var++ )
{
[Link]( "Var is : " + var );
if ( var == 3 )
break;
}
}
}
Jump Statements
Jump statements are used to unconditionally transfer the program control to another part of the
program.
Java provides the following jump statements:
• break statement
• continue statement
• return statement
Break Statement
The break statement immediately quits the current iteration and goes to the first statement
following the loop. Another form of break is used in the switch statement.
6. Write and explain the general syntax of a class
A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class‟s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Example classes
UNIT-II
1. Mention the classes belonging to output stream category
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1) [Link]: standard output stream
2) [Link]: standard input stream
3) [Link]: standard error stream
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
2. Write a java program to implement file input and file output streams
3. Explain about the methods of print writer class
Java PrintWriter class is the implementation of Writer class. It is used to print the formatted
representation of objects to the text-output stream.
Methods of PrintWriter class
UNIT-III
1. Write notes on hierarchy of collection framework
Let us see the hierarchy of Collection framework. The [Link] package contains all the
classes and interfaces for the Collection framework.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of
Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have duplicate
values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed. Consider the following example.
import [Link].*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion order
and is not synchronized. In LinkedList, the manipulation is fast because no shifting is
required.
Consider the following example.
import [Link].*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
2. Give an overview of Map interface
A map contains values on the basis of key, i.e. key and value pair. Each key and value
pair is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
Java Map Hierarchy
There are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given
below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or
value.
A Map can't be traversed, so you need to convert it into Set
using keySet() or entrySet() method.
3. Write a java program to demonstrate generics