Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Lab

The document contains various Java programs demonstrating key concepts such as command line arguments, class creation, method and constructor overloading, inheritance, input/output streams, package creation, multithreading, and GUI using Swing. Each section includes code examples illustrating the respective concepts. The programs cover practical applications like calculating factorials, checking palindromes, and creating a simple GUI application.

Uploaded by

Janki Sharan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Lab

The document contains various Java programs demonstrating key concepts such as command line arguments, class creation, method and constructor overloading, inheritance, input/output streams, package creation, multithreading, and GUI using Swing. Each section includes code examples illustrating the respective concepts. The programs cover practical applications like calculating factorials, checking palindromes, and creating a simple GUI application.

Uploaded by

Janki Sharan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1.

Demonstration of Programs on Command Line Arguments


public class Factorial {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please provide a number to calculate its
factorial.");
return;
}

try {
int num = Integer.parseInt(args[0]);
if (num < 0) {
System.out.println("Factorial is not defined for negative numbers.");
return;
}

int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("The factorial of " + num + " is: " + factorial);
} catch (NumberFormatException e) {
System.out.println("Please provide a valid integer.");
}
}
}
----------------------
public class PalindromeCheck {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please provide a string to check.");
return;
}

String input = args[0];


String reversed = new StringBuilder(input).reverse().toString();

if (input.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
-------------
public class SumArgs {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers as arguments.");
return;
}

try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
} catch (NumberFormatException e) {
System.out.println("Please provide valid integers.");
}
}
}

2. Demonstration of Creation of Class, Objects


// Define a class
class Car {
// Attributes
String make;
String model;
int year;

// Constructor to initialize the object


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

// Method to display car details


public String displayDetails() {
return year + " " + make + " " + model;
}

// Method to start the car


public String start() {
return "The " + model + " is starting.";
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create objects (instances of the class)
Car car1 = new Car("Toyota", "Corolla", 2020);
Car car2 = new Car("Honda", "Civic", 2021);

// Access object methods


System.out.println("Car 1: " + car1.displayDetails());
System.out.println("Car 2: " + car2.displayDetails());

// Call methods on objects


System.out.println(car1.start());
System.out.println(car2.start());
}
}
3. Programs on Method Overloading and Constructor Overloading
//Simple Program for Method Overloading
public class MethodOverloadingExample {

// Method to add two numbers


public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three numbers


public int add(int a, int b, int c) {
return a + b + c;
}

public static void main(String[] args) {


MethodOverloadingExample obj = new MethodOverloadingExample();

// Call the method with two parameters


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

// Call the method with three parameters


System.out.println("Sum of 10, 20, and 30: " + obj.add(10, 20, 30));
}
}
//Simple Program for Constructor Overloading
public class ConstructorOverloadingExample {
int number;
String name;

// Constructor with one parameter


public ConstructorOverloadingExample(int num) {
number = num;
name = "Default Name";
}

// Overloaded constructor with two parameters


public ConstructorOverloadingExample(int num, String str) {
number = num;
name = str;
}

public void display() {


System.out.println("Number: " + number + ", Name: " + name);
}

public static void main(String[] args) {


// Create an object using the constructor with one parameter
ConstructorOverloadingExample obj1 = new
ConstructorOverloadingExample(10);
obj1.display();

// Create an object using the constructor with two parameters


ConstructorOverloadingExample obj2 = new
ConstructorOverloadingExample(20, "John");
obj2.display();
}
}
4. Programs on Inheritance and Method Overriding

// Parent Class
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}

// Child Class
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks: Woof! Woof!");
}
}

// Main Class
public class SmallInheritanceExample {
public static void main(String[] args) {
Animal animal = new Animal();
animal.sound(); // Calls the parent class method

Dog dog = new Dog();


dog.sound(); // Calls the overridden method in Dog class

Animal polyAnimal = new Dog();


polyAnimal.sound(); // Demonstrates polymorphism (calls Dog's
method)
}
}
5. Program on demonstrations of Input Output Stream.
import java.io.*;
import java.util.Scanner;
class FileIO{
void File()
{
try {
InputStream input = new FileInputStream("file.txt");
int size = input.available();
System.out.println("Available byte:"+size);
byte [] array = new byte[size];
input.read(array);
String data=new String(array);
System.out.println("Data in File\n"+data);
input.close();
}
catch(FileNotFoundException e)
{
System.err.println("Error:File Not Found.");
}
catch(IOException e){
e.printStackTrace();
}
}
void Out(){
try {
Scanner sc = new Scanner(System.in);
OutputStream out = new FileOutputStream("file2.txt");
System.out.println("Enter Data to write:-");
String data =sc.nextLine();
byte [] bdata = data.getBytes();
out.write(bdata);
System.out.println("Data Written successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class IOStream{
public static void main(String[] args) {
FileIO f = new FileIO();
f.File();
f.Out();
}
}
6. Program on Creation of Packages, importing the user defined
Package.
//Step 1: Create the package
Create a package named mypackage with a class MyClass.
File: MyClass.java

package mypackage;

public class MyClass {


public void displayMessage() {
System.out.println("Hello from MyClass inside mypackage!");
}

public int addNumbers(int a, int b) {


return a + b;
}
}
//Step 2: Compile the package
1. Save the MyClass.java file inside a folder named mypackage.
2. Open the terminal/command prompt, navigate to the directory
containing the mypackage folder, and run:

javac mypackage/MyClass.java

Step 3: Create a program to use the package


Create another Java file to import and use the mypackage.
File: MainProgram.java

import mypackage.MyClass;

public class MainProgram {


public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.displayMessage();

int sum = myObject.addNumbers(10, 20);


System.out.println("The sum of 10 and 20 is: " + sum);
}
}
Step 4: Compile and run the program
javac MainProgram.java
java MainProgram
7. Demonstration of Multithreading using Thread Class and Runnable
Interface.
// Using Thread Class
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread Class: Running in " +
Thread.currentThread().getName());
}
}

// Using Runnable Interface


class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable Interface: Running in " +
Thread.currentThread().getName());
}
}

public class SimpleMultithreadingDemo {


public static void main(String[] args) {
// Using Thread Class
MyThread thread1 = new MyThread();

// Using Runnable Interface


Thread thread2 = new Thread(new MyRunnable());

// Start the threads


thread1.start();
thread2.start();

// Main thread task


System.out.println("Main Thread: Running in " +
Thread.currentThread().getName());
}
}
8. Demonstration of GUI using Swings
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleSwingExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("Simple Swing Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);

// Create a JLabel
JLabel label = new JLabel("Click the button!");
label.setBounds(100, 50, 150, 30);
frame.add(label);

// Create a JButton
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 100, 30);
frame.add(button);

// Add an ActionListener to the button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
});

// Make the frame visible


frame.setVisible(true);
}
}

You might also like