1726532641-Object Oriented Programming Lab Manual
1726532641-Object Oriented Programming Lab Manual
LABORATORY MANUAL
B.Tech. (CSE/iMSc/ECE/DS/CYS)
Semester I
L-T-P-C: 2-0-4-4
To be the role model of learning, research, innovation, and sustainability for the knowledge society.
NIIT University emerged from the visionary aspirations of esteemed intellectuals who sought to
revolutionize the Indian education system, with a focus on cultivating original thinkers, innovative
problem solvers, and inspiring leaders. Their goal was to foster a dynamic and intellectually
stimulating learning environment that seamlessly blends academic theories with real-life
experiences. NU's Computer Science and Engineering (CSE) programmes (Undergraduate,
Postgraduate, and PhD) are designed to provide a comprehensive understanding of the foundational
principles of computing and equip students with the necessary engineering skills for designing,
implementing, and utilizing computer systems. This course offers a holistic perspective on the field
of computing, encompassing the concepts, principles, and practical applications, allowing students
to gain both theoretical knowledge and hands-on experience. By enrolling in our CSE program,
students will embark on a journey that not only acquaints them with the intricacies of computing
but also nurtures their ability to apply and extend these concepts. Our curriculum is carefully crafted
to ensure that students develop a well-rounded skill set, encompassing theoretical understanding,
practical skills, and the capacity to apply these principles in real-world scenarios.
PROGRAM OVERVIEW
The Computer Science and Engineering at NIIT University seems to have a strong focus on
providing quality education and preparing students for practical challenges in the field. This
approach is valuable in ensuring that students are equipped with the necessary skills and knowledge
to contribute to fundamental research in computer science and engineering. By emphasizing real-
world challenges, the area likely provides a curriculum that integrates theoretical knowledge with
hands-on experience, preparing students for the demands of the industry. The University is actively
seeking out students with a passion for innovation and a drive to contribute to the field. This
approach can foster an environment that encourages creativity, problem-solving, and critical
thinking, which are all essential qualities for success in computer science and engineering.
PO2: Problem Analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using the first principles of mathematics, natural
sciences, and engineering sciences.
PO3: Design/Development of Solutions: Design solutions for complex engineering problems and
system components or processes that meet the specified needs with appropriate consideration for
the public health and safety, and the cultural, society, and environmental considerations.
PO5: Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of the professional engineering
solutions in society and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9: Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multi-disciplinary settings.
PO11: Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multi-disciplinary environments.
PO12: Life-long Learning: Recognize the need for and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
PSO 1: Ability to apply the knowledge of basic and advanced concepts of Computer
Science in order to address compelling problems of society and provide an acceptable
and practical solution.
PSO 6: Ability to model data and design the system architecture of high-performance
and tolerant systems.
PSO 9: Ability to publish technical papers in reputed journals and conferences under
the guidance of dedicated faculty members.
PSO 10: Ability to get involved in innovative, industry-relevant projects jointly with
world class engineers in Collaborative Education mode which will provide an
environment to convert their innovation into reality.
PSO 11: Develop expertise in specialized areas like Data Science, Artificial
Intelligence, Cyber Security, Cloud Computing and Big data Engineering.
PSO 12: Ability to seamlessly become industry professional after six months
Industry Practice in Industry Environment in the final academic year.
PEO 1: The Computer Science and Engineering program at NIIT University is designed to
empower graduates with the skills and knowledge necessary to achieve the following educational
objectives.
PEO 2: Thrive as proficient computer professionals: Our graduates will be equipped to work
productively as successful computer professionals in a diverse range of career paths. Whether in
supportive or leadership roles within multidisciplinary teams, they will possess the competence to
contribute effectively. Additionally, they will have the option to pursue higher studies to further
enhance their expertise in the field.
PEO 3: Demonstrate effective communication and ethical conduct: We emphasize the development
of excellent communication skills among our graduates, enabling them to effectively convey ideas
and solutions.
PEO 4: CSE program instills a strong awareness of societal needs and constraints, empowering
graduates to incorporate these considerations into their professional endeavors. With a high regard
for ethical responsibilities, they will contribute to the betterment of society through their practice.
PEO 5: Embrace lifelong learning for personal and organizational growth: Our program encourages
graduates to engage in lifelong learning, ensuring they remain up-to-date in their profession. By
nurturing a mindset of continuous growth, they will adapt to evolving technologies and industry
trends, fostering personal development and contributing to the growth of the organizations they
join. Through their commitment to ongoing learning, our graduates will stay at the forefront of the
field.
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly before the commencement, come prepared to the lab with the synopsis/
program/experiment details.
4. Execute your task in the laboratory, record the results/output, and get certified by the concerned
faculty.
5. All the students should be polite and cooperative with the laboratory staff, and must maintain
discipline and decency in the laboratory.
6. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment and misbehavior with the staff will attract severe punishment.
7. Students must get the permission of the faculty in case of any urgency to go out; if anybody is
found outside the lab/class without permission during working hours will be treated seriously and
punished appropriately.
8. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system/seat is kept
properly.
By empowering students with the skills necessary to access, understand and evaluate Information,
Capstone Project will support students in the achievement of 21st century learning expectations.
Students work in teams to develop or implement a real world IT solution
COURSE OUTCOMES
S.No. Description
Identify classes, objects, members, methods of a class and relationships among them
CO1
needed for a specific problem
CO2 Demonstrate the concepts of polymorphism and inheritance and reusability
Relate Java programs to implement error handling techniques using exception
CO3
handling
CO4 Compare Multithreaded programming with ordinary programming models
CO5 Design and Develop applications which connects with database using JDBC
FACULTY DETAILS
COURSE CONTENTS
Secondly, declare and assign variables of the following different data types.
• Declare a variable named value_int of the data type int that is assigned the value 20
• Secondly, declare a variable named value_string of the data type string that is assigned the value
“Java”
• Third, create a variable named value_double of the data type double that is assigned the value
23.63
• Finally, print all variables in the console.
Resulting in,
20
Java
23.63
First,
• Declare a variable named value of the data type int that is assigned the value 50
• Secondly, declare a variable named another_value of the data type double that is assigned the
value 30.2
Secondly,
• Convert the variable value from data type int to data type double. Save the new variable to a new
variable value_double
Finally,
• Add the variable value and another_value and assign the value to a new variable which is
assigned the name sum_value of type double.
• Print the result
Write a Java program to create a class called "Person" with a name and age attribute. Create two
instances of the "Person" class, set their attributes using the constructor, and print their name and
age.
Sample Solution:
Java Code:
// Person.java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
The above class has two private attributes: name and age, and a constructor that initializes these
attributes with the values passed as arguments. It also has a getter method to access the attributes.
// Main.java
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Ean Craig", 11);
Person person2 = new Person("Evan Ross", 12);
System.out.println(person1.getName() + " is " + person1.getAge() + " years old.");
System.out.println(person2.getName() + " is " + person2.getAge() + " years old.\n");
}
}
In the above example, we create two instances of the "Person" class, set their attributes with the
constructor, and print their name and age using the getter methods. We also modify the attributes
using the setter methods and print the updated values.
Sample Output:
Write a Java program to create a class called "Rectangle" with width and height attributes.
Calculate the area and perimeter of the rectangle.
Sample Solution:
Java Code:
//Rectangle.java
public class Rectangle {
private double width;
private double height;
The above class has two private attributes: ‘width’ and ‘height’, a constructor that initializes these
attributes with the values passed as arguments, and getter and setter methods to access and modify
these attributes. It also has two methods ‘getArea()’ and ‘getPerimeter() ‘ to calculate the area and
perimeter of the rectangle.
//Main.java
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(7, 12);
rectangle.setWidth(6);
rectangle.setHeight(12);
In the Main() function we create an instance of the "Rectangle" class with a width of 7 and a
height of 12, and call its methods to calculate the area and perimeter. We then modify the width
and height using the setter methods and print the updated rectangle area and perimeter.
Sample Output:
Write a Java program to demonstrate method overloading with two methods having
different data types
This Java code demonstrates method overloading, a feature that allows a class to have multiple
methods with the same name but different parameters. In this example, the OverloadExample
class has two print methods, each accepting a different type of parameter: one for int and one for
double.
Source Code
class OverloadExample
{
void print(int num)
{
System.out.println("Integer : " + num);
}
Output
Integer : 18
Double : 84.44
Create a Java program to demonstrate method overloading with two methods having
different numbers of parameters
Source Code
class MathOperations
{
int add(int a, int b)
{
return a + b;
}
Output
Sum of Two Numbers : 10
Sum of Three Numbers : 17
Practical 3: Arrays :
Pictorial Presentation:
Java Code:
Sample Output:
Original numeric array : [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365, 1456, 2165, 1457, 2456]
Sorted numeric array : [1254, 1456, 1456, 1457, 1458, 1472, 1789, 1899, 2013, 2035, 2165, 2365, 2456, 2458]
Original string array : [Java, Python, PHP, C#, C Programming, C++]
Sorted string array : [C Programming, C#, C++, Java, PHP, Python]
Here is the simple program to populate two matrices from the user input. Then add its elements at
the corresponding indices to get the addition of the matrices. Finally, we will print the sum of the
matrices.
package com.journaldev.examples;
import java.util.Scanner;
System.out.println("Second Matrix:\n");
print2dArray(second);
// sum of matrices
sum(first, second);
}
System.out.println("\nSum of Matrices:\n");
print2dArray(sum);
}
Here is the simple program to populate two matrices from the user input. Then add its elements at
the corresponding indices to get the addition of the matrices. Finally, we will print the sum of the
matrices.
package com.journaldev.examples;
import java.util.Scanner;
System.out.println("Second Matrix:\n");
print2dArray(second);
// sum of matrices
sum(first, second);
}
System.out.println("\nSum of Matrices:\n");
print2dArray(sum);
}
Here is the function to subtraction second matrix elements from the first matrix and then print the
result matrix.
System.out.println("\nSubtraction of Matrices:\n");
print2dArray(sum);
}
Below method will multiply the matrix elements and print the result matrix.
System.out.println("\nMultiplication of Matrices:\n");
print2dArray(sum);
}
Practical 4: Strings :
Write a Java program to get the character at the given index within the string.
Visualal Presentation:
Java Code:
Sample Output:
Write a Java program to test if a given string contains the specified sequence of char values.
Visual Presentation:
Sample Solution:
Java Code:
// Check if str1 contains the sequence specified in str2 and print the result.
System.out.println(str1.contains(str2));
}
}
Given a String, the task is to insert another string in between the given String at a particular
specified index in Java.
Examples:
Program:
import java.lang.*;
class GFG {
String originalString,
String stringToBeInserted,
int index)
newString += originalString.charAt(i);
newString += stringToBeInserted;
return newString;
// Driver code
int index = 4;
+ originalString);
+ stringToBeInserted);
+ index);
stringToBeInserted,
index));
Output:
Approach:
Program:
import java.lang.*;
class GFG {
String originalString,
String stringToBeInserted,
+ stringToBeInserted
+ originalString.substring(index + 1);
return newString;
// Driver code
int index = 4;
+ originalString);
+ stringToBeInserted);
+ index);
+ insertString(originalString,
index));
Output:
Approach:
Program:
import java.lang.*;
class GFG {
String originalString,
String stringToBeInserted,
int index)
StringBuffer newString
= new StringBuffer(originalString);
newString.insert(index + 1, stringToBeInserted);
return newString.toString();
// Driver code
int index = 4;
+ originalString);
+ stringToBeInserted);
+ index);
stringToBeInserted,
index));
Output:
• public class MultilevelInheritance: This is the main class that contains the main method, the entry
point of the program.
• public static void main(String[] args): The main method is the starting point of the program. It
creates an instance of the Puppy class and demonstrates multilevel inheritance by calling methods
from the Animal, Dog, and Puppy classes.
• Puppy puppy = new Puppy("Buddy");: This line creates an object of the Puppy class named
"Buddy." The constructor of the Puppy class is called, which, in turn, calls the constructor of the
Dog class (its parent class), which in turn calls the constructor of the Animal class (its grandparent
class).
• puppy.eat();: This line calls the eat method of the Puppy object, which is inherited from the Animal
class. The output will be "Buddy is Eating."
• puppy.bark();: This line calls the bark method of the Puppy object, which is inherited from the Dog
class. The output will be "Buddy is Barking."
• puppy.play();: This line calls the play method of the Puppy object, which is specific to the Puppy
class. The output will be "Buddy is Playing."
• class Animal: This is the grandparent class (superclass) that represents generic animal properties
and behaviors. It has an instance variable name and a parameterized constructor that initializes the
name.
• public void eat(): The eat method of the Animal class simply prints a message indicating that the
animal is eating, including its name.
This program demonstrates multilevel inheritance, where the Puppy class inherits properties and
methods from the Dog class, which, in turn, inherits from the Animal class. When an instance of
the Puppy class is created, it can access the behavior of all three classes in the hierarchy.
Source Code
public class MultilevelInheritance // Main class
{
public static void main(String[] args)
{
Puppy puppy = new Puppy("Buddy"); // Create an instance of Puppy
Output
Buddy is Eating
Buddy is Barking
Buddy is Playing
• public class OverrideMethod: This is the main class that contains the main method, the entry point
of the program.
• public static void main(String[] args): The main method is the starting point of the program. It
creates an object of the Car class and demonstrates method overriding by calling the display
method on this object.
• Car car = new Car();: This line creates an object of the Car class.
• car.display();: This line calls the display method on the car object. Because the Car class has
overridden the display method, the specific implementation in the Car class is executed. Therefore,
the output will be "This is a Car" instead of "This is a Vehicle" that is defined in the Vehicle class.
• class Vehicle: This is the base class that represents generic vehicle properties and behaviors.
• void display(): The display method of the Vehicle class simply prints a message indicating that it is
a vehicle.
• class Car extends Vehicle: This is the derived class (subclass) that inherits from the Vehicle class.
It represents a specific type of vehicle, a car.
This program demonstrates method overriding, where a method in the derived class (Car)
provides its own implementation of a method that is already defined in the base class (Vehicle).
When the overridden method is called on an object of the derived class, the specific
implementation in the derived class is executed.
Source Code
public class AccessSpecifier // Main class
{
public static void main(String[] args)
{
Car car = new Car(); // Create an object of the child class
car.setBrand("Toyota"); // Set the brand using the public method
car.displayBrand(); // Access the protected member and method
}
}
class Vehicle // Parent class
{
protected String brand;
Output
Brand : Toyota
This Java program demonstrates constructor chaining and the use of the super keyword to call a
constructor from a superclass when creating an object of a subclass. In this program, there are two
classes: Super and Sub, where Sub inherits from Super. Here's an explanation of the program:
This program demonstrates constructor chaining, where the constructor of a subclass (Sub) can
call the constructor of its superclass (Super) using the super keyword. When an object of the
subclass is created, both constructors are called in order: first, the constructor of the superclass,
and then the constructor of the subclass. This behavior is due to the inheritance relationship
between the two classes.
Source Code
public class Constructor
{
public static void main(String[] args)
{
Sub obj = new Sub();
}
}
class Super
{
Super()
{
System.out.println("Super class Constructor called");
}
}
class Sub extends Super
{
Sub()
{
super();
System.out.println("Sub class Constructor called");
}
}
Output
Super class Constructor called
Sub class Constructor called
• public class MethodOverloading: This is the main class that contains the main method, the entry
point of the program.
• public static void main(String[] args) : The main method is where the program execution starts. It
creates an object of the Car class and demonstrates method overloading by calling two different
versions of the start method.
• Car car = new Car();: This line creates an object of the Car class.
• car.start();: This line calls the start method on the car object. Since the Car class does not override
the start method of the parent class, the method from the parent class (Vehicle) is called. The
output will be "Vehicle starting ..."
• car.start(3); : This line calls the overloaded start method in the Car class, which takes an integer
parameter. This version of the method prints a message indicating the number of cars starting. The
output will be "Starting 3 Cars ..."
• class Vehicle: This is the parent class, which has a method named start.
• void start(): The start method of the Vehicle class simply prints "Vehicle starting ..."
• class Car extends Vehicle: This is the child class that inherits from the Vehicle class.
• void start(int count): The Car class overloads the start method by defining a new version that takes
an integer parameter, count. This version of the method prints a message indicating the number of
cars starting.
This program demonstrates method overloading, where the child class (Car) defines a method
with the same name as the one in the parent class (Vehicle) but with a different parameter list.
The appropriate version of the method is called based on the number and types of arguments
provided when the method is invoked.
Source Code
public class MethodOverloading // Main class
{
public static void main(String[] args)
{
Car car = new Car();
car.start(); // Accessing parent class method
car.start(3); // Accessing overloaded method in child class
}
}
class Vehicle // Parent class
{
void start()
{
System.out.println("Vehicle starting ...");
}
Output
Vehicle starting ...
Starting 3 Cars ...
Write a Java program to create a class called Animal with a method called makeSound(). Create a
subclass called Cat that overrides the makeSound() method to bark.
This exercise shows how inheritance works in Java programming language. Inheritance allows
you to create new classes based on existing classes, inheriting their attributes and behaviors. In
this case, the 'Cat' class is a more specific implementation of the 'Animal' class, adding quarrel
behavior.
Sample Solution:
Java Code:
// Animal.java
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound.");
}
}
// Cat.java
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat quarrels.");
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Cat cat = new Cat();
animal.makeSound();
cat.makeSound();
}
}
Write a Java program to create a class called Animal with a method named move(). Create a
subclass called Cheetah that overrides the move() method to run.
Sample Solution:
Java Code:
// Animal.java
// Parent class Animal
// Cheetah.java
// Child class Cheetah
public class Cheetah extends Animal {
@Override
public void move() {
System.out.println("This cheetah is running!");
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.move();
Cheetah cheetah = new Cheetah();
cheetah.move();
}
}
Sample Output:
Animal moves
This cheetah is running!
Write a Java program to create a method that takes an integer as a parameter and throws an
exception if the number is odd.
Java Code:
Sample Output:
18 is even.
Error: 7 is odd.
Write a Java program that reads a list of integers from the user and throws an exception if any
numbers are duplicates.
Sample Solution:
Java Code:
import java.util.*;
scanner.close();
return numbers;
}
public static void checkDuplicates(List < Integer > numbers) throws Duplicate_Number_Exception {
Set < Integer > uniqueNumbers = new HashSet < > ();
Sample Output:
Write a Java program to create a method that takes a string as input and throws an exception if the
string does not contain vowels.
Sample Solution:
Java Code:
Sample Output:
Sample Solution:
Java Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
if (!scanner.hasNextLine()) {
scanner.close();
throw new EmptyFileException("File is empty.");
}
scanner.close();
}
}
Sample Output:
Write a Java program to create an array list, add some colors (strings) and print out the collection.
Pictorial Presentation:
Java Code:
import java.util.*;
public class Exercise1 {
public static void main(String[] args) {
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
System.out.println(list_Strings);
}
}
Sample Output:
Sample Solution:-
Java Code:
import java.util.LinkedList;
public class Exercise2 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> l_list = new LinkedList<String>();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
l_list.add("White");
l_list.add("Pink");
// Print the linked list
for (String element : l_list) {
System.out.println(element);
}
}
}
Sample Output:
Red
Green
Write a Java program to create a tree set, add some colors (strings) and print out the tree set.
Sample Solution:
Java Code:
import java.util.TreeSet;
public class Exercise1 {
public static void main(String[] args) {
TreeSet<String> tree_set = new TreeSet<String>();
tree_set.add("Red");
tree_set.add("Green");
tree_set.add("Orange");
tree_set.add("White");
tree_set.add("Black");
System.out.println("Tree set: ");
System.out.println(tree_set);
}
}
Sample Output:
Tree set:
[Black, Green, Orange, Red, White]
Write a generic method to count the number of elements in a collection that have a specific
property (for example, odd integers, prime numbers, palindromes).
Answer:
public final class Algorithm {
public static <T> int countIf(Collection<T> c, UnaryPredicate<T> p) {
int count = 0;
for (T elem : c)
if (p.test(elem))
++count;
return count;
}
}
where the generic UnaryPredicate interface is defined as follows:
public interface UnaryPredicate<T> {
public boolean test(T obj);
}
For example, the following program counts the number of odd integers in an integer list:
import java.util.*;
Practical 9: Event-handling :
AWTCounter
Write an AWT GUI application (called AWTCounter) as shown in the Figure. Each time the
"Count" button is clicked, the counter value shall increase by 1.
1. a java.awt.Label "Counter";
2. a non-editable java.awt.TextField to display the counter value; and
3. a java.awt.Button "Count".
The components are placed inside the top-level AWT container java.awt.Frame, arranged in
FlowLayout.
You have to use control-c, or "close" the CMD shell, or hit the "terminate" button on Eclipse's
Console to terminate the program. This is because the program does not process the WindowEvent
fired by the "window-close" button.
import java.sql.*;
try
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establishing Connection
if (con != null)
System.out.println("Connected");
System.out.println("Not Connected");
con.close();
catch(Exception e)
System.out.println(e);
Output :
Connected
Note: Here oracle in database URL in getConnection() method specifies SID of Oracle Database.
For Oracle database 11g it is orcl and for oracle database 10g it is xe.
import java.sql.*;
String id = "id1";
try
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
catch(Exception e)
System.out.println(e);
Output :
Successfully Registered
import java.sql.*;
String id = "id1";
try
Class.forName("oracle.jdbc.driver.OracleDriver");
// Updating database
"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
else
con.close();
catch(Exception e)
System.out.println(e);
Output :
Password Successfully Updated
import java.sql.*;
String id = "id2";
try
Class.forName("oracle.jdbc.driver.OracleDriver");
int x = stmt.executeUpdate(q1);
if (x > 0)
else
con.close();
System.out.println(e);
Output :
One User Successfully Deleted
import java.sql.*;
String id = "id1";
try
Class.forName("oracle.jdbc.driver.OracleDriver");
// SELECT query
ResultSet rs = stmt.executeQuery(q1);
if (rs.next())
else
con.close();
catch(Exception e)
System.out.println(e);
Output
User-Id : id1
Full Name : geeks for geeks
E-mail :geeks@geeks.org
File: MyServer.java
1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
File: MyClient.java
1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
Write a Java program to create a basic Java thread that prints "Hello, World!" when executed.
Sample Solution:
Java Code:
Sample Output:
Hello, World!
Write a Java program that creates two threads to find and print even and odd numbers from 1 to
20.
Java Code:
evenThread.start();
oddThread.start();
}
}
Sample Output:
Write a Java program that sorts an array of integers using multiple threads.
The program divides the sorting task among multiple threads and perform parallel sorting to
improve the performance of sorting large arrays.
Sample Solution:
Java Code:
import java.util.Arrays;
private static void merge(int[] array, int left, int mid, int right) {
int[] temp = new int[right - left + 1];
int i = left, j = mid + 1, k = 0;
@Override
public void run() {
Arrays.sort(array, startIndex, endIndex + 1);
}
}
}
Sample Output:
Before sorting: [317, 153, 98, 262, 171, 100, 371, 350, 386, 162, 139, 160, 69, 59, 331, 305, 12, 312, 190, 385, 355,
259, 9, 96, 217, 340, 313, 46, 47, 213, 200, 121, 94, 79, 64, 47, 91, 113, 192, 268, 135, 362, 256, 72, 299, 181, 22,
174, 360, 217, 149, 238, 67, 226, 261, 91, 26, 17, 292, 300, 107, 314, 389, 75, 222, 322, 129, 186, 133, 356, 129, 134,
313, 276, 376, 133, 352, 95, 205, 50, 152, 303, 296, 4, 281, 328, 282, 110, 16, 359, 70, 266, 143, 226, 353, 69, 395,
291, 197, 395, 171, 188, 346, 177, 179, 146, 319, 202, 71, 105, 399, 182, 367, 398, 396, 30, 170, 251, 390, 361, 75,
127, 39, 334, 294, 92, 157, 272, 120, 112, 323, 383, 122, 29, 397, 291, 392, 290, 87, 390, 39, 359, 299, 223, 88, 325,
35, 232, 46, 264, 69, 247, 392, 147, 56, 39, 345, 138, 223, 299, 114, 207, 74, 27, 160, 234, 0, 125, 44, 101, 49, 263,
216, 351, 169, 341, 346, 316, 27, 318, 27, 154, 389, 109, 141, 351, 73, 100, 17, 230, 184, 374, 214, 152, 387, 48, 235,
74, 309, 68, 185, 337, 23, 138, 281, 130, 146, 32, 82, 337, 322, 114, 399, 253, 129, 258, 256, 123, 74, 183, 158, 328,
229, 195, 177, 54, 332, 385, 88, 26, 84, 340, 252, 319, 68, 87, 76, 8, 31, 238, 196, 304, 21, 392, 86, 171, 0, 117, 310,
344, 110, 341, 37, 245, 145, 297, 185, 19, 365, 274, 168, 145, 367, 177, 198, 25, 161, 234, 141, 365, 389, 350, 102, 2,
282, 193, 15, 30, 167, 257, 293, 336, 32, 170, 330, 304, 75, 310, 248, 116, 98, 16, 245, 151, 51, 318, 322, 280, 384,
358, 362, 354, 147, 131, 382, 305, 129, 253, 179, 194, 270, 135, 92, 103, 126, 57, 214, 93, 155, 130, 107, 54, 149, 63,
128, 9, 354, 399, 392, 253, 13, 394, 306, 311, 289, 122, 338, 96, 367, 128, 8, 301, 347, 334, 269, 278, 250, 134, 158,
121, 265, 373, 39, 145, 107, 183, 83, 212, 190, 33, 83, 254, 296, 229, 66, 259, 56, 159, 45, 84, 385, 219, 32, 393, 258,
98, 139, 167, 266, 122, 14, 377, 280, 146, 157, 376, 190, 342, 145, 161, 44, 4, 296, 222, 142, 10, 1, 117, 40, 382]
After sorting: [0, 0, 1, 2, 4, 4, 8, 8, 9, 9, 10, 12, 13, 14, 15, 16, 16, 17, 17, 19, 21, 22, 23, 25, 26, 26, 27, 27, 27, 29, 30,
30, 31, 32, 32, 32, 33, 35, 37, 39, 39, 39, 39, 40, 44, 44, 45, 46, 46, 47, 47, 48, 49, 50, 51, 54, 54, 56, 56, 57, 59, 63,
64, 66, 67, 68, 68, 69, 69, 69, 70, 71, 72, 73, 74, 74, 74, 75, 75, 75, 76, 79, 82, 83, 83, 84, 84, 86, 87, 87, 88, 88, 91,
91, 92, 92, 93, 94, 95, 96, 96, 98, 98, 98, 100, 100, 101, 102, 103, 105, 107, 107, 107, 109, 110, 110, 112, 113, 114,
114, 116, 117, 117, 120, 121, 121, 122, 122, 122, 123, 125, 126, 127, 128, 128, 129, 129, 129, 129, 130, 130, 131,
133, 133, 134, 134, 135, 135, 138, 138, 139, 139, 141, 141, 142, 143, 145, 145, 145, 145, 146, 146, 146, 147, 147,
149, 149, 151, 152, 152, 153, 154, 155, 157, 157, 158, 158, 159, 160, 160, 161, 161, 162, 167, 167, 168, 169, 170,
170, 171, 171, 171, 174, 177, 177, 177, 179, 179, 181, 182, 183, 183, 184, 185, 185, 186, 188, 190, 190, 190, 192,
193, 194, 195, 196, 197, 198, 200, 202, 205, 207, 212, 213, 214, 214, 216, 217, 217, 219, 222, 222, 223, 223, 226,
226, 229, 229, 230, 232, 234, 234, 235, 238, 238, 245, 245, 247, 248, 250, 251, 252, 253, 253, 253, 254, 256, 256,
257, 258, 258, 259, 259, 261, 262, 263, 264, 265, 266, 266, 268, 269, 270, 272, 274, 276, 278, 280, 280, 281, 281,
282, 282, 289, 290, 291, 291, 292, 293, 294, 296, 296, 296, 297, 299, 299, 299, 300, 301, 303, 304, 304, 305, 305,
306, 309, 310, 310, 311, 312, 313, 313, 314, 316, 317, 318, 318, 319, 319, 322, 322, 322, 323, 325, 328, 328, 330,
331, 332, 334, 334, 336, 337, 337, 338, 340, 340, 341, 341, 342, 344, 345, 346, 346, 347, 350, 350, 351, 351, 352,
353, 354, 354, 355, 356, 358, 359, 359, 360, 361, 362, 362, 365, 365, 367, 367, 367, 371, 373, 374, 376, 376, 377,
382, 382, 383, 384, 385, 385, 385, 386, 387, 389, 389, 389, 390, 390, 392, 392, 392, 392, 393, 394, 395, 395, 396,
397, 398, 399, 399, 399]