0% found this document useful (0 votes)
28 views23 pages

OOPS File

The document provides a comprehensive guide on creating Java programs using various concepts such as Eclipse IDE, command line arguments, OOP principles, inheritance, polymorphism, exception handling, multithreading, packages, Java I/O, and building an industry-oriented application with Spring Framework. Each section includes step-by-step instructions and code examples to illustrate the concepts effectively. The document serves as a practical resource for learning Java programming and application development.

Uploaded by

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

OOPS File

The document provides a comprehensive guide on creating Java programs using various concepts such as Eclipse IDE, command line arguments, OOP principles, inheritance, polymorphism, exception handling, multithreading, packages, Java I/O, and building an industry-oriented application with Spring Framework. Each section includes step-by-step instructions and code examples to illustrate the concepts effectively. The document serves as a practical resource for learning Java programming and application development.

Uploaded by

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

PROGRAM:1

Use Java compiler and eclipse platform to write and execute java program.

Here's a step-by-step guide on how to write and execute a Java program using the Eclipse IDE:

1. **Install Eclipse**: If you haven't already, download and install Eclipse from the official website:
https://www.eclipse.org/downloads/

2. **Open Eclipse**: After installing, open Eclipse from your desktop or start menu.

3. **Create a New Java Project**:


- Go to "File" > "New" > "Java Project".
- Enter a project name (e.g., "MyJavaProject").
- Click "Finish".

4. **Create a New Java Class**:


- Right-click on the "src" folder within your project.
- Go to "New" > "Class".
- Enter a class name (e.g., "Main") and check the "public static void main(String[] args)" option.
- Click "Finish".

5. **Write Your Java Code**:


- Eclipse should automatically open the newly created class file.
- Write your Java code inside the `main` method.

Example:

public class Main {


public static void main(String[] args) {
System.out.println("Hello, world!");
}
}

6. **Save Your Java File**: Make sure to save your Java file (usually Ctrl + S or Command + S on macOS).

7. **Compile and Execute**:


- Eclipse automatically compiles your code in the background.
- To run the program, right-click on your Java file.
- Go to "Run As" > "Java Application".
- Alternatively, you can click the green "Run" button in the toolbar.

8. **View Output**:
- The output of your program will be displayed in the "Console" view at the bottom of the Eclipse window.
PROGRAM:2
Creating simple java programs using command line arguments

public class CommandLineArgumentsExample {


public static void main(String[] args) {
// Check if any command line arguments are provided
if (args.length == 0) {
System.out.println("No command line arguments provided.");
} else {
System.out.println("Command line arguments:");
// Iterate through the command line arguments and print them
for (int i = 0; i < args.length; i++) {
System.out.println((i + 1) + ": " + args[i]);
}
}
}
}
PROGRAM:3
Understand OOP concepts and basics of Java programming.

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects,"
which can contain data and code to manipulate that data. Java is a widely used programming language that fully
supports OOP principles. Here's an overview of some key OOP concepts and how they are implemented in Java:

1. **Classes and Objects**:


- A class is a blueprint for creating objects. It defines the properties (fields) and behaviors (methods) that
objects of that type will have.
- In Java, classes are declared using the `class` keyword. For example:

public class Car {


// Fields
String model;
int year;

// Constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}

// Method
public void drive() {
System.out.println("Driving the " + year + " " + model);
}
}

- Objects are instances of classes. They are created using the `new` keyword followed by a call to the class
constructor. For example:

Car myCar = new Car("Toyota Camry", 2020);

2. **Encapsulation**:
- Encapsulation is the concept of bundling data (fields) and methods that operate on that data within a single
unit (a class).
- In Java, you can control access to class members using access modifiers such as `public`, `private`, and
`protected`.

3. **Inheritance**:
- Inheritance allows a class (subclass or derived class) to inherit fields and methods from another class
(superclass or base class).
- In Java, you can achieve inheritance using the `extends` keyword. For example:

public class ElectricCar extends Car {


// Additional fields and methods specific to ElectricCar
}

4. **Polymorphism**:
- Polymorphism allows objects of different classes to be treated as objects of a common superclass.
- In Java, polymorphism can be achieved through method overriding and method overloading.

5. **Abstraction**:
- Abstraction refers to the process of hiding the implementation details and showing only the essential features
of an object.
- In Java, you can use abstract classes and interfaces to achieve abstraction.
PROGRAM:4
Create Java programs using inheritance and polymorphism.
Here's an example of Java programs that demonstrate inheritance and polymorphism:

# Inheritance Example:

// Parent class
class Animal {
String name;

// Constructor
public Animal(String name) {
this.name = name;
}

// Method
public void sound() {
System.out.println("Animal sound");
}
}

// Child class inheriting from Animal


class Dog extends Animal {
// Constructor
public Dog(String name) {
// Call to superclass constructor
super(name);
}

// Method overriding
@Override
public void sound() {
System.out.println(name + " barks");
}
}

public class InheritanceExample {


public static void main(String[] args) {
// Creating objects of parent and child classes
Animal animal = new Animal("Generic Animal");
Dog dog = new Dog("Buddy");

// Calling methods
animal.sound(); // Output: Animal sound
dog.sound(); // Output: Buddy barks
}
}
# Polymorphism Example:

// Parent class
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}

// Child class 1
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}

// Child class 2
class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}

public class PolymorphismExample {


public static void main(String[] args) {
// Creating objects of child classes
Shape circle = new Circle();
Shape rectangle = new Rectangle();

// Polymorphic method calls


circle.draw(); // Output: Drawing a circle
rectangle.draw(); // Output: Drawing a rectangle
}
}

In the inheritance example, the `Dog` class extends the `Animal` class, inheriting its properties and methods. The
`sound()` method is overridden in the `Dog` class to provide a specific implementation.

In the polymorphism example, both `Circle` and `Rectangle` classes inherit from the `Shape` class, and they both
override the `draw()` method to provide specific implementations. The `Shape` reference can hold objects of
`Circle` and `Rectangle` classes, and the `draw()` method calls are resolved dynamically at runtime, depending
on the actual object being referred to.
PROGRAM:5
Implement error-handling techniques using exception handling and multithreading
Below are examples demonstrating error handling using exception handling and multithreading in Java.

# Exception Handling Example:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
// Attempt to read a file that does not exist
File file = new File("nonexistent_file.txt");
Scanner scanner = new Scanner(file);
} catch (FileNotFoundException e) {
// Handle the exception
System.out.println("File not found: " + e.getMessage());
}
}
}

In this example, we attempt to read from a file that does not exist. The `FileNotFoundException` is caught in a
`try-catch` block, and we handle it by printing an error message.

# Multithreading Example:

public class MultithreadingExample {


public static void main(String[] args) {
// Creating threads
Thread thread1 = new Thread(new MyRunnable(), "Thread 1");
Thread thread2 = new Thread(new MyRunnable(), "Thread 2");

// Starting threads
thread1.start();
thread2.start();
}

// Runnable implementation
static class MyRunnable implements Runnable {
@Override
public void run() {
// Simulate some work
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
// Introducing a delay
Thread.sleep(1000);
} catch (InterruptedException e) {
// Handle interruption if necessary
e.printStackTrace();
}
}
}
}
}

In this example, we create two threads (`thread1` and `thread2`) that execute instances of the `MyRunnable` class
concurrently. Each thread simulates some work by printing numbers from 0 to 4 with a delay of 1 second
between each print statement.

If you run this code, you'll see both threads executing concurrently and printing numbers alternately.

These examples demonstrate the basics of error handling using exception handling and multithreading in Java.
It's essential to handle exceptions to make your programs robust, and multithreading allows you to perform
concurrent tasks efficiently.
PROGRAM:6
Create java program with the use of java packages.
Below is an example of a Java program that uses packages:

# Directory Structure:
MyPackageDemo/
├── src/
│ ├── com/
│ │ └── mypackage/
│ │ ├── MyClass.java
│ │ └── AnotherClass.java

# MyClass.java:

package com.mypackage;

public class MyClass {


public void display() {
System.out.println("This is MyClass in com.mypackage");
}
}

# AnotherClass.java:

package com.mypackage;

public class AnotherClass {


public void show() {
System.out.println("This is AnotherClass in com.mypackage");
}
}

# Main.java (outside the package):

import com.mypackage.MyClass;
import com.mypackage.AnotherClass;

public class Main {


public static void main(String[] args) {
MyClass obj1 = new MyClass();
AnotherClass obj2 = new AnotherClass();

obj1.display();
obj2.show();
}
}

In this example:
- `MyClass` and `AnotherClass` are part of the package `com.mypackage`.
- We import `MyClass` and `AnotherClass` into the `Main` class from the `com.mypackage` package.
- `Main` class is outside the `com.mypackage` package.
- We create objects of `MyClass` and `AnotherClass` and call their methods from the `Main` class.

To compile and run this program:


1. Navigate to the directory containing the `src` folder.
2. Compile all `.java` files using `javac src/com/mypackage/*.java Main.java`.
3. Run the program using `java Main`.

You should see the following output:

This is MyClass in com.mypackage


This is AnotherClass in com.mypackage

This demonstrates how to create and use Java packages in a program.


PROGRAM:7
Construct java program using Java I/O package.
Below is an example of a Java program that utilizes the Java I/O package to read from a file and write to another
file:

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

public class FileIOExample {


public static void main(String[] args) {
// Define file paths
String inputFile = "input.txt";
String outputFile = "output.txt";

try {
// Create FileReader and FileWriter objects
FileReader reader = new FileReader(inputFile);
FileWriter writer = new FileWriter(outputFile);

// Create BufferedReader and BufferedWriter objects for efficient reading and writing
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter bufferedWriter = new BufferedWriter(writer);

// Read from input file line by line and write to output file
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine(); // Add newline character
}

// Close the resources


bufferedReader.close();
bufferedWriter.close();

System.out.println("File copied successfully!");


} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

In this example:
- We import classes from the `java.io` package to handle file input and output operations.
- We define two file paths: `inputFile` for the file to read from and `outputFile` for the file to write to.
- Inside the `try` block, we create `FileReader` and `FileWriter` objects to read from and write to files,
respectively.
- We create `BufferedReader` and `BufferedWriter` objects for efficient reading and writing.
- We use a `while` loop to read from the input file line by line using `readLine()` method of `BufferedReader`,
and write each line to the output file using `write()` method of `BufferedWriter`. We also add a newline character
after each line.
- Finally, we close the resources (file readers and writers) using `close()` method to release any system resources
associated with them.
- We handle any `IOException` that may occur during file operations.

Make sure you have an `input.txt` file in the same directory as the program, which contains the content you want
to copy. After running this program, it will create an `output.txt` file with the same content as `input.txt`.
PROGRAM:8
Create industry oriented application using Spring Framework.

Creating a complete industry-oriented application using the Spring Framework involves several steps and
components. For the sake of brevity, I'll outline a simplified example of a web-based e-commerce application
using Spring Boot, which is a popular module of the Spring Framework for creating stand-alone, production-
grade Spring-based applications.

Let's create a basic e-commerce application with the following features:

1. User authentication and authorization.


2. Product management (CRUD operations).
3. Shopping cart functionality.

### Technologies Used:


- Spring Boot
- Spring Security
- Spring Data JPA
- Thymeleaf (for server-side templating)
- H2 Database (in-memory database)
- Maven (for dependency management)
- HTML/CSS (for frontend)

### Steps:

1. **Project Setup**:
- Set up a new Spring Boot project using your preferred IDE or Spring Initializr (https://start.spring.io/).
- Add dependencies for Spring Security, Spring Data JPA, Thymeleaf, and H2 Database.

2. **User Authentication and Authorization**:


- Configure Spring Security to handle user authentication and authorization.
- Implement user registration, login, and logout functionalities.
- Define roles (e.g., USER and ADMIN) and restrict access to certain endpoints based on roles.

3. **Product Management**:
- Create a `Product` entity with attributes like id, name, price, description, etc.
- Implement CRUD (Create, Read, Update, Delete) operations for products using Spring Data JPA.
- Develop RESTful APIs to expose product endpoints for managing products.

4. **Shopping Cart Functionality**:


- Implement shopping cart functionality for users to add products to their carts.
- Persist shopping cart data in the session or database.
- Allow users to view their cart, add/remove items, and proceed to checkout.

5. **Frontend**:
- Create HTML/CSS templates using Thymeleaf for user interface components like login/register forms,
product listings, shopping cart, etc.
- Integrate frontend with backend by making AJAX calls to RESTful APIs for fetching and updating data.

6. **Testing**:
- Write unit tests and integration tests to ensure the correctness of your application logic.
- Test different scenarios like user authentication, product CRUD operations, shopping cart functionality, etc.

7. **Deployment**:
- Package your application into a WAR or JAR file.
- Deploy the application to a web server like Apache Tomcat or use cloud platforms like AWS, Heroku, or
Azure for deployment.

8. **Continuous Integration/Continuous Deployment (CI/CD)**:


- Set up CI/CD pipelines to automate the build, test, and deployment process.
- Use tools like Jenkins, Travis CI, or GitLab CI for CI/CD pipelines.

9. **Monitoring and Logging**:


- Implement logging using SLF4J and Logback to record application events and errors.
- Set up monitoring tools like Prometheus, Grafana, or ELK stack for monitoring application performance and
health.

10. **Security and Scalability**:


- Ensure proper security measures are in place to protect against common security threats like SQL injection,
cross-site scripting (XSS), etc.
- Design your application for scalability by using distributed caching, load balancing, and horizontal scaling
techniques.

Remember, this is a simplified example, and a real-world industry-oriented application may involve more
complexities and additional features. You can further enhance the application by adding features like payment
gateway integration, order management, user reviews, recommendation systems, etc., based on your
requirements and use case.
9.) Illustrate all types of constructors with one example.

10.) WAP in java for finding vowels and consonants in a given string.

import java.util.Scanner;

public class VowelConsonantCounter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input the string

System.out.print("Enter a string: ");

String input = scanner.nextLine();

// Convert the string to lowercase to simplify comparisons

input = input.toLowerCase();

int vowels = 0, consonants = 0;

for (int i = 0; i < input.length(); i++) {

char ch = input.charAt(i);

// Check if the character is a letter


if (Character.isLetter(ch)) {

// Check if it is a vowel

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {

vowels++;

} else {

consonants++;

// Output the results

System.out.println("Number of vowels: " + vowels);

System.out.println("Number of consonants: " + consonants);

11.) Wap in java to find given number is prime or not (take input from user).

import java.util.Scanner;

Public class PrimeNumberCheck {

Public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input from user

System.out.print(“Enter a number: “);

Int number = scanner.nextInt();


Boolean isPrime = true;

// Check for numbers less than or equal to 1

If (number <= 1) {

isPrime = false;

} else {

// Check for factors from 2 to sqrt(number)

For (int I = 2; I <= Math.sqrt(number); i++) {

If (number % I == 0) {

isPrime = false;

break;

// Output the result

If (isPrime) {

System.out.println(number + “ is a prime number.”);

} else {

System.out.println(number + “ is not a prime number.”);

12.) Wap in java to print the sum of initial 10 digits enter by user.
import java.util.Scanner;

Public class SumOf10Digits {

Public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

Int sum = 0;

System.out.println(“Enter 10 digits one by one:”);

For (int I = 1; I <= 10; i++) {

System.out.print(“Enter digit “ + I + “: “);

Int digit = scanner.nextInt();

// Optional: validate that it’s a single digit (0-9)

If (digit < 0 || digit > 9) {

System.out.println(“Invalid input. Please enter a single digit (0-9).”);

i--; // repeat this iteration

continue;

Sum += digit;

System.out.println(“Sum of the 10 digits: “ + sum);

13.) Wap in java to achive inharitence concept.


// Parent class (superclass)

Class Animal {

Void eat() {

System.out.println(“This animal eats food.”);

Void sleep() {

System.out.println(“This animal sleeps.”);

// Child class (subclass) inherits from Animal

Class Dog extends Animal {

Void bark() {

System.out.println(“The dog barks.”);

// Main class to run the program

Public class InheritanceExample {

Public static void main(String[] args) {

Dog myDog = new Dog();

// Inherited methods from Animal

myDog.eat();

myDog.sleep();
// Own method of Dog class

myDog.bark();

14.) wap in java for method overriding and overloading.

// Parent class

class Calculator {

// Method Overloading (same method name, different parameters)

int add(int a, int b) {

return a + b;

int add(int a, int b, int c) {

return a + b + c;

// Method that will be overridden

void show() {

System.out.println("Calculator: Showing basic calculator");

// Subclass

class AdvancedCalculator extends Calculator {


// Overriding the show() method

@Override

void show() {

System.out.println("AdvancedCalculator: Showing scientific calculator");

// Main class

public class PolymorphismExample {

public static void main(String[] args) {

Calculator calc = new Calculator();

AdvancedCalculator advCalc = new AdvancedCalculator();

// Method Overloading examples

System.out.println("Sum of 10 and 20: " + calc.add(10, 20));

System.out.println("Sum of 1, 2 and 3: " + calc.add(1, 2, 3));

// Method Overriding example

calc.show(); // Calls method from Calculator

advCalc.show(); // Calls overridden method from AdvancedCalculator

15.) Wap in java to achive abstraction with a suitable example.


Abstraction means hiding the internal implementation and showing only the essential
features. In Java, abstraction is achieved using:

Abstract classes

Abstract methods

// Abstract class

Abstract class Shape {

// Abstract method (no body)

Abstract void draw();

// Concrete method

Void display() {

System.out.println(“This is a shape.”);

// Subclass 1

Class Circle extends Shape {

@Override

Void draw() {

System.out.println(“Drawing a Circle.”);

// Subclass 2

Class Rectangle extends Shape {


@Override

Void draw() {

System.out.println(“Drawing a Rectangle.”);

// Main class

Public class AbstractionExample {

Public static void main(String[] args) {

Shape s1 = new Circle(); // Abstract class reference -> Circle object

Shape s2 = new Rectangle(); // Abstract class reference -> Rectangle object

S1.display();

S1.draw();

S2.display();

S2.draw();

You might also like