PPL June
PPL June
(May-June 2022 )
Q.1)
a) Describe primitive data types. List the primitive data types in Java and their respective
storage capacity.
Ans: Primitive data types in Java are basic data types that are predefined by the language and
are used to represent simple values. They are not objects and do not have methods. In Java,
there are eight primitive data types, each with its own storage capacity and range of values.
These primitive data types are:
These primitive data types are used to represent different types of values, such as integers,
floating-point numbers, characters, and boolean values. They are used to store data efficiently
in memory and are the building blocks of more complex data structures and objects in Java
programs.
Ans:
Java Virtual Machine (JVM) is a crucial component of the Java Runtime Environment (JRE)
responsible for executing Java bytecode. Here are some key points about JVM:
Execution Environment: JVM provides an execution environment for Java bytecode, enabling
Java programs to run on any platform that supports the JVM.
Intermediary between Java Code and Underlying Hardware: JVM acts as an intermediary
between Java code and the underlying hardware, shielding the Java developer from platform-
specific details.
Platform Independence: JVM enables platform independence by executing bytecode on any
platform that has a compatible JVM implementation, making Java a "write once, run anywhere"
language.
Memory Management: JVM manages memory allocation and deallocation dynamically during
program execution, including garbage collection to reclaim memory occupied by unused
objects.
Just-In-Time (JIT) Compilation: JVM employs Just-In-Time compilation to improve
performance. It translates bytecode into native machine code at runtime, optimizing
frequently executed code segments for faster execution.
Class Loading and Verification: JVM loads classes dynamically as needed during program
execution and verifies them to ensure they adhere to the Java language specification,
enhancing security and preventing runtime errors.
Security Manager: JVM includes a security manager that regulates the actions performed by
Java applications, providing a secure execution environment by controlling access to system
resources.
Exception Handling: JVM provides robust exception handling mechanisms to manage runtime
errors and exceptions, ensuring the reliability and stability of Java applications.
Multithreading Support: JVM supports multithreading, allowing Java programs to execute
multiple threads concurrently, enabling efficient utilization of system resources and enhancing
performance.
Debugging and Monitoring: JVM includes tools and APIs for debugging and monitoring Java
applications, facilitating the detection and resolution of issues during development and
production.
Ans: In Java, the final keyword is used to declare entities such as variables, methods, and
classes with certain characteristics. Here are the main uses of the final keyword:
Final Variables: When applied to variables, the final keyword indicates that the value of the
variable cannot be changed once it has been assigned a value. This is similar to constants in
other programming languages. Example:
final int MAX_VALUE = 100;
Final Methods: When applied to methods, the final keyword indicates that the method cannot
be overridden by subclasses. This is often used to enforce the immutability of certain behaviors
in a class's inheritance hierarchy. Example:
class Parent {
final void display() {
System.out.println("This method cannot be overridden.");
}
}
Final Classes: When applied to classes, the final keyword indicates that the class cannot be
subclassed. This is useful when you want to prevent further specialization or extension of a
class. Example:
Final Parameters: When applied to method parameters, the final keyword indicates that the
parameter cannot be modified within the method. This is useful for ensuring that the value of
the parameter remains constant throughout the method's execution. Example:
Final Fields in Objects: When applied to fields in a class, the final keyword ensures that the field
value can only be assigned once, either at the time of declaration or in the constructor. This
helps in creating immutable objects or enforcing certain invariants. Example:
class ImmutableClass {
final int value;
ImmutableClass(int value) {
this.value = value;
}
}
Q.2)
a) Define String in Java. Explain following operations of class strings in Java with example.
Ans: In Java, a String is a sequence of characters. It is a built-in class in Java and is widely used
for representing text. Strings in Java are immutable, meaning once a string object is created,
its value cannot be changed.
The length() method of the String class is used to find the length of a string, i.e., the number of
characters in the string.
Example:
String str = "Hello, World!";
int length = str.length();
System.out.println("Length of the string: " + length); // Output: 13
The equals() method is used to compare the contents of two strings for equality. It returns true
if the strings are equal, and false otherwise.
Example:
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2);
System.out.println("Strings are equal: " + isEqual); // Output: true
You can extract a character from a string using the charAt() method. It returns the character at
the specified index in the string.
Indexing starts from 0.
Example:
String str = "Java";
char ch = str.charAt(2); // Extracts character at index 2 (zero-based index)
System.out.println("Character at index 2: " + ch); // Output: v
The + operator and the concat() method are used to concatenate two strings.
Example:
String str1 = "Hello";
String str2 = "World";
// Using + operator
String result1 = str1 + " " + str2; // Concatenates str1, a space, and str2
System.out.println("Concatenated string using + operator: " + result1); // Output: Hello World
i) Secure
ii) Architectural Neutral
iii) Distributed
Ans: Java plays a significant role in the Internet landscape due to its versatility, portability, and
various features that make it suitable for developing web applications, distributed systems,
and networked services. Here's an explanation of Java's role in the Internet and how its
features justify its suitability:
i) Secure:
Java's architecture-neutral nature allows Java applications to run on any platform that
supports the Java Virtual Machine (JVM), regardless of the underlying hardware and
operating system.
Java bytecode, generated by compiling Java source code, is platform-independent,
meaning it can be executed on any device with a compatible JVM implementation.
This portability enables developers to write once and run anywhere (WORA),
simplifying the deployment and distribution of Java applications across diverse
computing environments, including web servers, desktops, mobile devices, and
embedded systems.
iii) Distributed:
Java provides extensive support for building distributed applications, enabling seamless
communication and interaction between networked components.
Java's Remote Method Invocation (RMI) framework facilitates distributed computing
by allowing objects to invoke methods on remote objects residing on different JVMs
across a network.
Java's support for network protocols, such as TCP/IP, UDP, HTTP, and FTP, enables
developers to create client-server applications, web services, and peer-to-peer
networks.
Java's built-in networking APIs, such as java.net package, provide classes and interfaces
for implementing network communication protocols and handling network-related
operations, such as socket programming, URL handling, and data transfer.
c) Summarize different access controls in Java. Explain the situation if you remove static
modifier from the main method.
Ans: In Java, access controls are mechanisms that regulate the accessibility of classes, methods,
and variables within a program. There are different access modifiers in Java, each defining the
level of access that classes, methods, or variables have in various contexts. Here's a summary
of the different access controls in Java:
Public: Public access modifier allows classes, methods, and variables to be accessed from
anywhere in the Java program, including from other packages. There are no restrictions on
access.
Private: Private access modifier restricts access to the member (method or variable) only within
the same class where it is declared. Private members cannot be accessed from outside the
class.
Protected: Protected access modifier allows access to the member within the same package
or by subclasses (inherited classes) outside the package. Protected members are not accessible
by unrelated classes outside the package hierarchy.
Q.3)
a) State the difference between character and byte stream in Java. Give any two input and any
two output classes for character streams.
Ans: In Java, character streams and byte streams are two different types of I/O streams used
for reading and writing data. Here are the main differences between character and byte
streams:
Character Streams:
Character streams are used to handle characters (Unicode characters) and are ideal for
working with text data.
They are capable of directly reading and writing characters from and to a file.
Character streams are based on character encoding, which allows them to handle
characters from different languages and character sets uniformly.
Character streams are represented by classes that end with Reader or Writer in their
names.
Byte Streams:
Byte streams are used to handle binary data, such as images, audio, and video files.
They are not designed to work directly with characters, and reading or writing text using
byte streams may lead to character encoding issues.
Byte streams handle data in the form of bytes, which are the smallest unit of data in a
computer system.
Byte streams are represented by classes that end with InputStream or OutputStream
in their names.
Two input classes for character streams in Java are:
FileReader: Reads text from character files.
BufferedReader: Reads text from a character-input stream, buffering characters to provide for
the efficient reading of characters, arrays, and lines.
b) Describe Exception. Explain keywords try, catch, throw, throws and finally related to
exception handling.
Ans: An exception in Java is an event that disrupts the normal flow of a program's execution. It
occurs during the execution of a program when an error or unexpected condition is
encountered, which prevents the program from continuing normally. Exceptions can occur for
various reasons, such as invalid input, file not found, network issues, arithmetic errors, etc.
Exception handling is a mechanism in Java that allows programmers to deal with these
unexpected conditions gracefully, by providing a way to handle errors and recover from them
without causing the program to crash. The primary components of exception handling in Java
are:
try: The try block is used to enclose the code that may potentially throw an exception. It
identifies a block of code where an exception can occur.
catch: The catch block is used to handle the exception that occurs within the corresponding try
block. It specifies the type of exception it can catch and contains the code to handle the
exception. A single try block can have multiple catch blocks to handle different types of
exceptions.
throw: The throw keyword is used to explicitly throw an exception from within a method or
block of code. It is typically used when a specific error condition is encountered that cannot be
handled locally, and the responsibility of handling the exception is delegated to the caller or
higher-level code.
throws: The throws keyword is used in method declarations to indicate that the method may
throw certain types of exceptions. It specifies the exceptions that a method can throw but does
not handle locally. When a method is declared with a throws clause, the caller of that method
must handle or propagate the exceptions.
finally: The finally block is used to execute a block of code regardless of whether an exception
occurs or not. It is usually used to release resources or perform cleanup operations that must
be executed under all circumstances. The finally block is optional and can appear after the try
block or after the last catch block.
Interfaces in Java are similar to classes but can only contain method declarations and constant
definitions. They define a contract for classes to implement, specifying a set of methods that
the implementing classes must provide. Interfaces facilitate multiple inheritance-like behavior
in Java.
Q.4)
a) Define is inheritance. List the advantages of Inheritance. Explain Simple inheritance in java
with example.
Ans: Inheritance in object-oriented programming is a mechanism by which a new class
(subclass) is created from an existing class (superclass). The subclass inherits the attributes and
methods of the superclass, allowing for code reuse and the creation of hierarchical
relationships between classes.
Advantages of Inheritance:
Code Reusability: Inheritance allows subclasses to inherit fields and methods from their
superclass, reducing the need for redundant code.
Extensibility: Subclasses can add new functionality or override existing methods inherited from
the superclass, allowing for customization and extension of behavior.
Modularity: Inheritance promotes a modular design by organizing classes into a hierarchy,
making the codebase easier to understand and maintain.
Polymorphism: Inheritance enables polymorphic behavior, where objects of different
subclasses can be treated interchangeably through their common superclass interface.
Simple Inheritance in Java:
example:
// Superclass
class Animal {
String name;
// Constructor
public Animal(String name) {
this.name = name;
}
// Method
void sound() {
System.out.println("Animal makes a sound");
}
}
// Method overriding
@Override
void sound() {
System.out.println("Dog barks");
}
// Main class
public class Main {
public static void main(String[] args) {
// Create an object of Dog class
Dog dog = new Dog("Buddy");
b) Elaborate the significance of key word “Super” in Java. Demonstrate with example for Super
keyword in Java constructor.
Ans: In Java, the super keyword is used to refer to the superclass (parent class) of the current
subclass (child class). It can be used to access superclass members (fields and methods) and to
call superclass constructors. The super keyword is particularly useful in cases of method
overriding and when dealing with constructors in inheritance.
Accessing superclass members: You can use super to access fields and methods of the
superclass that are hidden by the subclass's members.
Invoking superclass constructors: When a subclass constructor is called, the superclass
constructor is automatically invoked. However, you can use super to explicitly call a superclass
constructor from a subclass constructor, allowing for initialization of superclass-specific fields
or executing superclass-specific logic.
Example of super keyword in Java constructor:
class Animal {
String name;
// Superclass constructor
public Animal(String name) {
this.name = name;
System.out.println("Animal constructor called");
}
void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Subclass constructor
public Dog(String name, int age) {
super(name); // Call superclass constructor
this.age = age;
System.out.println("Dog constructor called");
}
void wagTail() {
System.out.println("Dog wags tail");
}
}
c) State the importance of finally blocks. Illustrate the ways finally block differ from finalize()
method.
Ans: The finally block is an important part of exception handling in Java. It is used to ensure
that a block of code is executed, regardless of whether an exception is thrown or not. This can
be useful for cleaning up resources, such as closing files or releasing database connections.
The finalize() method is a method that is called by the garbage collector before an object is
destroyed. It can be used to perform cleanup activities, such as closing files or releasing
resources. However, the finalize() method is not guaranteed to be called, and it should not be
relied upon for critical cleanup operations.
Here are some of the key differences between finally blocks and finalize() methods:
Execution:
Finally blocks are always executed, regardless of whether an exception is thrown or not.
Finalize() methods are only called when the garbage collector decides to destroy an object.
Purpose:
Finally blocks are typically used for cleanup operations. Finalize() methods can be used for
cleanup operations, but they can also be used for other purposes, such as logging or debugging.
Reliability:
Finally blocks are more reliable than finalize() methods. Finalize() methods are not guaranteed
to be called, and they can be delayed or even ignored by the garbage collector.
Q.5)
a) Interpret the terms multitasking and multiprocessing and multithreading in Java with
example.
Multitasking:
Multitasking refers to the ability of a system to execute multiple tasks or processes
concurrently. It can be achieved through time-sharing or context switching, where the
CPU rapidly switches between executing different tasks.
In Java, multitasking can be achieved using threads. Java provides built-in support for
multithreading, allowing developers to create concurrent applications that perform
multiple tasks simultaneously.
Multiprocessing:
Multiprocessing involves the simultaneous execution of multiple processes by utilizing
multiple CPUs or CPU cores. Each process runs independently and can execute different
tasks or parts of the same task.
In Java, multiprocessing can be achieved by running multiple Java Virtual Machines
(JVMs) on a system, each running a separate Java application or process. Java
applications can also utilize native libraries or external tools to interact with
multiprocessing capabilities provided by the underlying operating system.
Multithreading:
Multithreading involves the concurrent execution of multiple threads within the same
process. Threads share the same memory space and resources of the process and can
perform different tasks concurrently.
In Java, multithreading is achieved by creating and managing threads using the Thread
class or implementing the Runnable interface. Java provides extensive support for
multithreading through its java.lang.Thread class and related APIs, allowing developers
to create responsive and efficient concurrent applications.
Example:
// Start threads
thread1.start();
thread2.start();
}
}
Ans: AngularJS, a popular JavaScript framework developed and maintained by Google, offers a
wide range of features, advantages, and limitations:
Features of AngularJS:
MVC Architecture:
AngularJS follows the Model-View-Controller (MVC) architectural pattern, facilitating the
development of well-structured and maintainable web applications. It separates concerns by
organizing code into distinct modules for models, views, and controllers.
Directives:
Directives are reusable components in AngularJS that extend HTML with custom attributes and
behaviors. They enable developers to create dynamic and interactive web applications by
adding functionality to HTML elements.
Advantages of AngularJS:
Productivity:
AngularJS simplifies web development by providing a comprehensive framework with built-in
features and utilities. It reduces boilerplate code and allows developers to focus on application
logic rather than low-level implementation details.
Modularity:
AngularJS promotes modular development through its component-based architecture and
dependency injection system. Developers can easily organize code into reusable components,
making it easier to maintain and extend applications.
Testability:
AngularJS is designed with testability in mind, making it easy to write unit tests and end-to-end
tests for AngularJS applications. Its dependency injection system allows for easy mocking and
testing of components, promoting code quality and reliability.
Limitations of AngularJS:
Performance Overhead:
AngularJS imposes some performance overhead due to its features like two-way data binding,
digest cycle, and dependency injection. While optimizations can mitigate these issues, large
and complex AngularJS applications may still experience performance bottlenecks.
<div class="container">
<h2>Login</h2>
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<script>
document.getElementById("loginForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent form submission
</body>
</html>
Q.6)
Ans:
Popularity and Community Support:
React.js: Developed by Facebook, React has gained immense popularity and has a large
and active community of developers. It is widely used in industry-leading projects.
Angular.js: Developed and maintained by Google, Angular has a strong backing and is
used in many Google applications. It has a large community and comprehensive
documentation.
Vue.js: Developed by Evan You, Vue has seen significant growth in recent years and has
a growing community. It is known for its simplicity and ease of learning.
Learning Curve:
React.js: React has a relatively shallow learning curve, especially for developers already
familiar with JavaScript. However, mastering advanced concepts like Redux for state
management may require additional effort.
Angular.js: Angular has a steeper learning curve due to its comprehensive features and
concepts like dependency injection, modules, and decorators.
Vue.js: Vue strikes a balance between React and Angular, offering simplicity and ease
of learning while providing powerful features for building complex applications.
Component-Based Architecture:
React.js: React is known for its component-based architecture, where UIs are
composed of reusable components. It uses a virtual DOM for efficient updates.
Angular.js: Angular also follows a component-based architecture, with components as
the building blocks of the application. It uses two-way data binding for automatic
synchronization of the model and view.
Vue.js: Vue shares similarities with both React and Angular in terms of component-
based architecture. It provides a flexible and intuitive way to compose components and
manage state.
State Management:
React.js: React's core library focuses on the view layer, leaving state management up
to developers. Redux and Context API are popular choices for managing state in React
applications.
Angular.js: Angular provides built-in tools like services and RxJS for managing
application state. It also offers features like dependency injection for handling shared
state.
Vue.js: Vue offers Vuex, a state management library inspired by Redux, for managing
state in Vue applications. It provides a centralized store for managing all application
state.
Ans: The thread class provides methods getPriority() and setPriority() for managing the priority
of threads in a multithreaded application. These methods are used to control the scheduling
behavior of threads by assigning them different priorities. Here's an explanation of each
method with examples:
getPriority() Method:
The getPriority() method is used to retrieve the priority of a thread.
It returns an integer value representing the priority of the thread.
Thread priorities are represented by integer values ranging from 1 to 10, where 1 is the
lowest priority and 10 is the highest priority.
The default priority of a thread is set to 5.
Higher priority threads are scheduled to run before lower priority threads, but the exact
behavior depends on the underlying operating system's thread scheduler.
Example:
public class GetPriorityExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread Priority: " + Thread.currentThread().getPriority());
});
thread.start();
System.out.println("Main Thread Priority: " + Thread.currentThread().getPriority());
}
}
setPriority() Method:
The setPriority() method is used to set the priority of a thread.
It takes an integer argument representing the new priority of the thread.
The argument value must be in the range of 1 to 10.
If the specified priority value is out of the valid range, it will throw an
IllegalArgumentException.
It is important to note that setting the priority of a thread does not guarantee the
thread will be scheduled accordingly, as it depends on the underlying operating
system's thread scheduler.
Example:
public class SetPriorityExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread Priority: " + Thread.currentThread().getPriority());
});
thread.setPriority(Thread.MAX_PRIORITY); // Set thread priority to maximum
thread.start();
}
}
c) Explain the uses of isAlive() and Join() methods in Java thread with example.
Ans: The isAlive() and join() methods are used for thread management and synchronization.
Here's an explanation of each method along with examples:
isAlive() Method:
The isAlive() method is used to check whether a thread is alive or not.
A thread is considered alive from the moment it is started using the start() method until
it completes its execution or is terminated.
It returns a boolean value true if the thread is alive, and false otherwise.
This method is often used to check the status of a thread before performing certain
actions or making decisions based on its execution status.
Example:
public class IsAliveExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(2000); // Simulate some task
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
try {
thread.join(); // Wait for the thread to complete
} catch (InterruptedException e) {
e.printStackTrace();
}
join() Method:
The join() method is used to wait for a thread to complete its execution before
proceeding with the execution of the current thread.
It blocks the calling thread until the thread on which it is called completes execution or
until a specified timeout period expires.
If the specified timeout value is zero, the calling thread will wait indefinitely until the
target thread completes.
This method is often used to ensure that certain tasks are executed in a specific order
or to coordinate the execution of multiple threads.
Example:
public class JoinExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 started");
try {
Thread.sleep(2000); // Simulate some task
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 completed");
});
thread1.start();
thread2.start();
try {
thread1.join(); // Wait for thread1 to complete
thread2.join(); // Wait for thread2 to complete
} catch (InterruptedException e) {
e.printStackTrace();
}
Q.7)
a) Describe Functional Programming. Enlist its features. Also list the commonly used functional
programming languages.
Ans: Functional programming (FP) is a programming paradigm that treats computation as the
evaluation of mathematical functions and avoids changing-state and mutable data. It
emphasizes the use of functions that take input and produce output without modifying state
or data outside the function itself. Here are the key features of functional programming:
First-class and Higher-order Functions: Functions are treated as first-class citizens, meaning
they can be assigned to variables, passed as arguments to other functions, and returned as
values from other functions. Higher-order functions can take other functions as arguments or
return them.
Pure Functions: Pure functions are functions that always return the same output for the
same input and have no side effects. They do not rely on or modify external state and only
depend on their input parameters.
Haskell
Scala
Clojure
Erlang
F#
b) Write sequences of CAR’s and CDR’s that will pick the atom pear our of the following s-
expression :
i) (apple orange pear grapes)
ii) ((apple orange) (pear grapes))
iii) (((apple)(orange) (pear) (grapes)))
Ans:
i) (apple orange pear grapes)
Ans: In Prolog, structures are compound terms that consist of a functor (a predicate or
function symbol) and a fixed number of arguments. Structures are used to represent complex
data structures or relationships between entities in the problem domain. They allow Prolog
programmers to organize and manipulate data in a structured and meaningful way.
Q.8)
a) Describe Logical Programming. Enlist its features. Also list the commonly used Logical
programming languages.
Ans: Logical programming is a programming paradigm based on formal logic, where programs
are expressed as sets of logical statements or rules that define relationships and constraints
among entities. In logical programming, computation is achieved through logical inference,
where the program logic is used to derive conclusions from given facts and rules.
b) Write a LISP program to find the factorial of n numbers using recursion concept.
Ans:
i) NUMBERP
ii) ZEROP
iii) PLUSP
iv) EVENP
v) ODDP
Ans:
i) NUMBERP: This predicate checks whether its argument is a number or not. It returns T if
the argument is a number, otherwise NIL.
ii) ZEROP: This predicate checks whether its argument is zero or not. It returns T if the
argument is zero, otherwise NIL.
iv) EVENP: This predicate checks whether its argument is an even number or not. It returns T
if the argument is even, otherwise NIL.
v) ODDP: This predicate checks whether its argument is an odd number or not. It returns T if
the argument is odd, otherwise NIL.
https://www.instagram.com/sppu_engineering_update
https://t.me/SPPU_TE_BE_COMP
https://www.whatsapp.com/channel/0029VaAhRMdAzNbmPG0jyq2x