0% found this document useful (0 votes)
9 views

Basic Java Program

Basic Java Program addition program

Uploaded by

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

Basic Java Program

Basic Java Program addition program

Uploaded by

SENTHIL R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1.

Hello World Program

class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World!"); // Output Hello World
}
}

Output:

Hello, World!

2. Addition of Two Numbers

import java.util.Scanner;

public class AddTwoNumbers


{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = scanner.nextInt();

System.out.print("Enter second number: ");


int num2 = scanner.nextInt();

int sum = num1 + num2;

System.out.println("The sum is: " + sum);


}
}

Output:

Enter first number: 3


Enter second number: 5
The sum is: 8
3.Demonstrates the use of a class

// Defining a Car class

public class Car


{
// Attributes (or instance variables)
String model;
String color;
int year;

// Constructor to initialize the object


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

// Method to display car details


public void displayDetails()
{
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
System.out.println("Car Year: " + year);
}

// Method to simulate driving


public void drive()
{
System.out.println("The " + color + " " + model + " is driving.");
}

// Main method to run the program


public static void main(String[] args)
{
// Creating an object of the Car class
Car myCar = new Car("Toyota Corolla", "Red", 2020);

// Calling methods on the object


myCar.displayDetails();
myCar.drive();
System.out.println(myCar.year);

}
}
Output:

Car Model: Toyota Corolla


Car Color: Red
Car Year: 2020
The Red Toyota Corolla is driving.
2020
4. Example of Creating and Using a User-Defined Package

Steps:

1. Create a Package: Define the package name at the beginning of the Java file using the
package keyword.
2. Create Classes Inside the Package: Define classes within the package.
3. Use the Package: Import the package into another class or program and use the classes inside
the package.

Step 1: Create a Package

Let’s say we want to create a package called myPackage.

// File: MyClass.java
package myPackage;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass in myPackage!");
}
}

Here, the class MyClass is inside the myPackage package.

Step 2: Compile the Package

After creating the Java file, save it and compile it using the following commands in the terminal:

>javac -d . MyClass.java

● -d . ensures that the package is created in a corresponding directory structure.

Step 3: Create Another Class to Use the Package

Now, we will create another Java file that will use the myPackage package.

// File: Main.java

import myPackage.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Step 4: Compile and Run

1. Compile both files:

>javac Main.java

2. Run the Main class:

>java Main

Output:

Hello from MyClass in myPackage!


5. Singly Linked List

A Singly Linked List is a data structure that consists of nodes, where each node contains data and a
reference (or pointer) to the next node in the sequence. The last node points to null, indicating the
end of the list.

Node Class for Singly Linked List

Each node in a singly linked list contains two fields:

1. Data: The value stored in the node.


2. Next: A reference to the next node in the list.

Here’s an example implementation of a Singly Linked List in Java:

1. Node Class
class ListNode {
int data; // Data stored in the node
ListNode next; // Reference to the next node

// Constructor to create a new node


public ListNode(int data) {
this.data = data;
this.next = null; // By default, next is null
}
}

2. Singly Linked List Class

This class will contain methods to manage the singly linked list, such as adding nodes,
removing nodes, and printing the list.

public class SinglyLinkedList {


private ListNode head;

// Constructor to initialize an empty linked list


public SinglyLinkedList() {
this.head = null;
}

// Method to add a new node at the end of the list


public void addNode(int data) {
ListNode newNode = new ListNode(data);
if (head == null) {
head = newNode; // If the list is empty, set the head to the new node
} else {
ListNode current = head;
while (current.next != null) { // Traverse to the last node
current = current.next;
}
current.next = newNode; // Insert the new node at the end
}
}

// Method to print the elements of the list


public void printList() {
if (head == null) {
System.out.println("The list is empty.");
return;
}
ListNode current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}

// Method to delete a node with a specific value


public void deleteNode(int key) {
if (head == null) {
System.out.println("The list is empty.");
return;
}

// If the head node itself holds the key to be deleted


if (head.data == key) {
head = head.next; // Change head to the next node
return;
}

// Search for the key to be deleted, and keep track of the previous node
ListNode current = head;
ListNode prev = null;
while (current != null && current.data != key) {
prev = current;
current = current.next;
}

// If the key was not present in the list


if (current == null) {
System.out.println("Node with value " + key + " not found.");
return;
}

// Unlink the node from the list


prev.next = current.next;
}

public static void main(String[] args) {


SinglyLinkedList list = new SinglyLinkedList();

// Adding nodes
list.addNode(10);
list.addNode(20);
list.addNode(30);
list.addNode(40);

// Printing the linked list


System.out.print("Linked List: ");
list.printList(); // Output: 10 -> 20 -> 30 -> 40 -> null

// Deleting a node
list.deleteNode(20);
System.out.print("After deletion of 20: ");
list.printList(); // Output: 10 -> 30 -> 40 -> null
}
}

Explanation:

1. ListNode Class:

● This class defines the structure of a node in the singly linked list. Each node contains two fields:
data and next, where data holds the value of the node, and next points to the next node in
the list.

2. SinglyLinkedList Class:

● head: The head of the linked list. Initially, it's set to null to indicate that the list is empty.
● addNode(int data): This method adds a new node at the end of the list. If the list is empty, it
sets the new node as the head. Otherwise, it traverses to the last node and links the new node
to the end of the list.
● printList(): This method prints all the nodes in the list, starting from the head, and
continues until it reaches the end (null).
● deleteNode(int key): This method deletes the node that contains the specified key (data
value). If the node to be deleted is the head, it updates the head. Otherwise, it searches for the
node and unlinks it from the list.

Example:

1. Adding Nodes:
○ We add nodes with values 10, 20, 30, and 40. After adding these nodes, the list looks
like this:
10 -> 20 -> 30 -> 40 -> null

Deleting a Node:

● After calling deleteNode(20), the list becomes:

10 -> 30 -> 40 -> null


6. Basic Blockchain Class

This program demonstrates the structure of a simple blockchain with blocks linked together.

import java.util.ArrayList;
import java.util.Date;

class Block {
public String hash;
public String previousHash;
private String data;
private long timeStamp;

public Block(String data, String previousHash) {


this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash();
}

public String calculateHash() {


String input = previousHash + Long.toString(timeStamp) + data;
return Integer.toString(input.hashCode());
}
}

public class SimpleBlockchain {


public static ArrayList<Block> blockchain = new ArrayList<>();

public static void main(String[] args) {


blockchain.add(new Block("First block", "0"));
blockchain.add(new Block("Second block", blockchain.get(blockchain.size() - 1).hash));
blockchain.add(new Block("Third block", blockchain.get(blockchain.size() - 1).hash));

for (Block block : blockchain) {


System.out.println("Hash: " + block.hash);
System.out.println("Previous Hash: " + block.previousHash);
System.out.println();
}
}
}
Key Components:

1. Block Class:
○ Attributes:
■ hash: The current block's hash (unique identifier).
■ previousHash: The hash of the previous block in the chain.
■ data: The information stored in the block (in this case, it's a string, but in
real blockchains, it could be transactions).
■ timeStamp: The time at which the block was created.
○ Constructor:
■ Initializes the data, previousHash, and timeStamp when a block is
created.
■ Calls the calculateHash() method to generate a unique hash for the
block.
○ calculateHash():
■ Combines previousHash, timeStamp, and data to generate the block's
hash. It uses hashCode() to compute a hash, though in actual
blockchains, a more complex and secure hashing algorithm like SHA-256
would be used.
2. SimpleBlockchain Class:
○ ArrayList<Block> blockchain:
■ A list to store all the blocks in the chain.
○ Main Method:
■ Creates three blocks.
■ Adds each block to the blockchain, where each block's previousHash
refers to the hash of the last block.
■ Prints out the hash and previousHash of each block in the chain.

Output Example:

Hash: 123456789 (calculated hash for the first block)


Previous Hash: 0

Hash: 987654321 (calculated hash for the second block)


Previous Hash: 123456789

Hash: 543216789 (calculated hash for the third block)


Previous Hash: 987654321

You might also like