0% found this document useful (0 votes)
11 views69 pages

PPL 3-6

The document provides an in-depth overview of Java features, including security, platform independence, object-oriented principles, and garbage collection. It explains constructors, arrays, strings, command-line arguments, primitive data types, and access controls, along with examples for clarity. Additionally, it includes Java programming exercises related to basic operations and inheritance.

Uploaded by

prajwalcharthad6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views69 pages

PPL 3-6

The document provides an in-depth overview of Java features, including security, platform independence, object-oriented principles, and garbage collection. It explains constructors, arrays, strings, command-line arguments, primitive data types, and access controls, along with examples for clarity. Additionally, it includes Java programming exercises related to basic operations and inheritance.

Uploaded by

prajwalcharthad6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Unit 3

1. Explain following features of java in detail


i) Security
 Java is designed to be secure. It runs programs inside a
protected area called the Java sandbox, preventing access to
system resources like files or memory unless allowed. It also
uses bytecode verification and security managers to protect
users from malicious code.

ii) Platform Independence


 Java code is written once and run anywhere. It gets compiled
into bytecode, which can run on any machine that has the
Java Virtual Machine (JVM), regardless of the operating
system.

iii) Object – oriented


 Java uses the object-oriented programming (OOP) model,
where everything is represented as objects. Concepts like
inheritance, encapsulation, abstraction, and polymorphism
help make code reusable, organized, and easy to maintain.

iv) Portability
 Java programs can be moved from one system to another
without any changes. Since bytecode runs on JVM, and JVMs
are available on many platforms, Java code is highly portable.

v) Distributed
 Java supports distributed computing, meaning programs can
run on multiple systems connected via a network.
Technologies like RMI (Remote Method Invocation) and EJB
(Enterprise JavaBeans) help Java applications communicate
across systems.

vi) Robust
 Java is reliable and handles errors effectively. It checks code
during both compile-time and runtime. Features like
exception handling, garbage collection, and strong memory
management help Java avoid crashes and bugs.

2. Write short note on


i) Garbage collector
The Garbage Collector (GC) in Java is a process that
automatically deallocates memory by removing objects that
are no longer referenced or used. It helps in efficient memory
management by reclaiming heap space, thus preventing
memory leaks and improving performance. Developers do not
need to manually free memory, unlike in C/C++.

ii) this
 The this keyword is a reference variable in Java that refers to
the current object. It is used to:
 Differentiate between instance variables and parameters with
the same name.
 Call another constructor in the same class.
 Pass the current object as a parameter. Eg : this.name =
name;

i) final
 The final keyword means "cannot be changed."
 Final variable = value can't change
 Final method = can't be overridden
 Final class = can't be inherited

ii) finalize()
 It’s a special method that runs just before the object is
deleted from memory. You can use it to clean things up like
closing files or connections.

iii) static
 Static means the variable or method belongs to the class,
not to any object.
 You can use it without creating an object.
 Eg : ClassName.methodName(); // static method call

iv) references
 A reference is like a remote control that controls an object. It
doesn’t store the object, just points to it in memory.
 Eg : Car myCar = new Car(); // myCar is a reference to a Car
object

3. Define constructor. Which are the types of Constructor


used in Java? Explain with example
 A constructor is a special method in Java that is used to create
(or initialize) an object. It has the same name as the class and
doesn’t have a return type, not even void.
 When you create an object using new, the constructor is called
automatically.
 A constructor is like a special method that runs automatically
when you create an object of a class.
Types :-
1.Default Constructor
 This is a constructor without any parameters.
 If you don’t write any constructor, Java automatically gives you
one.
Example:
CopyEdit
class Car {
Car() { // Default constructor
System.out.println("Car is created");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Constructor is called
}
}
Output: Car is created

2. Parameterized Constructor
 This constructor accepts arguments (parameters).
 Used when you want to set values during object creation.
Example:
java
CopyEdit
class Car {
String model;
Car(String m) { // Parameterized constructor
model = m;
System.out.println("Model: " + model);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("BMW");
}}
🟢 Output: Model: BMW

4. Explain one dimensional and multi - dimensional array


used in Java with suitable examples.
 An array is a collection of similar types of data stored in a
single variable.
 It helps when you want to store multiple values (like numbers
or names) instead of creating separate variables.
1. One-Dimensional Array (1D Array)
Definition:
 A one-dimensional array is a single row of elements.
 It stores a list of values of the same data type, accessed using a
single index.
 Think of it like a line of lockers or a list.
Example:
int[] numbers = {10, 20, 30, 40, 50};
You can access elements like:
System.out.println(numbers[2]); // Output: 30

2. Multi-Dimensional Array
Definition:
 A multi-dimensional array is an array that contains more than
one row or column.
 The most common is the two-dimensional array, which looks
like a table or matrix.
 You use two indexes to access the elements: one for row, one
for column. };
Example: You can access elements
int[][] matrix = { like:
{1, 2, 3}, System.out.println(matri
x[1][2]); // Output: 6
{4, 5, 6}
5. Define String in Java programming. Explain the following
operations of class string in Java with example.
 In Java, a String is a sequence of characters used to represent
textual data such as names, sentences, symbols, or any
combination of letters, numbers, and special characters.
 Unlike primitive data types like int or char, a String is an object
of the String class in Java, found in the java.lang package.
 Strings in Java are immutable, which means once a string is
created, it cannot be changed. If you modify a string, Java
creates a new one in the background. This makes strings
secure, thread-safe, and efficient for memory handling.

i) To find the length of a string.


 To find out how many characters are in a string, use
the .length() method.
This includes spaces, letters, numbers, and special characters.
Example:
String city = "Gotham";
System.out.println(city.length()); // Output: 6
✔ length() returns 6 because there are 6 characters in "Gotham".

ii) To compare two strings


 You can compare two strings in Java in two main ways:
.equals() → Checks if two strings are exactly the same (case-
sensitive).
.compareTo() → Compares strings alphabetically
(lexicographically).
Example:
String a = "Knight";
String b = "knight";
System.out.println(a.equals(b)); // false (case matters)
System.out.println(a.compareTo(b)); // returns a negative or
positive number

✔ equals() is true only when all characters match exactly.


✔ compareTo() returns 0 if both are equal, a negative number if
a < b, and positive if a > b.

iii) Extraction of character from a string


 To get a single character from a string, use .charAt(index).
The index starts from 0 (just like arrays).
Example:
String name = "Batman";
System.out.println(name.charAt(2)); // Output: t
✔ charAt(2) gives you the 3rd character because index starts
at 0.

iv) To concatenate two strings


 To join or combine two strings into one, use
1. The + operator
2. The .concat() method
Example:
String first = "Dark";
String second = "Knight";
System.out.println(first + " " + second); // Output: Dark
Knight
System.out.println(first.concat(" ").concat(second)); // Output:
Dark Knight
✔ Both methods give the same result.
✔ concat() joins without adding spaces unless you do it
manually.

v) To search a substring
 You can search for a part of a string using:
1).contains() → checks if a substring exists.
2).indexOf() → tells where it starts (returns -1 if not found).
Example:
String dialogue = "I am Batman";
System.out.println(dialogue.contains("Bat")); // true
System.out.println(dialogue.indexOf("Bat")); // 5
✔ contains() is a quick yes/no check.
✔ indexOf() is useful if you want the exact position of the
word.
7. Explain command line arguments and variable length
arguments in Java with an example.
 The command-line arguments in Java allow us to pass
arguments during the execution of the program.
 As the name suggests arguments are passed through the
command line.
 Command Line Arguments are inputs (values) you can pass to a
Java program when you run it from the command line or
terminal.
 These arguments allow your program to take different inputs
without changing the code.
 The values are passed when starting the Java program and are
stored as strings in the String [] args array of the main ()
method.
Example:
class Main {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for(int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}}}
Input
javac Main.java // Compiles the code
java Main Batman Robin Joker
Output
Number of arguments: 3
Argument 0: Batman
Argument 1: Robin
Argument 2: Joker

VARIABLE LENGTH ARGUMENTS:


 Variable Length Arguments (Varargs) allow a method to accept
zero or more arguments of the same type.
You don't have to know in advance how many values you want
to pass.
 In Java, varargs are written with three dots ... after the data
type.
 It bundles all passed values into an array automatically inside
the method.
Example:
class Main {
static void displayNames(String... names) {
System.out.println("Number of names: " + names.length);
for (String name : names) {
System.out.println(name);
}
public static void main(String[] args) {
displayNames("Batman", "Robin", "Batgirl");
displayNames("Joker");
displayNames(); // No names passed
}
}
Output:
Number of names: 3
Batman
Robin
Batgirl
Number of names: 1
Joker
8. Describe primitive data types. List the primitive data
types in Java and their respective storage capacity.
1 bit (depends on JVM) boolean
1 byte (8 bits) byte
2 bytes (16 bits) short

2 bytes (16 bits) char

4 bytes (32 bits) int

4 bytes (32 bits) float

8 bytes (64 bits) long

8 bytes (64 bits) double

9. Write short notes on Java Virtual Machine (JVM) with


diagram.
 Java Virtual Machine (JVM) is a virtual computer or software-
based engine that runs Java programs.

 It converts the compiled Java bytecode (.class file) into


machine code so that the underlying computer's CPU can
understand and execute it.
 JVM is the heart of Java's platform independence, meaning
Java programs can run on any device that has a JVM installed
— "Write Once, Run Anywhere."
 Java applications are called WORA (Write Once Run Anywhere).
This means a programmer can develop Java code on one
system and expect it to run on any other Java-enabled system
without any adjustment. This is all possible because of JVM.

10. Summarize different access controls in Java. Explain the


situation if you remove static modifier from the main
method.
 In Java, Access Modifiers decide which classes, methods, or
variables can be seen or used by other classes.
 They control visibility and security of parts of your code.
 Access control is very important for:
- Protecting data (security)
- Designing clean and modular code
- Avoiding unintended use of variables/methods by outside
classes
1.Default
 If we do not explicitly specify any access modifier for classes,
methods, variables, etc, then by default the default access
modifier is considered.
For example,
package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}
2.Private
 When variables and methods are declared private, they cannot
be accessed outside of the class.
For example,
class Example {
private int number = 10; // private variable
void display() {
System.out.println("Number is: " + number);
}
}
class Test {
public static void main(String[] args) {
Example obj = new Example();
obj.display(); // OK
// System.out.println(obj.number); // ❌ Error: number is private
}
}
3.Protected
 When methods and data members are declared protected, we
can access them within the same package as well as from
subclasses.
For example,
class Example {
protected int number = 30; // protected variable
protected void display() {
System.out.println("Number is: " + number);
}}
class Test extends Example {
public static void main(String[] args) {
Test obj = new Test();
obj.display(); // OK: Subclass can access protected
}}

4. Public
When methods, variables, classes, and so on are declared public,
then we can access them from anywhere. The public access
modifier has no scope restriction.
For example,
public class Example {
public int number = 40; // public variable
public void show() {
System.out.println("Number is: " + number);
}}
class Test {
public static void main(String[] args) {
Example obj = new Example();
obj.show(); // OK: Public method and variable
}}
PROGRAMS

11. Write a program in Java using switch-case statement to


perform addition, subtraction, Multiplication and Division
of given two numbers and print the result.

import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
System.out.println("Choose operation:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.print("Enter your choice (1-4): ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Result: " + (num1 + num2));
break;
case 2:
System.out.println("Result: " + (num1 - num2));
break;
case 3:
System.out.println("Result: " + (num1 * num2));
break;
case 4:
System.out.println("Result: " + (num1 / num2));
break;
default:
sc.close();
}}

13. Write a program in Java to perform the addition of two


matrices (multidimensional arrays) and set the diagonal
elements of resultant matrix to 0.
14. Write a program which receives n integers. Store the
integers in an array. Program outputs the number of odd
and even numbers present in this array
6. Write a program to print the area of a circle by creating
a class named 'Area' having two methods. First method
named as 'setRadius' takes the radius of the circle as a
parameter and the second method, named as get 'Area'
returns the area of the circle. The radius of circle is entered
through the keyboard?
Unit 4

1) What is mean by inheritance? Explain the various types


of inheritance used in Java with suitable example.
 Inheritance is an object-oriented programming concept in Java.
 It allows one class (called the subclass or child class) to
derive/inherit the properties and behaviors of another class
(called the superclass or parent class).
 It promotes code reusability, supports method overriding, and
enables polymorphism by allowing a subclass to extend and
customize the functionality of its superclass.
Types of Inheritance in Java:
1. Single Inheritance
 A single subclass inherits from one superclass.
Example:
class Animal {
void eat() {
System.out.println("Animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
2. Multilevel Inheritance
 A class inherits from a derived class, forming a chain of
inheritance.
Example:
class Animal {
void eat() {
System.out.println("Animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Puppy weeps");
}}
3. Hierarchical Inheritance
 Multiple subclasses inherit from a single superclass.
Example:
class Animal {
void eat() {
System.out.println("Animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
4. Hybrid Inheritance (Using Interfaces)
 Combination of multiple inheritance types. Since Java doesn’t
support multiple inheritance with classes, interfaces are used.
Example:
interface Printable {
void print();
}
interface Showable {
void show();
}
class Demo implements Printable, Showable {
public void print() {
System.out.println("Printing");
}
public void show() {
System.out.println("Showing");
}
}

2) Explain following keywords of Java in detail i) try ii)


catch iii) finally Iv) throw v) throws
i) try
 The try block is used to enclose the code that might throw an

exception.
 It must be followed by either a catch block or a finally block.

 If an exception occurs in the try block, it is caught by the

corresponding catch block.


Example:
try {
int a = 10 / 0; // may cause ArithmeticException
}

ii) catch
 The catch block handles the exception thrown by the try block.

 Each catch block handles a specific type of exception.

 Multiple catch blocks can be used to handle different

exceptions.
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}

iii) finally
 The finally block contains code that is always executed after

the try block, regardless of whether an exception occurred or


not.
 It is used to release resources like file handles, database

connections, etc.
Example:
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught");
} finally {
System.out.println("Finally block executed");
}

iv) throw
 The throw keyword is used to explicitly throw an exception,

either predefined or user-defined.


 It is followed by an object of Throwable class or its subclass.

Example:
throw new ArithmeticException("Divide by zero error");

v) throws
 The throws keyword is used in the method declaration to

indicate that the method might throw one or more exceptions.


 It informs the caller of the method to handle those exceptions.

Example:
void myMethod() throws IOException {
// code that may throw IOException
}

3) Define package used in Java. Explain syntax, use,


CLASSPATH, hierarchy of package with example.
 A package in Java is a namespace used to group related
classes and interfaces together in an organized way.
 It functions like a folder in a file system.
 It helps avoid naming conflicts, enhances code modularity, and
improves maintainability
Java provides two types of packages:
 Built-in packages (like java.util, java.io, etc.)
 User-defined packages (created by programmers)

Syntax of Package:
 To define a package, use the package keyword as the first
statement in the Java source file.
package mypackage; // syntax to define a package
public class MyClass {
public void display() {
System.out.println("Inside package");
}
}
To use this class in another file:
import mypackage.MyClass; // importing class from package
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Use of Packages:
1. Namespace Management: Avoids class name conflicts.
2. Access Protection: Provides access control through public,
private, protected.
3. Code Reusability: Makes code modular and reusable.
4. Organized Development: Helps in logically organizing files in
large projects.

CLASSPATH in Java:
 CLASSPATH is an environment variable that tells the Java
compiler and JVM where to find user-defined classes and
packages.
 If your package is stored in a specific directory, that path must
be included in the CLASSPATH.
Setting CLASSPATH Example (command line):
set CLASSPATH=C:\JavaPrograms
Hierarchy of Packages:
Packages can be nested, forming a hierarchy like directories.
package college.engineering.computer;

public class Student {


public void show() {
System.out.println("Student of Computer Department");
}
}
This will be stored in the directory path:
college/engineering/computer/Student.java
To use:
import college.engineering.computer.Student;

4) Explain various Exception Handing mechanisms in Java


 Exception handling in Java is a powerful mechanism that allows
programmers to manage runtime errors, so the normal flow of
the program can be maintained.
 An exception is an event that disrupts the normal flow of a
program during execution.
Types of Exceptions in Java:
1. Checked Exceptions – Checked at compile-time (e.g.,
IOException, SQLException)
2. Unchecked Exceptions – Occur at runtime (e.g.,
ArithmeticException, NullPointerException)
3. Errors – Serious problems that a program should not try to
handle (e.g., OutOfMemoryError)
Java Exception Handling Mechanisms:
Java provides five keywords to handle exceptions:
Try, catch, finally, throw, throws from q no 2.
Custom Exception Handling (User-Defined Exceptions):
You can define your own exception by extending the Exception
class.
Example: super(msg);
class MyException extends Exception { }
MyException(String msg) { }
5) What is the concept of stream , State the difference
between character and byte stream in Java. Give any two
input and any two output classes for character streams
 In Java, a stream is a sequence of data used for reading from or
writing to different input/output sources like files, memory, or
network.
 Java provides the java.io and java.nio packages to handle I/O
operations using streams.
Streams are of two main types:
1. Byte Streams – Handle binary data (8-bit)
2. Character Streams – Handle text data (16-bit Unicode)
Byte Stream Character Stream
Handles raw binary data (8-bit) Handles character data (16-bit
Unicode)
Uses classes like InputStream, Uses classes like Reader, Writer
OutputStream
Suitable for images, audio, video Suitable for reading and writing
files text files
Does not perform character Automatically handles encoding
encoding/decoding and decoding
Character Stream Classes in Java:
Two Input Classes (from java.io.Reader):
1. FileReader
o Used to read data from a file as characters.
FileReader fr = new FileReader("file.txt");
2. BufferedReader
o Wraps FileReader for efficient reading of characters,
arrays, or lines.
BufferedReader br = new BufferedReader(new
FileReader("file.txt"));
Two Output Classes (from java.io.Writer):
1. FileWriter
o Used to write character data to a file.
FileWriter fw = new FileWriter("output.txt");
2. BufferedWriter
o Wraps FileWriter for efficient writing of characters or
strings.
BufferedWriter bw = new BufferedWriter(new
FileWriter("output.txt"));

6) Elaborate the significance of key word “Super” in Java.


Demonstrate with example for Super keyword in Java
constructor.
 The super keyword in Java is used to refer to the immediate
parent class object.
 It is mainly used in inheritance to access methods, variables,
and constructors of the parent class.
Uses of super Keyword:
1. Accessing parent class variables when they are hidden by child
class
2. Calling parent class methods that are overridden
3. Invoking parent class constructor from child class constructor
Use of super in Constructor:
 When a subclass constructor calls super(), it invokes the
constructor of its immediate parent class.
 It must be the first statement in the subclass constructor.
 This is useful when the parent class constructor needs to be
called for initialization.
Example: super keyword in constructor
class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}
class Dog extends Animal {
Dog() {
super(); // calling parent class constructor
System.out.println("Dog constructor called");
}
}

public class Test {


public static void main(String[] args) {
Dog d = new Dog();
}
}
7) State the importance of finally blocks. Illustrate the
ways finally block differ from finalize() method.
 The finally block in Java is used for resource cleanup.
 It is always executed after the try and catch blocks, regardless
of whether an exception was thrown or not.
Importance:
 It is used to close or release resources like files, database
connections, or network sockets.
 It ensures that essential cleanup code is executed even if an
exception occurs.
 It is optional, but if used, it must follow either a try or a catch
block.

Example of finally Block:


public class Test {
public static void main(String[] args) {
try {
int a = 10 / 0; // Causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("finally block is always executed");
}
}
}
Difference Between finally and finalize() in Java:
finally Block finalize() Method
Used for exception handling Used for garbage collection
Always executes after Called by JVM before destroying an
try/catch blocks object
Used to close resources like Used to perform cleanup before
files, DB, etc. object is collected
Runs every time the code is Runs only once in the object's
executed lifecycle (if at all)
Defined as a block after try- Defined as a method in a class:
catch protected void finalize()

8) Explain with example how the access protection is


provided for packages in java?
 Java provides access control mechanisms using access specifiers
(modifiers) to protect classes, methods, and variables across
packages.
 These access specifiers define how the members of a class are
accessed within and across packages.
Access Specifiers in Java:
Access Within Class Within Outside Package (via Outside
Modifier Package subclass) Package
private Yes No No No

default Yes Yes No No

protected Yes Yes Yes No

public Yes Yes Yes Yes

Package 1: mypack/BaseClass.java
package mypack;
public class BaseClass {
public int a = 10;
protected int b = 20;
int c = 30; // default
private int d = 40;

public void show() {


System.out.println("Public: " + a);
System.out.println("Protected: " + b);
System.out.println("Default: " + c);
System.out.println("Private: " + d);
}
}
Package 2: otherpack/Derived.java
package otherpack;
import mypack.BaseClass;
public class Derived extends BaseClass {
public void display() {
System.out.println("Accessing from other package:");
System.out.println("Public: " + a); // Allowed
System.out.println("Protected: " + b); // Allowed (via
subclass)
// System.out.println(c); // Error - default not accessible
// System.out.println(d); // Error - private not accessible
}}
Main File: TestAccess.java
import otherpack.Derived;
public class TestAccess {
public static void main(String[] args) {
Derived obj = new Derived();
obj.display();
}
}

9) What are uncaught exceptions? Illustrate with example


the use of try( ), catch( ) and throw( ) methods in
exception handling?
 An uncaught exception is an exception that occurs during the
execution of a program but is not handled using a try-catch
block.
 When this happens, the program terminates abnormally, and the
Java Runtime System prints a stack trace of the error.
________________________________________
Example of an Uncaught Exception:
public class Test {
public static void main(String[] args) {
int a = 10 / 0; // Causes ArithmeticException
System.out.println("This line will not execute.");
}
}

10) Elaborate on the significance of the keyword '' final'' in


java. With code example of each case.
 The final keyword in Java is used to define constants, prevent
method overriding, and prevent inheritance.
 It has different uses depending on where it is applied — to
variables, methods, and classes.
Examples of final Keyword Usage:
1. final Variable Example:
A variable marked with final can only be assigned a value once.
Any attempt to change it later results in a compile-time error.
public class FinalVariableExample {
final int maxSpeed = 120; // Final variable
public static void main(String[] args) {
FinalVariableExample obj = new FinalVariableExample();
// obj.maxSpeed = 140; // Error: cannot assign a value to final
variable
System.out.println("Max Speed: " + obj.maxSpeed);
}
}
2. final Method Example:
A final method cannot be overridden by any subclass.
class Parent {
public final void display() {
System.out.println("Parent class display()");
}
}
class Child extends Parent {
// This will cause a compile-time error because display() is final
in Parent class.
// public void display() {
// System.out.println("Child class display()");
// }
}
public class FinalMethodExample {
public static void main(String[] args) {
Parent obj = new Parent();
obj.display(); // Output from Parent class
}
}
3. final Class Example:
A class marked as final cannot be subclassed.
final class FinalClass {
public void show() {
System.out.println("This is a final class.");
}
}
// This will cause a compile-time error because FinalClass cannot be
subclassed.
// class SubClass extends FinalClass {
// }
public class FinalClassExample {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.show();
}
}

11) Explain following concepts with example. [8] i) abstract


classes ii) Method Overloading iii) package iv)interface
v) dynamic dispatch vi) polymorphism
i) Abstract Classes:
 An abstract class in Java is a class that cannot be instantiated
directly.
 It is designed to be subclassed, and it can contain abstract
methods (methods without a body) and concrete methods
(methods with a body).
 Abstract class: A class that contains abstract methods or is
specifically declared as abstract.
 Abstract method: A method without implementation, to be
implemented by subclasses.
Example:
abstract class Animal {
// Abstract method (no implementation)
abstract void sound();

// Regular method
void sleep() {
System.out.println("Animal is sleeping");
}
}

class Dog extends Animal {


// Providing implementation of the abstract method
void sound() {
System.out.println("Bark");
}
}

public class Test {


public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
myDog.sound(); // Calls Dog's sound method
myDog.sleep(); // Calls the sleep method of Animal
}
}
ii) Method Overloading:
 Method overloading is a concept where multiple methods can
have the same name but different parameters (number, type,
or both) within the same class.
 The return type can be the same or different, but it does not
contribute to overloading.
Example:
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two doubles
double add(double a, double b) {
return a + b;
}
}
public class Test {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // Calls the method with
two integers
System.out.println(calc.add(2, 3, 4)); // Calls the method
with three integers
System.out.println(calc.add(2.5, 3.5)); // Calls the method
with two doubles
}
}
iv) Interface:
 An interface in Java is a reference type that defines a set of
abstract methods that a class must implement.
 It allows classes from different hierarchies to have common
behaviors.
Example:
interface Animal {
void sound(); // Abstract method
}

class Dog implements Animal {


public void sound() {
System.out.println("Bark");
}
}

class Cat implements Animal {


public void sound() {
System.out.println("Meow");
}
}
public class Test {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.sound(); // Calls Dog's sound method
myCat.sound(); // Calls Cat's sound method
}
}

v) Dynamic Dispatch:
 Dynamic dispatch refers to the process by which a method call
is resolved at runtime, based on the actual object type, not the
reference type.
 It is an important feature of runtime polymorphism.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Reference type is Animal, but
object is Dog
myAnimal.sound(); // Calls Dog's sound method
(dynamic dispatch)
}
}
vi) Polymorphism:
 Polymorphism in Java refers to the ability of an object to take
on many forms.
 It allows methods to perform different tasks based on the
object’s actual class type.
 Polymorphism can be categorized into:
 Compile-time polymorphism (Method Overloading)
 Runtime polymorphism (Method Overriding)
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class Test {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.sound(); // Calls Animal's sound
myDog.sound(); // Calls Dog's sound
myCat.sound(); // Calls Cat's sound
}
}

12) Write a program to create interface A in a package; in


this interface we have two methods meth1 and meth2.
Implements this interface in another class named
MyClass by importing your package

Unit 5
1)Explain different ways to implement Threads in Java?
With code example.
 In Java, a Thread is a lightweight, smallest unit of processing. It
is like a small program inside a bigger program that can run
independently and parallelly with other threads.
 Threads are used to do multiple tasks at the same time
without waiting for one task to finish first.
 For example, while playing a video game, you can move the
character (one task) while the background music plays
(another task). Both happen together using threads.
 Java supports multithreading, which makes programs faster,
responsive, and efficient.
 A thread has its own lifecycle (New ➔ Runnable ➔ Running ➔
Dead).

2) Explain the below methods in detail.


i) isAlive()
 The isAlive() method in Java is used to check whether a thread
is still running or has finished its execution.
 It returns a boolean value:
- true → if the thread is still running (alive)
- false → if the thread has finished (dead)
 This method is useful when you want to know if a particular
thread is still working before doing other operations.
 Syntax - boolean isAlive()
Example:
Thread t1 = new Thread();
t1.start();
System.out.println(t1.isAlive()); // true
ii) Notify
 The notify() method is used in Java for thread communication
inside synchronized blocks.
 When multiple threads are waiting for the same lock
(resource), notify() wakes up one thread that is waiting.
 The thread that gets notified will then compete for the lock
and continue execution.
 It is used with wait(), notify(), and notifyAll() methods to
handle cooperation between threads.
 Syntax – void notify()
Example:
synchronized(obj) {
obj.notify();
}

iii) Getpriority
 The getPriority() method is used to retrieve (get) the priority of
a thread.
 In Java, each thread has a priority value between 1
(MIN_PRIORITY) and 10 (MAX_PRIORITY), where 5
(NORM_PRIORITY) is the default.
 Higher priority threads are given preference for CPU time (but
it is not guaranteed).
 Syntax - int getPriority()
Example:
Thread t1 = new Thread();
System.out.println(t1.getPriority()); // Output: 5
iv) setPriority()
 The setPriority() method is used to assign a priority to a thread.
 Priorities help the Thread Scheduler decide which thread
should run first when multiple threads are waiting.
 Priority is set using an integer value from 1 to 10.
 Syntax - void setPriority(int priority)
 Example:
Thread t1 = new Thread();
t1.setPriority(8); // Sets high priority

v) Join()
 The join() method is used when one thread wants to wait for
another thread to finish its execution before continuing.
 It pauses the current thread until the thread on which join() is
called completes its work.
 For example, if Thread A calls B.join(), then Thread A will wait
until Thread B finishes.
 Syntax - void join() throws InterruptedException
Example:
Thread t1 = new Thread();
t1.start();
t1.join(); // main thread will wait here until t1 finishes

2)List the Features, advantages, and limitations of Vue JS.


 VueJS is an open source progressive JavaScript framework used
to develop interactive web interfaces.
 It is called "progressive" because you can gradually adopt its
features — meaning you can use it just for a part of your project
or build an entire application with it.
 It is one of the famous frameworks used to simplify web
development. VueJS focusses on the view layer.
 It can be easily integrated into big projects for front-end
development without any issues.
Features :
1. Reactive Data Binding
- Vue automatically updates the view (UI) when data changes
using a reactivity system.
2. Component-Based Architecture
- You can build your application by combining small reusable
components.
3. Lightweight and Fast
- The core library is very small (~20–30 KB), making Vue very
fast and easy to download and load
4. Two-way Data Binding
- Similar to AngularJS, Vue supports two-way binding, allowing
easy synchronization between data and the view.
5. Transition Effects
- Vue provides easy ways to add animations and transitions
when elements are added, updated, or removed from the
DOM.
Advantages:
- Simple and Easy to learn
- Flexibility
- High performance
- Fast and Lightweight
1) Write a short note on React JS and Angular JS and Vue
JS (features, advantages and limitations and compare).
Feature React JS Angular JS Vue JS
Type Library Framework Framework
Developed by Facebook Google Evan you
Learning curve Medium High Easy
Data binding One-way Two-way Two-way
Performance Very high Moderte High
Size Small Large Small
DOM Virtual DOM Real DOM Virtual DOM
Flexibility High Low Medium
Community Very strong Strong Growing fast
support
Best for Dynamic UI’s Enterprise apps All-size apps
2) Interpret the terms multitasking and multiprocessing
and multithreading in Java with example and
differentiate.

What is Multitasking in Java?


 Multitasking means performing multiple tasks at the same time.
 In Java, multitasking allows the CPU to switch between multiple
processes or threads, so the user feels like everything is
happening at once.
 There are two types of multitasking:
- Process-based Multitasking (Multiprocessing)
- Thread-based Multitasking (Multithreading)

What is Multiprocessing in Java?


 Multiprocessing means using two or more processors (CPUs) to
perform multiple tasks at the same time.
 Each task runs in a separate process. A process has its own
memory space and is heavier than a thread.
 Java itself doesn’t directly control multiple CPUs, but Java
programs can run on systems with multiple processors, and
multiple Java processes can run in parallel.
Example (Conceptual):
 You open a video editor and a browser at the same time.
 The video editor and browser run in separate processes, and
your system with multiple CPUs runs them in parallel.

What is Multithreading?
 Multithreading means breaking a single program into multiple
threads that run independently.
 Threads are lightweight sub-processes that share the same
memory space but can run concurrently.
Example in Java:
class MyThread extends Thread {
public void run() {
for(int i=1; i<=5; i++) {
System.out.println("Thread running: " + i);
}}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread
for(int i=1; i<=5; i++) {
System.out.println("Main thread: " + i);
} }}
Speed – fast, fast, very fast Basis – tasks, process, threads
Commn – hard, hard, easy memory – depends, high, low
3) Write the JavaScript code to create Login page Form.
4) List the features of JavaScript and write a JavaScript
program to display Welcome message.
What is JavaScript?
 JavaScript is a lightweight, interpreted programming language
mainly used to create dynamic and interactive effects on
websites.
 It runs in the browser and allows web pages to respond to user
actions.

Features of JavaScript:
1.Lightweight & Interpreted
- JavaScript is not compiled; it is interpreted directly by the
browser, making it fast and easy to use.

2.Client-Side Technology
- It runs on the user's browser without the need for server
communication (unless needed).
3.Object-Based Language
- JavaScript supports objects and also allows creating custom
objects.

4.Dynamic Typing
- You don’t need to declare variable types; JavaScript figures it out
automatically.

5.Event-Driven
- JavaScript responds to user events like mouse clicks, form
submissions, or keypresses.

6.Cross-Platform
- JavaScript runs on any browser (Chrome, Firefox, Edge, Safari)
on any OS (Windows, Mac, Linux).

7.Functional & Object-Oriented


- It supports both functional and object-oriented programming
features.

8.Highly Compatible with HTML/CSS


- It works perfectly with HTML and CSS to create rich user
interfaces.

<!DOCTYPE html>
<html>
<head>
<title>Welcome Message</title>
</head>
<body>
<h2>JavaScript Welcome Example</h2>
<script>
alert("Welcome!");
</script>
</body>
</html>
Output:
Welcome!

8) Differentiate between process and thread. What are


various stages of thread lifecycle?
Aspect Process Thread
1. Defn Process means a Thread means a
program in segment of a
execution. process.
2. Terminate A process takes more A thread takes less
time to terminate. time to terminate.
3. Creation takes more time takes less time
4. Context switching Takes more time Takes less time
5. Speed Slower Faster
6. Crash impact One process crash If one thread
does not affect crashes, it may
others. affect the whole
process.
7. Memory space Every process runs in Threads share
its own memory memory.
8. System call Involved Not Involved

Thread life cycle:


1.New (Created)
o Why it exists:
This is the starting point of any thread. It represents a
thread that has been created but not yet started.
o When it's used:
When you define a thread and get it ready to run, but
haven’t called start() yet. It’s like preparing for a race but
not entering the track yet.

2.Runnable
o Why it exists:
Once you start the thread, it’s ready to run but not
guaranteed to run immediately.
o When it's used:
The thread is in a waiting queue for CPU time. It may sit in
this state briefly or for a while depending on CPU
availability.

3.Running
o Why it exists:
This is the active execution state where the thread is
actually performing its task.
o When it's used:
The thread gets CPU time and starts executing the code in
its run() method.

4.Blocked
o Why it exists:
To handle situations where a thread wants to access a
resource (like a file or object) that’s already being used by
another thread.
o When it's used:
The thread must wait until the resource is released. This
helps avoid data corruption or conflicts.

5.Waiting
o Why it exists:
For scenarios where the thread should pause and wait
indefinitely for another thread’s signal to continue.
o When it's used:
Used in multi-threaded coordination — like waiting for a
result from another thread or synchronization.

6.Timed Waiting
o Why it exists:
Similar to waiting, but here the thread waits only for a set
time, then goes back to the runnable state automatically.
o When it's used:
Used for timed pauses, like sleeping, timeout handling, or
waiting for a task to complete with a deadline.

7.Terminated (Dead)
o Why it exists:
Represents that the thread has finished its execution or
has been stopped.
o When it's used:
After completing its task or if it’s been forcefully stopped
due to an error or interruption. The thread cannot be
restarted.

9) Write a JavaScript program to develop a simple web


application?
<! DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<style>
body {
font-family: Arial;
background-color: #f0f0f0;
text-align: center;
padding: 50px;
}
input, button {
padding: 10px;
margin: 10px;
font-size: 16px;
}
#result {
font-weight: bold;
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>
<h2>Simple Calculator </h2>
<input type="number" id="num1" placeholder="Enter first
number">
<input type="number" id="num2" placeholder="Enter second
number"><br>
<button onclick="calculate('+')">Add</button>
<button onclick="calculate('-')">Subtract</button>
<button onclick="calculate('*')">Multiply</button>
<button onclick="calculate('/')">Divide</button>
<div id="result"></div>
<script>
function calculate(operator) {
const num1 =
parseFloat(document.getElementById("num1").value);
const num2 =
parseFloat(document.getElementById("num2").value);
let result = 0;
switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/':
if (num2 === 0) {
result = "Cannot divide by zero!";
} else {
result = num1 / num2;
}
break;
}
document.getElementById("result").innerText = "Result: " +
result;
}
</script>
</body>
</html>
Unit 6

1) Explain the features of LISP programming.


 LISP (LISt Processing) is one of the oldest high-level
programming languages, designed in 1958 by John McCarthy.
 It is primarily used for artificial intelligence (AI) and symbolic
processing.
 LISP's syntax and structure are distinct due to its use of
parentheses and a focus on recursion and list manipulation.
Features of LISP Programming:

1. Symbolic Expression (S-Expressions):


 LISP is centered around S-expressions (symbolic expressions),
which are either atoms (like numbers, symbols) or lists.
 Lists are fundamental data structures in LISP, and programs
themselves are written as lists.
 Example: (+ 2 3) is a list representing the addition of 2 and 3.

2. Recursive Nature:
 LISP is a recursive language, meaning that functions can call
themselves.
 This feature is fundamental for processing list structures and
solving problems in a natural and elegant manner.
 Example:
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
The function factorial calls itself recursively.

3. Dynamic Typing:
 LISP is dynamically typed, which means variables do not need
to be declared with a type, and types are determined at
runtime.
 This allows for great flexibility in how functions and data
structures are used.
 Example:
(defvar x 10) ; x is treated as an integer
(defvar y "Hello") ; y is treated as a string

4. Powerful List Processing:


Lists are the fundamental data structure in LISP. LISP provides
powerful built-in functions for manipulating lists, such as car, cdr,
cons, list, etc.
 car: Returns the first element of a list.
 cdr: Returns the rest of the list (tail).
 cons: Combines two elements into a list.
 Example:
(setq my-list '(1 2 3 4))
(car my-list) ; Output: 1
(cdr my-list) ; Output: (2 3 4)
5. High-Level Functions:
LISP is a functional programming language. Functions are first-
class objects, meaning they can be passed as arguments to other
functions, returned from functions, and stored in variables.
 Example:
(defvar add (lambda (a b) (+ a b))) ; Defining an anonymous
function
(funcall add 2 3) ; Output: 5

6. Macros:
LISP allows the definition of macros. Macros provide a way to
define custom control structures and syntax extensions. Macros
operate on the code itself, transforming it before evaluation.
 Example:
(defmacro square (x)
`(* ,x ,x)) ; The macro expands to (* x x)
(square 4) ; Output: 16
2) Explain the following Equality predicates using a
suitable example.
1. EQ Predicate:
 The EQ predicate is used to compare whether two objects are
the same in terms of memory location.
 This means that it checks whether both variables refer to the
exact same object, not whether their contents are identical.
 Usage: EQ is most commonly used to compare symbols or
pointers.
 Example:
(setq x 'a) ; x is assigned the symbol 'a'
(setq y 'a) ; y is assigned the symbol 'a'

(eq x y) ; Output: T (True, because x and y refer to the same


symbol 'a')

(setq a '(1 2 3)) ; a is a list


(setq b '(1 2 3)) ; b is another list with the same content as a

(eq a b) ; Output: NIL (False, because a and b are two different lists
in memory)

2. EQL Predicate:
 The EQL predicate compares two objects for equality in terms
of value for simple types and checks whether they are
physically identical for more complex types (like lists and
symbols).
 Usage: EQL works for both numeric types (such as integers
and floats) and symbols, and can be used to check both value
equality and object identity.
 Example:
(setq x 42) ; x is assigned the integer 42
(setq y 42) ; y is also assigned the integer 42

(eql x y) ; Output: T (True, because both x and y have the same


value)

(setq a 3.14) ; a is a floating-point number


(setq b 3.14) ; b is also a floating-point number with the same
value
(eql a b) ; Output: T (True, because both a and b have the same
value)

(setq x 'hello) ; x is the symbol 'hello'


(setq y 'hello) ; y is another symbol 'hello'
(eql x y) ; Output: T (True, because x and y refer to the same
symbol 'hello')

(setq a '(1 2 3)) ; a is a list


(setq b '(1 2 3)) ; b is a list with the same contents
(eql a b) ; Output: NIL (False, because a and b are different lists in
memory)
3. EQUAL Predicate:
 The EQUAL predicate checks whether two objects are
structurally equivalent.
 It can be used to compare lists, strings, and arrays by
comparing their contents recursively.
 Usage: EQUAL compares complex objects like lists or strings,
checking if the contents are the same, regardless of whether
the objects are in the same memory location.
 Example:
(setq x '(1 2 3)) ; x is a list
(setq y '(1 2 3)) ; y is another list with the same contents
(equal x y) ; Output: T (True, because the contents of x and y are
the same)

(setq str1 "hello") ; str1 is a string


(setq str2 "hello") ; str2 is another string with the same contents
(equal str1 str2) ; Output: T (True, because the strings have the
same characters)

(setq a '(1 2 3)) ; a is a list


(setq b '(1 2 4)) ; b is a list with different contents
(equal a b) ; Output: NIL (False, because the contents of a and b
are different)

3) Explain the following number predicates using a


suitable example.
1. NUMBERP Predicate:
 The NUMBERP predicate checks whether the given argument is
a number or not.
 It returns T (True) if the argument is a number (either integer,
floating-point, rational, or complex), and NIL (False) otherwise.
Usage:
 Syntax: (numberp object)
 Example:
(numberp 42) ; Output: T (True, 42 is a number)
(numberp 3.14) ; Output: T (True, 3.14 is a number)
(numberp "hello") ; Output: NIL (False, "hello" is a string, not a
number)
(numberp '(1 2 3)) ; Output: NIL (False, a list is not a number)
2. ZEROP Predicate:
 The ZEROP predicate checks if the given number is zero.
 It returns T (True) if the number is zero, and NIL (False) if it is
any other number.
Usage:
 Syntax: (zerop number)
 Example:
(zerop 0) ; Output: T (True, because 0 is zero)
(zerop 42) ; Output: NIL (False, because 42 is not zero)
(zerop -5) ; Output: NIL (False, because -5 is not zero)
(zerop 3.14) ; Output: NIL (False, because 3.14 is not zero)

3. PLUSP Predicate:
 The PLUSP predicate checks if the given number is positive.
 It returns T (True) if the number is positive (greater than zero),
and NIL (False) if it is zero or negative.
Usage:
 Syntax: (plusp number)
 Example:
(plusp 10) ; Output: T (True, because 10 is positive)
(plusp 0) ; Output: NIL (False, because 0 is not positive)
(plusp -3) ; Output: NIL (False, because -3 is negative)
(plusp 3.14) ; Output: T (True, because 3.14 is positive)

4. EVENP Predicate:
 The EVENP predicate checks if the given number is even (i.e.,
divisible by 2 without a remainder).
 It returns T (True) if the number is even, and NIL (False) if the
number is odd.
Usage:
 Syntax: (evenp number)
 Example:
(evenp 4) ; Output: T (True, because 4 is even)
(evenp 7) ; Output: NIL (False, because 7 is odd)
(evenp 0) ; Output: T (True, because 0 is considered even)
(evenp -8) ; Output: T (True, because -8 is even)

5. ODDP Predicate:
The ODDP predicate checks if the given number is odd (i.e., not
divisible by 2). It returns T (True) if the number is odd, and NIL
(False) if the number is even.
Usage:
 Syntax: (oddp number)
 Example:
(oddp 5) ; Output: T (True, because 5 is odd)
(oddp 2) ; Output: NIL (False, because 2 is even)
(oddp 0) ; Output: NIL (False, because 0 is even)
(oddp -3) ; Output: T (True, because -3 is odd)

4) Explain the following functions with suitable examples.


1. CAR() Function:
 The CAR function is used to retrieve the first element (or the
head) of a list.
 The name "CAR" stands for "Contents of the Address part of
Register" in early computer terminology.
 It is one of the oldest functions in LISP and is essential for
accessing the first element of any list.
 Usage: (car list)
 Example:
(setq my-list '(1 2 3 4)) ; Define a list
(car my-list) ; Output: 1 (The first element of the list)
(setq my-list '(apple banana cherry)) ; Define a list of strings
(car my-list) ; Output: apple (The first element of the list)
2. CDR() Function:
 The CDR function is used to retrieve the tail (or the rest) of a
list, i.e., all elements except for the first one.
 The name "CDR" stands for "Contents of the Decrement part
of Register" in early computer terminology.
 Like CAR, it is used to extract parts of a list and is fundamental
in recursive list processing.
 Usage: (cdr list)
 Example:
(setq my-list '(1 2 3 4)) ; Define a list
(cdr my-list) ; Output: (2 3 4) (The rest of the list, excluding the
first element)
(setq my-list '(apple banana cherry)) ; Define a list of strings
(cdr my-list) ; Output: (banana cherry) (The rest of the list)

3. FIRST() Function:
 The FIRST function is very similar to the CAR function.
 It returns the first element of a list, just like CAR.
 FIRST is essentially an alias for CAR in LISP, making the
language easier to understand, especially for beginners.
 Usage: (first list)
 Example:
(setq my-list '(1 2 3 4)) ; Define a list
(first my-list) ; Output: 1 (The first element of the list)

(setq my-list '(apple banana cherry)) ; Define a list of strings


(first my-list) ; Output: apple (The first element of the list)
5) Evaluate the following forms of LISP.
1. (car (cdr '(1 2 3 4 5))))
Step-by-step Evaluation:
 The inner expression is (cdr '(1 2 3 4 5)).
o cdr returns everything except the first element.
o (cdr '(1 2 3 4 5)) → (2 3 4 5).
 Now, the outer expression is (car '(2 3 4 5)).
o car returns the first element of the list (2 3 4 5), which is
2.
Result:
 Answer: 2.

2. (car (cdr '(a (b c) d e))))


Step-by-step Evaluation:
 The inner expression is (cdr '(a (b c) d e)).
o cdr removes the first element a and returns the rest of the
list: ((b c) d e).
o (cdr '(a (b c) d e)) → ((b c) d e).
 Now, the outer expression is (car '((b c) d e)).
o car returns the first element of the list ((b c) d e), which is
(b c).
Result:
 Answer: (b c).

3. (car (cdr (cdr '(1 2 3 4 5 6 7 8))))


Step-by-step Evaluation:
 The inner expression is (cdr '(1 2 3 4 5 6 7 8)).
o cdr removes the first element 1 and returns the rest: (2 3
4 5 6 7 8).
o (cdr '(1 2 3 4 5 6 7 8)) → (2 3 4 5 6 7 8).
 The next expression is (cdr '(2 3 4 5 6 7 8)).
o cdr removes the first element 2 and returns the rest: (3 4
5 6 7 8).
o (cdr '(2 3 4 5 6 7 8)) → (3 4 5 6 7 8).
 Now, the outer expression is (car '(3 4 5 6 7 8)).
o car returns the first element of the list (3 4 5 6 7 8), which
is 3.
Result:
 Answer: 3.

4. (car (cdr (cdr '(1 2 3 4 5 6 7 ED))))


Step-by-step Evaluation:
 The inner expression is (cdr '(1 2 3 4 5 6 7 ED)).
o cdr removes the first element 1 and returns the rest: (2 3
4 5 6 7 ED).
o (cdr '(1 2 3 4 5 6 7 ED)) → (2 3 4 5 6 7 ED).
 The next expression is (cdr '(2 3 4 5 6 7 ED)).
o cdr removes the first element 2 and returns the rest: (3 4
5 6 7 ED).
o (cdr '(2 3 4 5 6 7 ED)) → (3 4 5 6 7 ED).
 Now, the outer expression is (car '(3 4 5 6 7 ED)).
o car returns the first element of the list (3 4 5 6 7 ED),
which is 3.
Result:
 Answer: 3.
6) Describe Functional Programming. Enlist its features.
Also list the commonly used functional programming
languages.
 Functional programming (FP) is a programming paradigm that
treats computation as the evaluation of mathematical functions
and avoids changing state or mutable data.
 It is based on the concept of mathematical functions and
focuses on immutability, higher-order functions, and
declarative programming rather than imperative programming.
Features of Functional Programming:
1.First-Class and Higher-Order Functions:
o Functions in FP are first-class citizens, which means they
can be assigned to variables, passed as arguments to
other functions, and returned as results from other
functions.
2.Immutability:
o In functional programming, once a data structure is
created, it cannot be changed. This is called immutability.
If you need to change a value, you create a new instance
with the desired modification.
3.Pure Functions:
o A function is considered pure if the output is determined
solely by its input values, with no side effects (like
modifying global variables or performing I/O operations).
4.Recursion:
o Functional programming often uses recursion as the
primary mechanism for iteration or looping.
o This is because traditional loops (like for or while) are
typically not used in FP.
Commonly Used Functional Programming Languages:
1. LISP 2. Scala 3. F# 4. Clojure 5. Elixir:
7) Describe Logical Programming. Enlist its features. Also,
list the commonly used Logical programming languages.
 Logical programming is a programming paradigm based on
formal logic.
 It is primarily concerned with expressing logic in the form of
facts, rules, and queries.
 This paradigm enables a declarative approach where the focus
is on what is to be computed, rather than how it should be
computed.

Features of Logical Programming:


1.Declarative Nature:
o Logical programming is declarative, meaning the
programmer specifies what the problem is, rather than
how to solve it. The logic is expressed in terms of facts
and rules.
2.Facts and Rules:
o Facts represent known information in the form of relations.
o Rules define relationships between facts. They specify
conditions that must be true for a new fact to be inferred.
3.Inference Mechanism:
o Logical programming languages use inference to derive
new facts from existing facts and rules. The forward
chaining and backward chaining methods are commonly
used to perform logical inference.
4.Non-Procedural:
o In logical programming, the programmer specifies the
desired result, but the programming language or
interpreter handles how to compute it.

5.Backtracking:
o Backtracking is a key feature in logical programming
languages. It is the process of trying different possibilities
for a solution until a correct one is found or all options are
exhausted. If a rule leads to a dead end, the system will
backtrack and try another possibility.
6.Pattern Matching:
o Logical programming often involves pattern matching,
where queries are matched against facts and rules.
Commonly Used Logical Programming Languages:
1. Prolog (Programming in Logic)
2. Mercury
3. Choco
4. Answer Set Programming (ASP)
5. Datalog

8) Write sequences of CAR’s and CDR’s that will pick the


atom pear our of the following s-expression :
1.(apple orange pear grapes)
2.((apple orange) (pear grapes))
3.(((apple)(orange) (pear) (grapes)))

9) Explain the concept of “Structures” in Prolog with


example.

10) Explain the basic list manipulation in prolog.

11) Comparisons between functional programming and


logic programming.

12) Explain the phrases - “Term”, “Facts”, “Rule”, Goals”


used in Prolog with example

13) What is recursion? Write a lisp function to calculate


power of a number using recursion and iteration.
14) What is predicate in LISP? Explain any 5 predicates
with example.

15) What is clause in prolog? Explain types of clauses with


example.

16) Write a LISP program to find the factorial of n numbers


using recursion concept and without.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy