OOM ASSIGNMENTS
Assignment -1
Q.1. What is a programming language?
Ans. A programming language is a vocabulary and set of grammatical rules for instructing a
computer or computing device to perform specific tasks.
Q.2. What is OOP?
Ans. Object-oriented programming (OOP) is a computer programming model that organizes
software design around data, or objects, rather than functions and logic. An object can
be defined as a data field that has unique attributes and behaviour. Or Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects.
Q.3. What are the OOP Concepts?
Ans. Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
o Message Passing
o Dynamic Binding
1. Object
Any entity that has state and behaviour is known as an object. For example, a chair, pen,
table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and
takes
up some space in memory. Objects can communicate without knowing the details of
each
other's data or code. The only necessary thing is the type of message accepted and the
type
OOM ASSIGNMENTS
of response returned by the objects.
Example: A dog is an object because it has states like colour, name, breed, etc. as well
as
behaviour like wagging the tail, barking, eating, etc.
2. Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object.
Class doesn't consume any space.
3. Inheritance
When one object acquires all the properties and behaviours of a parent object, it is
known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
4. Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle,
etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog
barks
woof, etc.
5. Abstraction
Hiding internal details and showing functionality is known as abstraction. For example,
phone
call, we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
6. Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
For example, a capsule, it is wrapped with different medicines.
OOM ASSIGNMENTS
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
7. Message Passing:
Objects communicate with one another by sending and receiving information to each
other. A
message for an object is a request for execution of a procedure and therefore will invoke
a
function in the receiving object that generates the desired results. Message passing
involves
specifying the name of the object, the name of the function and the information to be
sent.
8. Dynamic Binding
Dynamic binding also called dynamic dispatch is the process of linking procedure call to
a
specific sequence of code (method) at run-time. It means that the code to be executed
for a
specific procedure call is not known until run-time. Dynamic binding is also known as
late binding or run-time binding.
Q.4. What are the benefits of OOP?
Ans, It is easy to model a real system as real objects are represented by programming
objects in OOP. The objects are processed by their field (member data) and methods
(functions). It is easy to analyse the user requirements.
• With the help of inheritance, we can reuse the existing class to derive a new class such
that the redundant code is eliminated and the use of existing class is extended. This
saves time and cost of program.
• In OOP, data can be made private to a class such that only member functions of the
class can access the data. This principle of data hiding helps the programmer to build
a secure program that cannot be invaded by code in other part of the program.
• With the help of polymorphism, the same function or same operator can be used for
different purposes. This helps to manage software complexity easily.
• Large problems can be reduced to smaller and more manageable problems. It is easy
to partition the work in a project based on objects.
OOM ASSIGNMENTS
• It is possible to have multiple instances of an object to co-exist without any
interference i.e. each object has its own separate field (member data) and methods
(functions).
OOM ASSIGNMENTS
Assignment -2
Q.1 What is Java?
Ans. Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language. Ø Java was developed by Sun Microsystems (which
is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java.
Before Java, its name was Oak. Since Oak was already a registered company, so Ja mes Gosling
and his team changed the Oak name to Java.
Q.2 What are variables in Java?
Ans. A variable is a name which is associated with a value that can be changed. For example
when I write int i=10; here variable name is i which is associated with value 10, int is a data type
that represents that this variable can hold integer values.
Q.3. Write the execution model of java?
Ans. Five phases in Java Programs
Ø In the figure below, 5 phases of the Java Program are described clearly with edit,
compile, load, verify and execute.
Ø Phase 1: Edit
Ø We create the program on editor, after that it stored in the disk with the
name's ending .java
Ø Phase 2: Compile javac (java compiler)
Ø Compiler translate from high -level language program to byte codes and store
it in disk with the ending name .class.
Ø Phase 3: Load
Ø Class loader compile read and put those byte codes from disk to Primary
Memory.
Ø Phase 4: Verify
Ø Verify byte codes to confirm that all byte codes are valid and do not risk for
the Java's security restrictions.
Ø Phase 5: Execute
Ø Java Virtual Machine (JVM) read and translates those byte codes to language
that computer can understand (Machine Language). Then execute the
OOM ASSIGNMENTS
program, store it values in primary memory.
Q.3. What is JVM and How it Works?
Ans. Ø Java Virtual Machine (JVM) is a engine that provides runtime environment to drive
the Java Code or applications.
Ø It converts Java bytecode into machines language.
Ø JVM is a part of Java Run Environment (JRE).
Working of Java Virtual Machine (JVM) & its Architecture
1) Class Loader
The class loader is a subsystem used for loading class files. It performs
three major functions viz. Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant
runtime pool, and the code for methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in
the heap. This memory is common and shared across multiple threads.
4) JVM language Stacks
Java language Stacks store local variables, and it’s partial results. Each
thread has its own JVM stack, created simultaneously as the thread is
created. A new frame is created whenever a method is invoked, and it is
deleted when method invocation process is complete.
5) PC Registers
OOM ASSIGNMENTS
PC register store the address of the Java virtual machine instruction
which is currently executing. In Java, each thread has its separate PC
register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depends on
the native library. It is written in another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete
systems. The test execution engine never carries any information about the
tested product.
8) Native Method interface
The Native Method Interface is a programming framework. It allows Java code which is
running in a JVM to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) which
are needed by the Execution Engine.
Q.4. How to declare variables in java?
Ans. Ø To declare a variable follow this syntax:
data_type variable_name = value;
here value is optional because in java, you can declare the variable first and then
l ater assign the value to it.
Ø For example: Here num is a variable and int is a data type.
int num;
OOM ASSIGNMENTS
Ø Similarly we can assign the values to the variables while declaring them, like this:
char ch = 'A';
int number = 100;
or we can do it like this:
char ch;
int number;
...
ch = 'A';
number = 100;
OOM ASSIGNMENTS
Assignment -3
Q.1. What is a class in java?
Ans. A class is a blueprint from which individual objects are created.
Q.2. What are methods in java?
Ans. A Java method is a collection of statements that are grouped together to perform an
operation. When you call the System.out.println() method, for example, the system
actually executes several statements in order to display a message on the console.
Q.3 How to create a object in class?
Ans. is created from a class. In Java, the new keyword is used to create new objects.
There are three steps 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.
Here is how we can create an object of a class.
SYNTAX:
<className> <objectname> = new className();
EXAMPLE:
// for Bicycle class
Bicycle sportsBicycle = new Bicycle();
Bicycles touringBicycle = new Bicycle();
Q.4. What are Constructors and type of constructors?
Ans. A constructor in Java is a special method that is used to initialize objects. The
constructor
is called when an object of a class is created.
In Java, a constructor is a block of codes similar to the method. It is called when an instance
OOM ASSIGNMENTS
of the class is created. At the time of calling constructor, memory for the object is allocated
in the memory.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
DEFAULT CONSTRUCTOR:
If you do not implement any constructor in your class, Java compiler inserts a default
constructor into your code on your behalf. This constructor is known as default constructor.
You would not find it in your source code(the java file) as it would be inserted into the code
during compilation and exists in .class file.
NO-ARG CONSTRUCTOR:
Constructor with no arguments is known as no-arg constructor. The signature is same as
default constructor, however body can have any code unlike default constructor where
the body of the constructor is empty.
PARAMETERIZED CONSTRUCTOR:
Constructor with arguments(or you can say parameters) is known as Parameterized
constructor.
OOM ASSIGNMENTS
Assignment -4
Q.1. What is StringBuilder in Java?
Ans. StringBuilder objects are like String objects, except that they can be modified.
Hence Java StringBuilder class is also used to create mutable (modifiable)
string object. StringBuilder is same as StringBuffer except for one important
difference. StringBuilder is not synchronized, which means it is not thread safe.
At any point, the length and content of the sequence can be changed through
method invocations.
Q.2 What is StringBufffer?
Ans. Java StringBuffer class is used to create mutable (modifiable) string object. A string
buffer is like a String, but can be modified.
Every string buffer has a capacity. As long as the length of the character sequence contained in
the string buffer does not exceed the capacity, it is not necessary to allocate a new internal
buffer array. If the internal buffer overflows, it is automatically made larger.
Q.3 Name any 5 Java String methods?
Ans. Java String length(): The Java String length() method tells the length of the string. It
returns count of total number of characters present in the String. For example:
public class Example{
public static void main(String args[]{
String s1="hello";
String s2="whatsup";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}}
Here, String length() function will return the length 5 for s1 and 7 for s2 respectively.
Java String concat() : The Java String concat() method combines a specific string at the
end of another string and ultimately returns a combined string. It is like appending
another string. For example:
public class ConcatExample{
OOM ASSIGNMENTS
public static void main(String args[]){
String s1="hello";
s1=s1.concat("how are you");
System.out.println(s1);
}}
The above code returns “hellohow are you”.
Java String IsEmpty() : This method checks whether the String contains anything or
not. If the java String is Empty, it returns true else false. For example:
public class IsEmptyExample{
public static void main(String args[]){
String s1="";
String s2="hello";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
}}
Java String Trim() : The java string trim() method removes the leading and trailing
spaces. It checks the unicode value of space character (‘u0020’) before and
after the
string. If it exists, then removes the spaces and return the omitted string. For
example:
public class StringTrimExample{
public static void main(String args[]){
String s1=" hello ";
System.out.println(s1+"how are you"); // withouttrim()
System.out.println(s1.trim()+"how are you"); // with trim()
}}
In the above code, the first print statement will print “hello how are you” while
the
second statement will print “hellohow are you” using the trim() function.
OOM ASSIGNMENTS
Java String toLowerCase() : The java string toLowerCase() method converts all
the
characters of the String to lower case. For example:
public class StringLowerExample{
public static void main(String args[]){
String s1="HELLO HOW Are You?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);}
The above code will return “hello how are you”.
Q.4. What are the methods of parameter passing?
Ans. Pass By Value:
Ø Changes made to formal parameter do not get transmitted back to the caller.
Ø Any modifications to the formal parameter variable inside the called function
or method affect only the separate storage location and will not be
reflected in
the actual parameter in the calling environment.
Ø This method is also called as call by value.
Ø Java in fact is strictly call by value.
Call by reference(aliasing):
Ø Changes made to formal parameter do get transmitted back to the caller
through parameter passing.
Ø Any changes to the formal parameter are reflected in the actual parameter in
the calling environment as formal parameter receives a reference (or pointer) to
the actual data.
Ø This method is also called as <em>call by reference.
Ø This method is efficient in both time and space.
OOM ASSIGNMENTS
Assignment – 5
Q.1. What is inheritance in java?
Ans. Ø Inheritance is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
Ø It is an important part of OOPs (Object Oriented programming system).
Q.2 What are the types of inheritance in java?
Ans. Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchial Inheritance
Hybrid Inheritance
Q.3. What is Multiple inheritance?
Ans. Ø In multiple inheritance there exist multiple base classes and single derived class.
Ø The concept of multiple inheritance is not supported in java through concept of
classes but it can be supported through the concept of interface
Program:
class A
void msg()
System.out.println("Hello");
class B
void msg()
{
OOM ASSIGNMENTS
System.out.println("Welcome");
class C extends A,B
{ //suppose if it were
public static void main(String args[])
C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
Ø Output:
Compile Time Error
Ø In above code we call both class A and class B msg() method then it confusion which
class method is call. So due to this ambiguity problem in java do not use multiple
inheritance at class level, but it support at interface level.
Q.5. What is Hierarchial inheritance?
Ans. When more than one classes inherit a same class then this is called hierarchical
inheritance. For example class B, C and D extends a same class A.
Ø As you can see in the above diagram that when a class has more than one child classes
(sub classes) or in other words more than one child classes have the same parent class
then this type of inheritance is known as hierarchical inheritance.
Program:
class Animal{
void eat()
System.out.println("eating...");
class Dog extends Animal
OOM ASSIGNMENTS
void bark()
System.out.println("barking...");
class Cat extends Animal
void meow()
System.out.println("meowing...");
class TestInheritance3
public static void main(String args[])
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
Ø Output:
meowing...
eating...
Ø Program:
class A
{
OOM ASSIGNMENTS
public void methodA()
System.out.println("method of Class A");
class B extends A
public void methodB()
System.out.println("method of Class B");
class C extends A
public void methodC()
System.out.println("method of Class C");
class D extends A
public void methodD()
System.out.println("method of Class D");
class JavaExample
public static void main(String args[])
B obj1 = new B(); C
OOM ASSIGNMENTS
obj2 = new C(); D
obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
Ø Output:
method of Class A
method of Class A
method of Class A
OOM ASSIGNMENTS
Assignment-6
Q.1. What is Polymorphism in java?
Ans. Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
Polymorphism uses those methods to perform different tasks. This allows us to perform a single
action in different ways. For example, think of a superclass called Animal that has a method
called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also
have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):
Q.2. What are type of Polymorphism?
Ans. Compile-time Polymorphism (Method Overloading)
Run-time polymorphism (Method-overidding)
Q.3. What is Method Overloading in java?
Ans, Method Overloading in Java
Method Overloading is a feature that allows a class to have more than one method
having the same name, if their argument lists are different. It is similar
to constructor overloading in Java, that allows a class to have more than one
constructor having different argument lists.
let’s get back to the point, when I say argument list it means the parameters that
a method has: For example the argument list of a method add(int a, int b) having
two parameters is different from the argument list of the method add(int a, int b,
int c) having three parameters.
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
This example shows how method overloading is done by having different number
of parameters
OOM ASSIGNMENTS
class DisplayOverloading
public void disp(char c)
System.out.println(c);
public void disp(char c, int num)
System.out.println(c + " "+num);
class Sample
public static void main(String args[])
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
Output:
a 10
Q.4. What is Method-Overriding in java?
Ans. Method overriding in JAVA
Declaring a method in sub class which is already present in parent class is known
as method overriding. Overriding is done so that a child class can give its own
implementation to a method which is already provided by the parent class. In this
case the method in parent class is called overridden method and the method in
child class is called overriding method. In this guide, we will see what is method
OOM ASSIGNMENTS
overriding in Java and why we use it.
Lets take a simple example to understand this. We have two classes: A child class
Boy and a parent class Human. The Boy class extends Human class. Both the classes
have a common method void eat(). Boy class is giving its own implementation to
the eat() method or in other words it is overriding the eat() method.
class Human{
//Overridden method
public void eat()
System.out.println("Human is eating");
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
Output:
Boy is eating
OOM ASSIGNMENTS
Assignment – 7
Q.1. What are packages in java?
Ans. Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces.
Q.2. How packages work in java?
Ans, Package names and directory structure are closely related. For example if a
package name is college.staff.cse, then there are three
directories, college, staff and cse such that cse is present in staff and staff is
present inside college. Also, the directory college is accessible
through CLASSPATH variable, i.e., path of parent directory of college is
present in CLASSPATH. The idea is to make sure that classes are easy to
locate.
Q.3. How to handle naming conflicts?
Ans. The only time we need to pay attention to packages is when we have a
name conflict . For example both, java.util and java.sql packages have a
class named Date. So if we import both packages in program as follows:
import java.util.*;
import java.sql.*;
//And then use Date class, then we will get a compile-time error :
Date today ; //ERROR-- java.util.Date or java.sql.Date?
The compiler will not be able to figure out which Date class do we want.
This problem can be solved by using a specific import statement:
import java.util.Date;
import java.sql.*;
If we need both Date classes then, we need to use a full package name
every time we declare a new object of that class.
For Example:
java.util.Date deadLine = new java.util.Date();
java.sql.Date today = new java.sql.Date();
OOM ASSIGNMENTS
Q.4. What are user-defined packages?
Ans. These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being
the package names.
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;
public class MyClass
public void getNames(String s)
System.out.println(s);
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */
import myPackage.MyClass;
public class PrintName
public static void main(String args[])
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";
// Creating an instance of class MyClass in
// the package.
MyClass obj = new MyClass();
obj.getNames(name);
}}
OOM ASSIGNMENTS
Assignment-8
Q.1 What is an exception in java is called?
Ans, In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
Q.2 What is Exception handling in java?
Ans. Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions.
Q,3 What do you mean by catching excpetions?
Ans. 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-Block of code to try i.e. creating exception
} catch (ExceptionName e1) {
// Catch block- Block of code to handle errors
The following is an array declared with 2 elements. Then the code tries to access the
element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
OOM ASSIGNMENTS
try {
int a[] = new int[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");
This will produce the following result −
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Q,4 What are the different Exception methods?
Ans, 1. public String getMessage()
Returns a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor.
2. public Throwable getCause()
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 Throwable fillInStackTrace()
OOM ASSIGNMENTS
Fills the stack trace of this Throwable object with the current stack trace,
adding to any previous information in the stack trace.