PPL 3-6
PPL 3-6
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.
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
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
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.
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
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
exception.
It must be followed by either a catch block or a finally block.
ii) catch
The catch block handles the exception thrown by the try block.
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
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,
Example:
throw new ArithmeticException("Divide by zero error");
v) throws
The throws keyword is used in the method declaration to
Example:
void myMethod() throws IOException {
// code that may throw IOException
}
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;
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;
// Regular method
void sleep() {
System.out.println("Animal is sleeping");
}
}
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
}
}
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).
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
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).
<!DOCTYPE html>
<html>
<head>
<title>Welcome Message</title>
</head>
<body>
<h2>JavaScript Welcome Example</h2>
<script>
alert("Welcome!");
</script>
</body>
</html>
Output:
Welcome!
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.
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
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 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
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)
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)
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