UNIT-I
3)a) Write a program to print the following output : 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5
public class PatternPrinting {
public static void main(String[] args) {
int rows = 5; // Number of rows in the pattern
// Outer loop to iterate over each row
for (int i = 1; i <= rows; i++) {
// Inner loop to print the numbers in each row
for (int j = 1; j <= rows - i + 1; j++) {
System.out.print(i + " "); // Print the current row number
}
System.out.println(); // Move to the next line after each row
}
}
}
This program will produce the following output:
Copy code
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
Explanation:
The outer loop iterates over each row from 1 to 5.
The inner loop prints the current row number (i) a certain number of times, where the
number of times decreases as i increases.
The number of times the inner loop runs for each row is determined by the condition j
<= rows - i + 1. As i increases, rows - i + 1 decreases, resulting in fewer
repetitions of the current row number.
3)b) Why java became platform independent language? Explain.
Java became platform-independent primarily due to its design and implementation choices,
which enabled it to run on any platform that supports the Java Virtual Machine (JVM). Here's
why:
1. Compilation to Bytecode: In Java, the source code is compiled into platform-
independent bytecode instead of native machine code. This bytecode is a set of
instructions for the Java Virtual Machine (JVM), rather than instructions for a specific
hardware architecture. This bytecode can run on any device or operating system that
has a compatible JVM.
2. Java Virtual Machine (JVM): The JVM is an integral part of Java's platform
independence. It acts as an interpreter that translates the bytecode into native machine
code at runtime. JVM implementations are available for various platforms, including
Windows, macOS, Linux, and others. Once a JVM is installed on a specific platform,
Java programs can run on that platform without modification.
3. Abstraction of Platform-Specific Details: Java abstracts away many platform-
specific details such as memory management, file handling, and networking through
its standard library and APIs. Instead of directly interacting with the underlying
operating system, Java programs rely on the JVM and the Java standard library, which
provides consistent behavior across different platforms.
4. Write Once, Run Anywhere (WORA): Java's slogan "Write Once, Run Anywhere"
encapsulates its platform independence. Developers can write Java code on one
platform and run it on any other platform with a compatible JVM without needing to
recompile or modify the code. This significantly reduces development and
deployment complexities for cross-platform applications.
5. Security Model: Java's security model also contributes to its platform independence.
The JVM imposes strict security restrictions on the execution of bytecode, preventing
malicious code from harming the underlying system. This security model is consistent
across different platforms, ensuring a uniform level of security regardless of the
underlying operating system.
Overall, Java's platform independence is a result of its bytecode compilation, the JVM's
ability to execute bytecode on various platforms, abstraction of platform-specific details, the
"Write Once, Run Anywhere" principle, and its robust security model. These features have
made Java a popular choice for developing cross-platform applications and web services.
UNIT-2
5) Develop a Java Program to create an abstract class named Shape that contains two integers and an
empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle such
that each one of the classes extends the class Shape. Each one of the classes contains only the
method print Area () that prints the area of the given shape.
// Abstract Shape class
abstract class Shape {
protected int side1;
protected int side2;
// Constructor
public Shape(int side1, int side2) {
this.side1 = side1;
this.side2 = side2;
// Abstract method to print area
public abstract void printArea();
}
// Rectangle class
class Rectangle extends Shape {
// Constructor
public Rectangle(int length, int width) {
super(length, width);
// Method to print area of rectangle
@Override
public void printArea() {
System.out.println("Area of Rectangle: " + (side1 * side2));
// Triangle class
class Triangle extends Shape {
// Constructor
public Triangle(int base, int height) {
super(base, height);
// Method to print area of triangle
@Override
public void printArea() {
System.out.println("Area of Triangle: " + (0.5 * side1 * side2));
// Circle class
class Circle extends Shape {
// Constructor
public Circle(int radius) {
super(radius, 0); // The second side is not used for circle
// Method to print area of circle
@Override
public void printArea() {
System.out.println("Area of Circle: " + (Math.PI * side1 * side1));
// Main class to test the Shape classes
public class Main {
public static void main(String[] args) {
// Create objects of Rectangle, Triangle and Circle
Rectangle rectangle = new Rectangle(5, 4);
Triangle triangle = new Triangle(6, 8);
Circle circle = new Circle(3);
// Print area of each shape
rectangle.printArea();
triangle.printArea();
circle.printArea();
UNIT-III
7) Write Java programs to add names in ArrayList, Stack, Vector, and LinkedList?
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
import java.util.Vector;
public class AddNames {
public static void main(String[] args) {
// Add names to ArrayList
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("John");
arrayList.add("Alice");
arrayList.add("Bob");
System.out.println("Names added to ArrayList: " + arrayList);
// Add names to Stack
Stack<String> stack = new Stack<>();
stack.push("John");
stack.push("Alice");
stack.push("Bob");
System.out.println("Names added to Stack: " + stack);
// Add names to Vector
Vector<String> vector = new Vector<>();
vector.add("John");
vector.add("Alice");
vector.add("Bob");
System.out.println("Names added to Vector: " + vector);
// Add names to LinkedList
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("John");
linkedList.add("Alice");
linkedList.add("Bob");
System.out.println("Names added to LinkedList: " + linkedList);
}
}
In this program:
Names are added to each data structure using their respective methods (add() for
ArrayList, push() for Stack, and add() for both Vector and LinkedList).
After adding names, the contents of each data structure are printed to verify the
addition.
UNIT-IV
8) With proper syntax and example explain following thread methods : (1) wait( ) (2) sleep( ) (3)
resume( ) (4) notify( ).
wait():
wait() is a method in Java that is used for synchronization between threads. When a
thread calls wait() on an object, it releases the lock it holds and waits for another
thread to call notify() or notifyAll() on the same object to wake it up.
Syntax:
java
Copy code
synchronized (object) {
while (condition) {
object.wait();
}
// Perform actions after being notified
}
Example:
java
Copy code
class WaitExample {
public static void main(String[] args) throws
InterruptedException {
final Object lock = new Object();
Thread thread1 = new Thread(() -> {
synchronized (lock) {
try {
System.out.println("Thread 1 is waiting");
lock.wait();
System.out.println("Thread 1 is awake");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2 is notifying");
lock.notify();
}
});
thread1.start();
Thread.sleep(1000); // Delay to ensure thread1 starts first
thread2.start();
}
}
sleep():
sleep() is a static method in the Thread class used to pause the execution of the
current thread for a specified amount of time. It does not release any locks held by the
thread.
Syntax:
java
Copy code
try {
Thread.sleep(milliseconds); // Sleep for specified milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
Example:
java
Copy code
class SleepExample {
public static void main(String[] args) throws
InterruptedException {
System.out.println("Before sleep");
Thread.sleep(2000); // Sleep for 2 seconds
System.out.println("After sleep");
}
}
resume():
resume() method is deprecated in Java and should not be used. It was previously
used to resume a suspended thread, but it's unsafe as it can lead to deadlock situations.
Instead of resume(), you can use other synchronization mechanisms like wait() and
notify().
notify():
notify() is a method in Java used to wake up a single thread that is waiting on the
object on which notify() is called. If multiple threads are waiting, only one of them
is chosen to be awakened.
Syntax:
java
Copy code
synchronized (object) {
object.notify();
}
Example:
java
Copy code
class NotifyExample {
public static void main(String[] args) {
final Object lock = new Object();
Thread thread1 = new Thread(() -> {
synchronized (lock) {
try {
System.out.println("Thread 1 is waiting");
lock.wait();
System.out.println("Thread 1 is awake");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2 is notifying");
lock.notify();
}
});
thread1.start();
Thread.sleep(1000); // Delay to ensure thread1 starts first
thread2.start();
}
}
UNIT-V
11) Write a program to create an applet for displaying circle, rectangle and triangle one below the
other & filled them with red, green and yellow respectively?
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
@SuppressWarnings("serial")
public class ShapeApplet extends Applet {
public void paint(Graphics g) {
// Set background color
setBackground(Color.white);
// Set shapes' colors
Color[] colors = {Color.red, Color.green, Color.yellow};
// Set positions and dimensions for shapes
int x = 100;
int y = 100;
int width = 100;
int height = 100;
// Draw circle
g.setColor(colors[0]);
g.fillOval(x, y, width, height);
// Draw rectangle
g.setColor(colors[1]);
g.fillRect(x, y + height + 50, width, height);
// Draw triangle
int[] triangleX = {x + width / 2, x, x + width};
int[] triangleY = {y + 2 * (height + 50), y + height + 50, y +
height + 50};
g.setColor(colors[2]);
g.fillPolygon(triangleX, triangleY, 3);
}
}
In this program:
We extend the Applet class and override the paint() method to draw the shapes.
We set the background color of the applet to white.
We define an array colors to store the colors for the circle, rectangle, and triangle.
We define variables for the positions and dimensions of the shapes.
We draw each shape using the Graphics object g, setting the color and filling the
shape with the respective color.
For the triangle, we define arrays triangleX and triangleY to specify the vertices of
the triangle, and then use fillPolygon() method to draw the filled triangle.
2 MARKS
a) Disadvantages of OOP:
Complexity: OOP can sometimes lead to complex designs and hierarchies, especially
in large-scale applications.
Performance Overhead: Object-oriented programs may incur performance overhead
due to features like dynamic dispatch and polymorphism.
Learning Curve: OOP concepts like inheritance, polymorphism, and encapsulation
may have a steep learning curve for beginners.
Overhead: Object-oriented programs may have more memory overhead compared to
procedural programming due to the need to create objects.
Inheritance Issues: Improper use of inheritance can lead to tight coupling and
difficulty in maintenance.
b) Java program to display multiples of 4:
java
Copy code
public class MultiplesOfFour {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 4 == 0) {
System.out.println(i);
}
}
}
}
c) Steps for creating and importing packages:
Creating a Package:
1. Create a directory with the package name.
2. Place the Java files (classes) inside this directory.
3. Add the package declaration at the top of each Java file: package
package_name;
Importing a Package:
1. Use the import keyword followed by the package name to import classes
from the package.
2. If you want to import all classes from a package, use import
package_name.*;.
d) CLASSPATH:
CLASSPATH is an environment variable in Java that specifies the locations (directories
or JAR files) where Java looks for user-defined classes and packages.
When compiling or running Java programs, Java searches for classes and packages in
the directories specified in the CLASSPATH variable.
If the CLASSPATH variable is not set, Java uses the current directory by default.
e) Runnable Interface:
Runnable is a functional interface in Java that represents a task that can be executed
concurrently by a thread.
It defines a single method run() that contains the code to be executed by the thread.
Example:
java
Copy code
public class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
System.out.println("Hello from a thread!");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
f) Random Access File:
RandomAccessFile is a class in Java that allows both reading and writing to a file at
any position.
Unlike other file I/O classes, RandomAccessFile supports non-sequential access to
the data in the file.
It allows reading and writing of primitive data types and strings to a file.
g) synchronized Keyword:
synchronized is a keyword in Java used to achieve thread safety by preventing
multiple threads from accessing the same block of code concurrently.
It can be applied to methods or code blocks.
When a method or block is declared as synchronized, only one thread can execute it
at a time.
It is often used when accessing shared resources or critical sections of code in multi-
threaded environments.
h) ArrayList Definition with Syntax:
An ArrayList is a resizable array implementation of the List interface in Java.
It dynamically resizes itself when elements are added or removed.
Syntax:
java
Copy code
import java.util.ArrayList;
ArrayList<Type> arrayList = new ArrayList<Type>();
Example:
java
Copy code
ArrayList<Integer> numbers = new ArrayList<Integer>();
i) Applet Life Cycle:
The life cycle of an applet includes several stages:
1. Initialization: init() method is called when the applet is first loaded into
memory.
2. Starting: start() method is called after init() and when the applet is about
to start running.
3. Running: The applet is running and can respond to user input.
4. Stopping: stop() method is called when the applet is about to stop running.
5. Destroying: destroy() method is called when the applet is about to be
unloaded from memory.
j) Components of Swing:
Swing is a GUI toolkit for Java that provides a set of components for building
graphical user interfaces.
Some components of Swing include:
o JFrame: A top-level container for GUI components.
o JButton: A button component that triggers an action when clicked.
o JLabel: A component for displaying text or images.
o JTextField: A component for entering and editing single-line text.
o JTextArea: A component for entering and editing multi-line text.
o JComboBox: A drop-down list component for selecting an item from a list.
o JCheckBox: A component for selecting/deselecting options.
o JRadioButton: A component for selecting one option from a group of
options.
o JPanel: A container for grouping and organizing components.
o JScrollPane: A scrollable container for displaying components when space is
limited.