0% found this document useful (0 votes)
8 views11 pages

Java Programming Examples and Concepts

Basic Java Program addition program

Uploaded by

SENTHIL R
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)
8 views11 pages

Java Programming Examples and Concepts

Basic Java Program addition program

Uploaded by

SENTHIL R
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

1.

Hello World Program

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

Output:

Hello, World!

2. Addition of Two Numbers

import [Link];

public class AddTwoNumbers


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

[Link]("Enter first number: ");


int num1 = [Link]();

[Link]("Enter second number: ");


int num2 = [Link]();

int sum = num1 + num2;

[Link]("The sum is: " + sum);


}
}

Output:

Enter first number: 3


Enter second number: 5
The sum is: 8
[Link] 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)
{
[Link] = model;
[Link] = color;
[Link] = year;
}

// Method to display car details


public void displayDetails()
{
[Link]("Car Model: " + model);
[Link]("Car Color: " + color);
[Link]("Car Year: " + year);
}

// Method to simulate driving


public void drive()
{
[Link]("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


[Link]();
[Link]();
[Link]([Link]);

}
}
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: [Link]
package myPackage;

public class MyClass {


public void display() {
[Link]("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 . [Link]

● -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: [Link]

import [Link];

public class Main {


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

1. Compile both files:

>javac [Link]

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) {
[Link] = data;
[Link] = 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() {
[Link] = 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 ([Link] != null) { // Traverse to the last node
current = [Link];
}
[Link] = newNode; // Insert the new node at the end
}
}

// Method to print the elements of the list


public void printList() {
if (head == null) {
[Link]("The list is empty.");
return;
}
ListNode current = head;
while (current != null) {
[Link]([Link] + " -> ");
current = [Link];
}
[Link]("null");
}

// Method to delete a node with a specific value


public void deleteNode(int key) {
if (head == null) {
[Link]("The list is empty.");
return;
}

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


if ([Link] == key) {
head = [Link]; // 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 && [Link] != key) {
prev = current;
current = [Link];
}

// If the key was not present in the list


if (current == null) {
[Link]("Node with value " + key + " not found.");
return;
}

// Unlink the node from the list


[Link] = [Link];
}

public static void main(String[] args) {


SinglyLinkedList list = new SinglyLinkedList();

// Adding nodes
[Link](10);
[Link](20);
[Link](30);
[Link](40);

// Printing the linked list


[Link]("Linked List: ");
[Link](); // Output: 10 -> 20 -> 30 -> 40 -> null

// Deleting a node
[Link](20);
[Link]("After deletion of 20: ");
[Link](); // 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 [Link];
import [Link];

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

public Block(String data, String previousHash) {


[Link] = data;
[Link] = previousHash;
[Link] = new Date().getTime();
[Link] = calculateHash();
}

public String calculateHash() {


String input = previousHash + [Link](timeStamp) + data;
return [Link]([Link]());
}
}

public class SimpleBlockchain {


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

public static void main(String[] args) {


[Link](new Block("First block", "0"));
[Link](new Block("Second block", [Link]([Link]() - 1).hash));
[Link](new Block("Third block", [Link]([Link]() - 1).hash));

for (Block block : blockchain) {


[Link]("Hash: " + [Link]);
[Link]("Previous Hash: " + [Link]);
[Link]();
}
}
}
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

Common questions

Powered by AI

The Node class used in a singly linked list contains attributes 'data' (to store the value) and 'next' (to reference the next node). Its methods include a constructor to initialize a new node with a given data value. On the other hand, the Car class has attributes like 'model', 'color', and 'year', and it includes methods for initializing an object with these attributes, displaying car details, and simulating driving with 'drive()' . These differences highlight specific use cases for each class: Node for data structure management and Car for representing object-oriented programming concepts.

Both examples exhibit object-oriented principles differently. The Car class uses encapsulation and instantiation to represent a tangible entity with attributes and behaviors, demonstrating methods and a constructor . SimpleBlockchain uses encapsulation through the Block class to model complex data structures in computer science, focusing on data security and structural linkage via the hash and previousHash . Both examples create objects (Car objects and Block instances) and operate on these objects, but they serve distinct purposes: one for representation and behavior, the other for data structuring and integrity.

In the given examples, access modifiers are used to control visibility. 'public' allows access from any other class, as seen with methods in Car class and the SimpleBlockchain’s main method, facilitating user interaction and execution . Conversely, 'private' restricts access, seen in attributes of the Block class, such as 'data' and 'timeStamp', ensuring encapsulation and protecting internal state from unwanted interference, thus maintaining integrity . These modifiers are crucial for safeguarding object integrity and enhancing code readability and security.

In Java, the 'main' method acts as the entry point for JVM execution. In the HelloWorld and Car examples, it initializes objects and invokes methods in a procedural flow . Similarly, in the SimpleBlockchain, the main method orchestrates block creation and linkage while printing their hashes . It unifies different program aspects into a runnable context, validating the combination of classes and methods into a coherent operational sequence.

Creating and utilizing a custom Java package involves several steps: define the package using the 'package' keyword at the top of the Java file, compile the class to generate the package directory structure, and use 'import' in another Java file to use classes from the package. Finally, compile and run the main file to ensure external class accessibility and functionality within the package .

The calculateHash() method in the Block class generates a unique identifier (hash) for each block based on its data, previousHash, and timeStamp. This method ensures data integrity and chain security by providing verifiable identities for blocks . In real blockchains, this function would use a robust algorithm like SHA-256 to prevent collision and ensure security .

The 'Hello World' program is simple, serving the primary function of outputting a static text. It involves creating a class and a main method, then using System.out.println to print 'Hello, World!' . In contrast, the program that adds two numbers is more complex as it requires user input, involves using the Scanner class to capture input, processes the input by converting and adding integers, and outputs a dynamic result influenced by the user's inputs .

Implementing secure hashing algorithms like SHA-256 in SimpleBlockchain would significantly enhance security by avoiding hash collisions and resisting attacks that can reverse-engineer hash values . Such algorithms ensure that each block's hash is unique and tamper-proof, critical for maintaining a secure and immutable chain. This shift would align the example more closely with real-world blockchain implementations, improving accuracy in data integrity and security against malicious threats.

Adding nodes involves iterating to the end of the list unless empty, making the complexity O(n), which can be inefficient for large lists. Yet, it doesn't require shifting elements as in arrays. Removing a node also averages O(n) complexity due to traversal for the node location, but its efficiency may decline if nodes frequently shift due to deletions . Such operations impact performance by increasing computational overhead as the list size grows, revealing a trade-off between dynamic memory allocation and access time efficiency.

Adding a node involves creating a new node object and linking it to the end of the list, either by pointing 'head' to it if the list is empty or iterating through the nodes to attach it at the end . Deleting a node requires checking if the list is empty, then matching and removing the node by unlinking it; if the node is 'head', it's directly re-assigned to the next node. This operation involves careful memory management to maintain list integrity .

You might also like