Showing posts with label Java Coding Programs. Show all posts
Showing posts with label Java Coding Programs. Show all posts

Monday, August 22, 2022

Convert String Date of Month To number In Java

Input :  String Month : March 

Output : 3

package com.javaiq.in;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MonthConvert {

	public static void main(String[] args) throws ParseException {
		SimpleDateFormat month_date = new SimpleDateFormat("M", Locale.ENGLISH);
		SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
		String monthStr = "March";
		Date date = sdf.parse(monthStr);
		String month_name = month_date.format(date);
		System.out.println("Month :  " + Integer.parseInt(month_name));  //Mar 2016
	}
}
Month :3

Saturday, May 7, 2022

Compare two CSV files and find common values

 Compare two CSV files and find common values or print ?

Question : We have two csv files like firstName.csv and lastName.csv. firstName.csv have one name in one row and lastName.csv have one lastName in one row.

We need to find the common values in both file and print. 

Answer: To compare two CSV files we have to follow below steps.

  • Read first CSV file and store in ArrayList.
  • Read second CSV file line by line and check in first csv file ArrayList.
  • if second file's data already exist in first file csv ArrayList than print value.
Image : firstName.csv
Image : lastName.csv

Let's see below Java Code:
package com.javaiq.in;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/*
 * Program to print common data from two csv files firstName.csv and lastName.csv
 */
public class PrintCommonDataCSV {
	public static void main(String... args) {

		// Get All data from firstName.csv to ArrayList
		List<String> firstNameList = new ArrayList<>();
		Path pathToFile = Paths.get("firstName.csv");
		System.out.println(" pathToFile :" + pathToFile);
		try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) {
			String line = br.readLine();
			while (line != null) {
				firstNameList.add(line.trim());
				line = br.readLine();
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		System.out.println(firstNameList);

		/*
		 * Check if LastName present in firstNameList that mean its common data to both
		 * files and print
		 */
		Path pathToFileLastName = Paths.get("lastName.csv");
		System.out.println(" pathToFileLastName :" + pathToFileLastName);
		try (BufferedReader br = Files.newBufferedReader(pathToFileLastName, StandardCharsets.US_ASCII)) {
			String lastName = br.readLine();
			while (lastName != null) {
				if (firstNameList.contains(lastName)) {
					System.out.println("Common data in firstName.csv and lastName.csv : " + lastName);
				}
				lastName = br.readLine();
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
Output :
 pathToFile :firstName.csv
[Sanjeev, Kumar, Amit, Rahul, Gupta, Kamal]
 pathToFileLastName :lastName.csv
Common data in firstName.csv and lastName.csv : Kumar
Common data in firstName.csv and lastName.csv : Gupta
As you can see in output of above code, Kumar and Gupta are common data in both files.

Monday, January 24, 2022

Password validation in java

 How to validate a Password using Regular Expressions in Java ?

A password is considered valid password if it contains all the following constraints.

  • It must have at least 8 characters and at most 20 characters.
  • It must have at least one digit.
  • It must have at least one upper case alphabet.
  • It must have at least one lower case alphabet.
  • It must have at least one special character like !@#$%&*()-+=^.
  • It doesn’t contain any white space.
Regular expression for password validation.
regex = “^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&-+=()])(?=\\S+$).{8, 20}$”
Explain on by one:
  • ^ represents starting character of the string.
  • (?=.*[0-9]) represents at least one digit(0 to 9).
  • (?=.*[a-z]) represents at least one lower case alphabet.
  • (?=.*[A-Z]) represents at least an upper case alphabet.
  • (?=.*[@#$%^&-+=()] represents at least one special character.
  • (?=\\S+$) represents, white spaces don’t allowed in the string.
  • .{8, 20} check  the length of string must be between 8 to 20
  • $ represents the end of the string.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordValidationTest {

	public static void main(String[] args) {
		String stringPass = "Test@1235";
		if (!isValidPassword(stringPass)) {
			System.out.println("Password validation successfully.");
		} else {
			// do code here after valid password
			System.out.println("Password valid successfully.");
		}
	}

	public static boolean isValidPassword(String password) {
		String regex = "^(?=.*[0-9])" + "(?=.*[a-z])(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\S+$).{8,20}$";
		Pattern p = Pattern.compile(regex);
		// return false if empty
		if (password == null) {
			return false;
		}
		Matcher m = p.matcher(password);
		return m.matches();
	}
}
Output:
Password validation successfully.

Sunday, August 1, 2021

Spring Boot Bootstrap Thymeleaf Rich Text Editor

 Spring Boot + Bootstrap + Thymeleaf Rich Text Editor

Download Minimal Rich Text Editor With jQuery And FontAwesome - RichText

cms.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<!-- Rich Text Editor  -->
<title>RichText example</title>
<!-- <link rel="stylesheet"
	th:href="@{/assets/richtext/font-awesome.min.css}"> -->
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" th:href="@{/assets/richtext/site.css}">
<link rel="stylesheet" th:href="@{/assets/richtext/richtext.min.css}">
<script type="text/javascript"
	th:src="@{/assets/richtext/jquery.min.js}"></script>
<script type="text/javascript"
	th:src="@{/assets/richtext/jquery.richtext.min.js}"></script>
<script type="text/javascript"
	th:src="@{/assets/richtext/jquery.richtext.js}"></script>
<script>
    $(document).ready(function() {
        $('.content').richText();
    });
</script>
</head>
<body>
	<nav class="navbar navbar-inverse navbar-fixed-top">
		<div class="container">
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collapsed"
					data-toggle="collapse" data-target="#navbar" aria-expanded="false"
					aria-controls="navbar">
					<span class="sr-only">Toggle navigation</span> <span
						class="icon-bar"></span> <span class="icon-bar"></span> <span
						class="icon-bar"></span>
				</button>
				<div class="collapse navbar-collapse" id="navbarResponsive">
					<ul class="navbar-nav ml-auto">
						<li class="nav-item active"><a class="nav-link" href="#">Home
								<span class="sr-only">(current)</span>
						</a></li>
						<li class="nav-item"><a class="nav-link" href="#">About</a></li>
						<li class="nav-item"><a class="nav-link" href="#">Services</a>
						</li>
						<li class="nav-item"><a class="nav-link" href="#">Contact</a>
						</li>
					</ul>
				</div>
			</div>
		</div>
	</nav>

	<br>
	<br>

	<div class="container">
		<div class="row">
			<div class="col-md-6 col-md-offset-3">

				<div th:if="${param.success}">
					<div class="alert alert-info">You've successfully content to
						our awesome app!</div>
				</div>

				<h1>Content Management System</h1>
				<form th:action="@{/cms}" th:object="${post}" method="post">

					<div class="form-group">
						<label for="title">Title:</label> <input type="text" id="title"
							placeholder="Title" autocomplete="off" class="form-control"
							th:field="*{title}" />
					</div>

					<div class="form-group">
						<label for="content">Content:</label>
						<textarea type="text" rows="4" class="content"
							placeholder="Content" th:field="*{content}" autocomplete="off"></textarea>
					</div>

					<button class="btn btn-primary" type="submit">Submit form</button>
				</form>
			</div>
		</div>
	</div>

</body>
</html>
PostController.java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.stock.analysis.entities.Post;

/**
 * Standard Layout System with Fragment Expressions usage example
 */
@Controller
public class CmsController {

	@ModelAttribute("module")
	public String module() {
		return "post";
	}

	@ModelAttribute("post")
	public Post post() {
		return new Post();
	}

	@GetMapping("/cms")
	public String cmsEditor(Model model) {
		model.addAttribute("post", new Post());
		model.addAttribute("title", "new Titla");
		model.addAttribute("content", "Hello");
		return "cms";
	}

	@PostMapping
	public String save(Post post, Model model) {
		model.addAttribute("post", post);
		return "cms";
	}

}
Post.java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Setter
@Getter
@NoArgsConstructor
@Entity
@Table(name = "post")
public class Post {

	@Id
	@ApiModelProperty(notes = "Title")
	private String title;

	@ApiModelProperty(notes = "Content")
	private String content;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}

Sunday, November 24, 2019

Find middle index of array where both ends sum is equal

Java Program to Find middle index of array where both ends sum is equal.
Solution:- To get solution of the program we need to sum the element from both side. and compar them.
So i am going to start sum of elements from left side and sum of element from right side.

package example;

public class FindMiddleIndex {

 public static int findMiddleIndex(int[] numbers) throws Exception {

  int endIndex = numbers.length - 1;
  int startIndex = 0;
  int sumOfLeft = 0;
  int sumOfRight = 0;
  while (true) {
   if (sumOfLeft > sumOfRight) {
    sumOfRight += numbers[endIndex--];
   } else {
    sumOfLeft += numbers[startIndex++];
   }
   if (startIndex > endIndex) {
    if (sumOfLeft == sumOfRight) {
     break;
    } else {
     throw new Exception("Please pass valid array to match the requirement");
    }
   }
  }
  return endIndex;
 }

 public static void main(String a[]) {
  int[] num = { 1, 3, 6, 6, 3, 1 };
  try {
   System.out.println(
     "Sum of left element at index " + findMiddleIndex(num) + " is equal to sum of right element.");
  } catch (Exception ex) {
   System.out.println(ex.getMessage());
  }
 }
}
Output:

Sum of left element at index 2 is equal to sum of right element.

Wednesday, November 13, 2019

Find Nth Node From The End Of Linked List


package linkelist.example;

public class Node {

 private int data;
 private Node next;

 public Node(int data) {
  this.data = data;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }

 public Node getNext() {
  return next;
 }

 public void setNext(Node next) {
  this.next = next;
 }
}
package linkelist.example;

public class GetNthLastElementFromList {

 Node startNode;

 public static void main(String[] args) {
  GetNthLastElementFromList getNthLastElementFromList = new GetNthLastElementFromList();

  Node n1 = new Node(10);
  Node n2 = new Node(20);
  Node n3 = new Node(30);
  Node n4 = new Node(40);
  Node n5 = new Node(50);
  Node n6 = new Node(60);
  Node n7 = new Node(70);
  Node n8 = new Node(80);

  getNthLastElementFromList.startNode = n1;

  n1.setNext(n2);
  n2.setNext(n3);
  n3.setNext(n4);
  n4.setNext(n5);
  n5.setNext(n6);
  n6.setNext(n7);
  n7.setNext(n8);

  // Print original list.
  getNthLastElementFromList.printLinkList();

  // Print Nth last node.
  System.out
    .println(getNthLastElementFromList.getNthLastNodeFromLinkList(getNthLastElementFromList.startNode, 3));
 }

 private int getNthLastNodeFromLinkList(Node startNode, int nthPosition) {
  if (nthPosition <= 0 || startNode == null) {
   return -1;
  }

  Node slowPointer = startNode;

  // Incrementing fastPointer to nth position from start, keeping at head node
  // until fastPointer
  // reaches nth position.
  // After fastPointer reaches nth position, both pointer will advance one node at
  // a time
  // until fastPointer reaches NULL.
  // When fastPointer reaches NULL, slowPointer will be at Nth node away from
  // last.
  for (Node fastPointer = startNode; fastPointer != null; fastPointer = fastPointer.getNext()) {
   nthPosition--;

   // slowPointer will only move when fastPointer reached nth position.
   if (nthPosition < 0) {
    slowPointer = slowPointer.getNext();
   }
  }

  // If nthPosition is greater than 0, it means nthPosition is larger than the
  // number of nodes
  // present and such position doesn't exist, so return -1 in that case else
  // return data pointed by slowPointer.
  if (nthPosition <= 0) {
   return slowPointer.getData();
  }

  return -1;
 }

 private void printLinkList() {
  Node tempNode = startNode;
  while (tempNode != null) {
   System.out.print(tempNode.getData() + " ");
   tempNode = tempNode.getNext();
  }
  System.out.println("\n=============");
 }

}
Output:

10 20 30 40 50 60 70 80 
=============
60

Remove Nth Node From End of List


Find Middle Element of Linked List


package linkelist.example;

public class GetMiddleOfLinkedList {

 private Node startNode;

 public static void main(String[] args) {

  GetMiddleOfLinkedList getMiddleOfLinkedList = new GetMiddleOfLinkedList();

  Node temp1 = new Node(10);
  Node temp2 = new Node(20);
  Node temp3 = new Node(30);
  Node temp4 = new Node(40);
  Node temp5 = new Node(50);
  Node temp6 = new Node(60);
  Node temp7 = new Node(70);
  Node temp8 = new Node(80);

  getMiddleOfLinkedList.startNode = temp1;
  temp1.setNext(temp2);
  temp2.setNext(temp3);
  temp3.setNext(temp4);
  temp4.setNext(temp5);
  temp5.setNext(temp6);
  temp6.setNext(temp7);
  temp7.setNext(temp8);

  Node temp = getMiddleOfLinkedList.findMiddleNodeOfLinkedList(getMiddleOfLinkedList.startNode);
  System.out.println(temp.getData());
 }

 private Node findMiddleNodeOfLinkedList(Node startNode) {
  if (startNode == null) {
   return startNode;
  }

  Node slowPointer = startNode;
  Node fastPointer = startNode;
  while (fastPointer != null && fastPointer.getNext() != null && fastPointer.getNext().getNext() != null) {
   slowPointer = slowPointer.getNext();
   fastPointer = fastPointer.getNext().getNext();

  }
  return slowPointer;
 }
}
package linkelist.example;

public class Node {

 private int data;
 private Node next;

 public Node(int data) {
  this.data = data;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }

 public Node getNext() {
  return next;
 }

 public void setNext(Node next) {
  this.next = next;
 }
}

Output:

40

Java Coding Interview Questions-2

Q- What is output of below program?


Question-1:

Integer intObj1 = new Integer(10);
 System.out.println(intObj1);
// Output: 10


Question-2:

String str = "100";
 Integer intObj2 = new Integer(str);
 System.out.println(intObj2);
 // Output: 100


Question-3:

Integer intObj3 = new Integer("abc");
System.out.println(intObj3);
/*Output: Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.<init>(Unknown Source)

at corejavaExample.MainTest.main(MainTest.java:16)*/

Question-4:

List<Object> objList = new ArrayList<Object>();
List<String> strList = new ArrayList<String>();
objList = strList;

/*Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Type mismatch: cannot convert from List<String> to List<Object>
at corejavaExample.MainTest.main(MainTest.java:11)*/


Question-5:

Object object = new Object();
String string = new String();
object = string;  // Yes this is perfectly possible
string = object;  // this is wrong because we are casting parent to child
/*Output:- Exception in thread "main" java.lang.Error: Unresolved compilation problem:
            Type mismatch: cannot convert from Object to String
at corejavaExample.MainTest.main(MainTest.java:13)*/

Solution:- Here we need to do explicit object type casting.
string = (String) object;


Question-6:


Related Tutorials:
Object Type Casting In Java

Tuesday, November 12, 2019

Java Coding Interview Questions-1

Q- What is output of the program?

package corejavaExample;

public class C {

 public static void main(String[] args) {
  B b = new B();
  System.out.println(b.name);
 }

}

class A {

 public String name;

 public A(String name) {
  this.name = name;
 }

}

class B extends A {

}
Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Implicit super constructor A() is undefined for default constructor. Must define an explicit constructor

 at corejavaExample.B.<init>(C.java:22)
 at corejavaExample.C.main(C.java:6)

This is because parent class has parameterized constructor but child class don't have constructor So how the parent class constructor would be initialized.
So if parent class has parameterized constructor than child class must have parameterized constructor.
                 Or
Parent class should have no-argument or default constructor  then child class may not have constructor is possiple.
Solution-1:

package corejavaExample;

public class C {

 public static void main(String[] args) {
  B b = new B("Ram kumar");
  System.out.println(b.name);
 }

}

class A {

 public String name;

 public A(String name) {
  this.name = name;
 }

}

class B extends A {

 public B(String name) {
  super(name);
  // TODO Auto-generated constructor stub
 }

}
Output:

Ram kumar
Solution-2:

package corejavaExample;

public class C {

 public static void main(String[] args) {
  A b = new B();
  System.out.println(b.name);
 }

}

class A {

 public String name;

 public A() {
  System.out.println("Hi");
 }
 
 public A(String name) {
  this.name = name;
 }

}

class B extends A {

}

If parent class don't has parameterized constructor then constructor is Optional in child class (i.e. not required). clear from below example.

package corejavaExample;

public class C {

 public static void main(String[] args) {
  B b = new B();
  System.out.println(b.name);
 }

}

class A {

 public String name;

 public A() {
  System.out.println("Hi");
 }

}

class B extends A {

}
Output:

Hi
null

Sunday, August 25, 2019

One Thread Print A And Other Thread Print B

Writing a program with 2 threads, one thread print A and other thread print B.
Ouput should be like  "ABABABA....."

package com.shubh.thread.example;

public class PrintABThread2Main {

 public static void main(String[] args) {

  Thread t1 = new PrintABThread2("A");
  Thread t2 = new PrintABThread2("B");
  t1.start();
  t2.start();
 }
}

class PrintABThread2 extends Thread {

 private volatile String inputString;
 private volatile String printString = null;
 static Object lockObject = new Object();

 public PrintABThread2(String inputString) {
  this.inputString = inputString;
 }

 @Override
 public void run() {
  while (true) {
   synchronized (lockObject) {
    if (printString == inputString) {
     try {
      lockObject.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    System.out.println(inputString);
    printString = inputString;

    lockObject.notifyAll();

   }
  }
 }
}
Output of above program.

A
B
A
B
A
B
A
B
A
B
A
B
Second Way todo same program:

package com.shubh.thread.example;

public class PrintABMain {

 public static void main(String[] args) {

  PrintAB printAB = new PrintAB();
  Thread t1 = new PrintABThread(printAB);
  Thread t2 = new PrintABThread(printAB);
  t1.start();
  t2.start();
 }
}


package com.shubh.thread.example;

public class PrintABThread extends Thread {

 private PrintAB printAB;

 public PrintABThread(PrintAB printAB) {
  this.printAB = printAB;
 }

 @Override
 public void run() {
  while (true) {
   synchronized (printAB) {
    if (printAB.getStr() == "B") {
     try {
      printAB.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    printAB.printB();
    printAB.notifyAll();

   }
   synchronized (printAB) {
    if (printAB.getStr() == "A") {
     try {
      printAB.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    printAB.printA();
    printAB.notifyAll();

   }
  }
 }

}

package com.shubh.thread.example;

public class PrintAB {
 private String str;

 public void printA() {
  System.out.println("A");
  setStr("A");
 }

 public void printB() {
  System.out.println("B");
  setStr("B");
 }

 public String getStr() {
  return str;
 }

 public void setStr(String str) {
  this.str = str;
 }
}
Related Tutorial

Thursday, August 22, 2019

Print Even Odd Using Two Threads In Java

In the below program i am using reminder. if reminder is 0 (Zero) it will print Even number else if reminder is 1 then it will print Odd number.

public class EvenOdd implements Runnable {

 public int printMaxNum = 10;
 static int num = 1;
 int remainder;
 static Object lockObject = new Object();

 EvenOdd(int remainder) {
  this.remainder = remainder;
 }

 @Override
 public void run() {
  while (num < printMaxNum - 1) {
   synchronized (lockObject) {
    while (num % 2 != remainder) { // wait for numbers other than remainder
     try {
      lockObject.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
    System.out.println(Thread.currentThread().getName() + " " + num);
    num++;
    lockObject.notifyAll();
   }
  }
 }
}

public class PrintEvenOddNumber {

 public static void main(String[] args) {

  EvenOdd runnable1 = new EvenOdd(0);
  EvenOdd runnable2 = new EvenOdd(1);

  Thread t1 = new Thread(runnable1, "Even");
  Thread t2 = new Thread(runnable2, "Odd");

  t1.start();
  t2.start();
 }
}
Output:

Odd 1
Even 2
Odd 3
Even 4
Odd 5
Even 6
Odd 7
Even 8
Note:- Why i take static object in the above program. because i want to lock on same object while calling two threads.
static object are initialized only once and live until the program terminates.
Local object is created each time its declaration is encountered in the execution of program. static objects are allocated storage in static storage area.

Tuesday, August 20, 2019

Producer Consumer with BlockingQueue

A blocking queue is a queue that blocks the queue when you try to dequeue items from it. If the queue is empty. Or if you try to enqueue items into it when the queue is already full. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue.
so we don't need to implement wait and notify manually. 

Example-1

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerUsingBlickingQueue {

 public static void main(String args[]) {

  // Creating shared object
  BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();

  // Creating Producer
  Thread prodThread = new Thread(new Producer(queue));
  // Consumer Thread
  Thread consThread = new Thread(new Consumer(queue));

  // Starting producer and Consumer thread
  prodThread.start();
  consThread.start();
 }

}

class Producer implements Runnable {

 private final BlockingQueue<Integer> queue;

 public Producer(BlockingQueue<Integer> queue) {
  this.queue = queue;
 }

 @Override
 public void run() {
  for (int i = 0; i < 10; i++) {
   try {
    System.out.println("Produced: " + i);
    queue.put(i);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }

}

class Consumer implements Runnable {

 private final BlockingQueue<Integer> queue;

 public Consumer(BlockingQueue<Integer> queue) {
  this.queue = queue;
 }

 @Override
 public void run() {
  while (true) {
   try {
    System.out.println("Consumed: " + queue.take());
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }

}
Output of above program:-

Produced: 0
Produced: 1
Produced: 2
Consumed: 0
Produced: 3
Consumed: 1
Produced: 4
Consumed: 2
Consumed: 3
Produced: 5
Consumed: 4
Produced: 6
Produced: 7
Produced: 8
Consumed: 5
Produced: 9
Consumed: 6
Consumed: 7
Consumed: 8
Consumed: 9
Example-2

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerUsingBlickingQueue2 {

 public static void main(String args[]) {

  // Creating shared object
  BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();

  // Creating Producer
  Thread prodThread = new Thread(new Producer(queue));
  // Consumer Thread
  Thread consThread = new Thread(new Consumer(queue));

  // Starting producer and Consumer thread
  prodThread.start();
  consThread.start();
 }

}

class Producer implements Runnable {

 private final BlockingQueue<Integer> queue;

 public Producer(BlockingQueue<Integer> queue) {
  this.queue = queue;
 }

 @Override
 public void run() {
  int value = 0;
  while (true) {
   try {
    System.out.println("Produced: " + value);
    queue.put(value);
    value++;
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}

class Consumer implements Runnable {

 private final BlockingQueue<Integer> queue;

 public Consumer(BlockingQueue<Integer> queue) {
  this.queue = queue;
 }

 @Override
 public void run() {
  while (true) {
   try {
    System.out.println("Consumed: " + queue.take());
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}
Output of above program:-

Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
Produced: 6
Consumed: 6
Produced: 7
Consumed: 7
Produced: 8
Consumed: 8
Produced: 9
Consumed: 9
Produced: 10
Consumed: 10
Produced: 11
Consumed: 11
Produced: 12
Consumed: 12
So from the above example its clear the use of BlockingQueue in Producer Consumer without using wait and notify methods of object class.

Related Tutorial

Producer Consumer Example In Java

Producer Consumer Example In Java
                                 OR
Producer Consumer Problem with Wait and Notify - Thread Example

Example-1: Without BlockingQueue. 

import java.util.Vector;

class Producer implements Runnable {

 private Vector<Integer> queue;
 private int SIZE;

 public Producer(Vector<Integer> queue, int size) {
  this.queue = queue;
  this.SIZE = size;
 }

 @Override
 public void run() {
  for (int i = 0; i < 7; i++) {
   System.out.println("Produced: " + i);
   try {
    produce(i);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }

  }
 }

 private void produce(int i) throws InterruptedException {
  synchronized (queue) {
   // wait if queue is full
   while (queue.size() == SIZE) {
    System.out.println("Queue is full " + Thread.currentThread().getName()
      + " is waiting for consumed elements from queue , size: " + queue.size());
    queue.wait();
   }
   // add elements
   queue.add(i);
   // notify consumers
   queue.notifyAll();
  }
 }
}

class Consumer implements Runnable {

 private Vector<Integer> queue;
 private int size;

 public Consumer(Vector<Integer> queue, int size) {
  this.queue = queue;
  this.size = size;
 }

 @Override
 public void run() {
  while (true) {
   try {
    consume();
    Thread.sleep(5000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }

  }
 }

 private void consume() throws InterruptedException {
  synchronized (queue) {
   // wait if queue is empty
   while (queue.isEmpty()) {
    System.out.println("Queue is empty " + Thread.currentThread().getName()
      + " is waiting for add elements in queue , size: " + queue.size());
    queue.wait();
   }
   // Otherwise consume element and notify waiting producer
   System.out.println("Consumed: " + (Integer) queue.remove(0));
   queue.notifyAll();
  }
 }
}

public class ProducerConsumerExample {

 public static void main(String args[]) {

  Vector<Integer> queue = new Vector<Integer>();
  int size = 4;

  Thread prodThread = new Thread(new Producer(queue, size), "Producer");
  Thread consThread = new Thread(new Consumer(queue, size), "Consumer");

  prodThread.start();
  consThread.start();
 }
} 
Outpout of above program:-

Produced: 0
Queue is empty Consumer is waiting for add elements in queue , size: 0
Produced: 1
Consumed: 0
Produced: 2
Produced: 3
Produced: 4
Produced: 5
Queue is full Producer is waiting for consumed elements from queue , size: 4
Consumed: 1
Produced: 6
Queue is full Producer is waiting for consumed elements from queue , size: 4
Consumed: 2
Consumed: 3
Consumed: 4
Consumed: 5
Consumed: 6
Queue is empty Consumer is waiting for add elements in queue , size: 0
Example-2: Without BlockingQueue.

import java.util.LinkedList;
import java.util.Queue;

class ProducerOne {
 private Queue<Integer> queue;
 private int size;

 public ProducerOne(Queue<Integer> queue, int size) {
  this.queue = queue;
  this.size = size;
 }

 public void produce() throws InterruptedException {
  int value = 0;
  while (true) {
   synchronized (queue) {
    while (queue.size() >= size) {
     // wait if queue is full
     queue.wait();
    }
    queue.add(value);
    System.out.println("Produced " + value);
    value++;
    // notify the consumer
    queue.notifyAll();
    Thread.sleep(1000);
   }
  }
 }
}

class ConsumerOne {
 private Queue<Integer> queue;
 private int size;

 public ConsumerOne(Queue<Integer> queue, int size) {
  this.queue = queue;
  this.size = size;
 }

 public void consume() throws InterruptedException {
  while (true) {
   synchronized (queue) {
    while (queue.size() == 0) {
     // wait if queue is empty
     queue.wait();
    }
    int value = queue.poll();
    System.out.println("Consume " + value);
    // notify the producer
    queue.notifyAll();
    Thread.sleep(1000);
   }
  }
 }
}

public class ProducerConsumerExample2 {

 public static void main(String[] args) throws InterruptedException {

  Queue<Integer> queue = new LinkedList<>();
  int size = 2;
  ProducerOne ProducerOne = new ProducerOne(queue, size);
  ConsumerOne ConsumerOne = new ConsumerOne(queue, size);

  Thread producerThread = new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     ProducerOne.produce();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  });
  Thread consumerThread = new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     ConsumerOne.consume();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  });

  producerThread.start();
  consumerThread.start();
  producerThread.join();
  consumerThread.join();
 }
}

Outpout of above program:-

Produced 0
Consume 0
Produced 1
Produced 2
Consume 1
Consume 2
Produced 3
Produced 4
Consume 3
Consume 4
Produced 5
Produced 6
Consume 5
Consume 6
Produced 7
Produced 8
Consume 7
Consume 8
Produced 9
Produced 10
Consume 9
Consume 10
Produced 11



Sunday, August 4, 2019

TreeSet With User Defined Objects

Q- How to sort a TreeSet with user defined objects?

To store user defined objects in TreeSet you must either implements Comparable or Comparator in your class. if we do not do this then it we throw exception like below mentioned.

Exception in thread "main" java.lang.ClassCastException: com.shubh.example.User cannot be cast to java.lang.Comparable
 at java.util.TreeMap.compare(Unknown Source)
 at java.util.TreeMap.put(Unknown Source)
 at java.util.TreeSet.add(Unknown Source)
 at com.shubh.example.TreeSetExample.main(TreeSetExample.java:10)
Example-1: Using Comparable.

package com.shubh.example;

import java.util.SortedSet;
import java.util.TreeSet;

public class TreeSetExample {

 public static void main(String[] args) {
  SortedSet<User> Users = new TreeSet<>();
  Users.add(new User("Ramesh",3000));
  Users.add(new User("Joson",6000));
  Users.add(new User("Ravi",2000));
  Users.add(new User("Kamal",2400));
        for(User e:Users){
            System.out.println(e);
        }
 }
}
class User implements Comparable<User> {

 private String name;
 private int salary;

 public User(String name, int salary) {
  this.name = name;
  this.salary = salary;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getSalary() {
  return salary;
 }

 public void setSalary(int salary) {
  this.salary = salary;
 }

 public String toString() {
  return "Name: " + this.name + "-- Salary: " + this.salary;
 }

 @Override
 public int compareTo(User o) {
  if(this.getSalary() > o.getSalary()){
            return 1;
        } else {
            return -1;
        }
 }
}
Output:-

Name: Ravi-- Salary: 2000
Name: Kamal-- Salary: 2400
Name: Ramesh-- Salary: 3000
Name: Joson-- Salary: 6000
Example-2: Using Comparator.

package com.shubh.example;

import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public class TreeSetUserDefineObjectExample {

 public static void main(String[] args) {
  SortedSet<User> Users = new TreeSet<>(new UserSalaryCom());
  Users.add(new User("Ramesh", 3000));
  Users.add(new User("Joson", 6000));
  Users.add(new User("Ravi", 2000));
  Users.add(new User("Kamal", 2400));
  for (User u : Users) {
   System.out.println(u);
  }
 }
}

class User {

 private String name;
 private int salary;

 public User(String name, int salary) {
  this.name = name;
  this.salary = salary;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getSalary() {
  return salary;
 }

 public void setSalary(int salary) {
  this.salary = salary;
 }

 public String toString() {
  return "Name: " + this.name + "-- Salary: " + this.salary;
 }
}

class UserSalaryCom implements Comparator<User> {
 public int compare(User o1, User o2) {
  if (o1.getSalary() == o2.getSalary()) {
   return 0;
  }
  if (o1.getSalary() < o2.getSalary()) {
   return -1;
  } else {
   return 1;
  }
 }
}
Output:

Name: Ravi-- Salary: 2000
Name: Kamal-- Salary: 2400
Name: Ramesh-- Salary: 3000
Name: Joson-- Salary: 6000

Saturday, July 27, 2019

Custom Own ArrayList Implementation

Create Custom ArrayList.

package com.shubh.example;

import java.util.Arrays;

public class CustomArrayList {
 // Define INITIAL_CAPACITY,
 private static int INITIAL_CAPACITY = 10;
 private Object[] listArray;
 // Define size of elements in custom ArrayList
 private int size = 0;

 // constructor of custom ArrayList with default INITIAL_CAPACITY
 public CustomArrayList() {
  listArray = new Object[INITIAL_CAPACITY];
 }

 // constructor of custom ArrayList with given INITIAL_CAPACITY
 public CustomArrayList(int initSize) {
  INITIAL_CAPACITY = initSize;
  listArray = new Object[INITIAL_CAPACITY];
 }

 public Object get(int index) {
  if (index < size) {
   return listArray[index];
  } else {
   throw new ArrayIndexOutOfBoundsException();
  }
 }

 public void add(E e) {
  if (size == listArray.length) {
   ensureCapacity(); // increase capacity of list, while size of array is equal to array length.
  }
  listArray[size++] = e;
 }

 public Object remove(int index) {
  if (index < size) {
   Object obj = listArray[index];
   listArray[index] = null;
   int tmp = index;
   while (tmp < size) {
    listArray[tmp] = listArray[tmp + 1];
    listArray[tmp + 1] = null;
    tmp++;
   }
   size--;
   return obj;
  } else {
   throw new ArrayIndexOutOfBoundsException();
  }

 }

 public int size() {
  return size;
 }

 private void ensureCapacity() {
  int newIncreasedCapacity = (int) (listArray.length + Math.ceil(listArray.length / 2));
  listArray = Arrays.copyOf(listArray, newIncreasedCapacity);
  System.out.println("\nNew length: " + listArray.length);
 }

 public static void main(String a[]) {
        CustomArrayList list = new CustomArrayList(11);
 list.add(2);
 list.add(5);
 list.add(1);
 list.add(12);
 list.add(13);
 list.add(15);
 list.add(16);
 list.add(15);
 list.add(17);
 list.add(13);
 list.add(25);
 for (int i = 0; i < list.size(); i++) {
  System.out.print(list.get(i) + " ");
 }
 list.add(15);
 list.add(16);
 list.add(15);
 list.add(17);
 list.add(30);
 for (int i = 0; i < list.size(); i++) {
  System.out.print(list.get(i) + " ");
 }
 list.add(18);
 list.add(19);
 System.out.println("Element at Index 6:" + list.get(6));
 System.out.println("List size: " + list.size());
 System.out.println("Removing element at index 2: " + list.remove(2));
 for (int i = 0; i < list.size(); i++) {
  System.out.print(list.get(i) + " ");
 }
 }
}
Output:

2 5 1 12 13 15 16 15 17 13 25 
New length: 16
2 5 1 12 13 15 16 15 17 13 25 15 16 15 17 30 
New length: 24
Element at Index 6:16
List size: 18
Removing element at index 2: 1
2 5 12 13 15 16 15 17 13 25 15 16 15 17 30 18 19 

Wednesday, July 17, 2019

How to Run Threads in Sequence In Java

Q- How to Run Threads in Sequence? Or How to Run Threads in Sequence without join? Or How to make sure sequence of threads in java? 

Example - 1 : Using Join() method.

public class ThreadSequenceUsingJoin {

 public static void main(String[] args) {
  Worker worker = new Worker();
  // Three threads
  Thread t1 = new Thread(worker);
  Thread t2 = new Thread(worker);
  Thread t3 = new Thread(worker);

  try {
   // First thread
   t1.start();
   t1.join();
   // Second thread
   t2.start();
   t2.join();
   // Third thread
   t3.start();
   t3.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

class Worker implements Runnable {

 @Override
 public void run() {
  System.out.println("In run method " + Thread.currentThread().getName());
 }
}
Output

In run method Thread-0
In run method Thread-1
In run method Thread-2
Example - 2 :Without using Join() method.

public class Thread1 extends Thread {

 ThreadController threadControler;
 int sequence;

 public Thread1(ThreadController threadControler, int sequence) {
  this.threadControler = threadControler;
  this.sequence = sequence;
 }

 @Override
 public void run() {
  while (true) {
   synchronized (threadControler) {
    if (threadControler.getCount() != sequence) {

     /*
      * System.out.println("In thred --- Thread1 : Count is " +
      * threadControler.getCount() + ", Sequence is " + sequence);
      */
     try {
      threadControler.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    } else if (threadControler.getCount() == sequence) {
     System.out.println(
       "Print :: Thread1, Count is " + threadControler.getCount() + ", Sequence is " + sequence);
     threadControler.incrementCount();
     threadControler.notifyAll();
    }
   }
  }
 }
}

public class Thread2 extends Thread {

 ThreadController threadControler;
 int sequence;

 public Thread2(ThreadController threadControler, int sequence) {
  this.threadControler = threadControler;
  this.sequence = sequence;
 }

 @Override
 public void run() {
  while (true) {
   synchronized (threadControler) {
    if (threadControler.getCount() != sequence) {
     /*
      * System.out.println("In thred --- Thread2 : Count is " +
      * threadControler.getCount() + ", Sequence is " + sequence);
      */
     try {
      threadControler.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    } else if (threadControler.getCount() == sequence) {
     System.out.println(
       "Print :: Thread2, Count is " + threadControler.getCount() + ", Sequence is " + sequence);
     threadControler.incrementCount();
     threadControler.notifyAll();
    }
   }
  }
 }

}

public class Thread3 extends Thread {

 ThreadController threadControler;
 int sequence;

 public Thread3(ThreadController threadControler, int sequence) {
  this.threadControler = threadControler;
  this.sequence = sequence;
 }

 @Override
 public void run() {
  while (true) {
   synchronized (threadControler) {
    if (threadControler.getCount() != sequence) {
     /*
      * System.out.println("In thred --- Thread3 : Count is " +
      * threadControler.getCount() + ", Sequence is " + sequence);
      */
     try {
      threadControler.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    } else if (threadControler.getCount() == sequence) {
     System.out.println(
       "Print :: Thread3, Count is " + threadControler.getCount() + ", Sequence is " + sequence);
     threadControler.incrementCount();
     threadControler.notifyAll();
    }
   }
  }
 }
}

public class ThreadController {

 private volatile int count = 1;

 public int getCount() {
  return count;
 }

 public void incrementCount() {
  count++;
 }
}
Now test the above code.

public class ThreadSequenceTest {
 public static void main(String[] args) {

  // In this code we can change sequence number. So we can get the output in same
  // sequence. as in below code i want to print t2 than t1 then t3
  ThreadController threadControler = new ThreadController();
  Thread1 t1 = new Thread1(threadControler, 2);
  Thread2 t2 = new Thread2(threadControler, 1);
  Thread3 t3 = new Thread3(threadControler, 3);

  t1.start();
  t2.start();
  t3.start();
 }
}
Output

Print :: Thread2, Count is 1, Sequence is 1
Print :: Thread1, Count is 2, Sequence is 2
Print :: Thread3, Count is 3, Sequence is 3

Tuesday, July 9, 2019

Detect And Remove Loop In A LinkedList

Detect And Remove Loop In A LinkedList Or Remove loop from a linked list.
Steps:
  • First you need to check for loop in linked list.
  • To check loop. you need to take two pointers prePointer and nextPointer, prePointer will be slow and next pointer will be fast.
  • once prePointer == nextPointer that means linked list has loop.
  • slow pointer will move one step
  • faster pointer will move two steps
  • set prePointer to NULL



package linkelist.example;

public class DetectAndRemoveLinkList {

 Node startNode;

 public static void main(String[] args) {
  DetectAndRemoveLinkList g = new DetectAndRemoveLinkList();

  Node n1 = new Node(10);
  Node n2 = new Node(20);
  Node n3 = new Node(30);
  Node n4 = new Node(40);
  Node n5 = new Node(50);
  Node n6 = new Node(60);
  Node n7 = new Node(70);
  Node n8 = new Node(80);

  g.startNode = n1;

  n1.setNext(n2);
  n2.setNext(n3);
  n3.setNext(n4);
  n4.setNext(n5);
  n5.setNext(n6);
  n6.setNext(n7);
  n7.setNext(n8);
  n8.setNext(n6);

  // Detect and Remove Loop in a Linked List
  Node newStart = detectAndRemoveLoopInLinkedList(g.startNode);
  g.printList(newStart);
 }

 private static Node detectAndRemoveLoopInLinkedList(Node startNode) {
  Node slowPointer = startNode;
  Node fastPointer = startNode;
  Node previousPointer = null;

  while (fastPointer != null && fastPointer.getNext() != null) {
   slowPointer = slowPointer.getNext();
   previousPointer = fastPointer.getNext(); // For capturing just previous node of loop node for setting it to
              // null for breaking loop.
   fastPointer = fastPointer.getNext().getNext();

   if (slowPointer == fastPointer) { // Loop identified.
    slowPointer = startNode;

    // If loop start node is starting at the root Node, then we slowpointer,
    // fastpointer and head all point at same location.
    // we already capture previous node, just setting it to null will work in this
    // case.
    if (slowPointer == fastPointer) {
     previousPointer.setNext(null);

    } else {
     // We need to first identify the start of loop node and then by setting just
     // previous node of loop node next to null.
     while (slowPointer.getNext() != fastPointer.getNext()) {
      slowPointer = slowPointer.getNext();
      fastPointer = fastPointer.getNext();
     }
     fastPointer.setNext(null);
    }
   }
  }
  return startNode;
 }

 // Print linked list.
 private void printList(Node startNode) {
  while (startNode != null) {
   System.out.print(startNode.getData() + " ");
   startNode = startNode.getNext();
  }
 }

}
package linkelist.example;

public class Node {

 private int data;
 private Node next;

 public Node(int data) {
  this.data = data;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }

 public Node getNext() {
  return next;
 }

 public void setNext(Node next) {
  this.next = next;
 }
}

Output:

10 20 30 40 50 60 70 80 
Related Tutorials

Custom LinkedList implementation in java


package com.shubh.example;

public class CustomLinkedList {

 Node head; // head of list
 private static int counter;

 static class Node {

  Object data;
  Node next;

  // Constructor
  Node(Object d) {
   data = d;
   next = null;
  }

  public Object getData() {
   return data;
  }

  @SuppressWarnings("unused")
  public void setData(Object dataValue) {
   data = dataValue;
  }

  public Node getNext() {
   return next;
  }

  public void setNext(Node nextValue) {
   next = nextValue;
  }
 }

 // This methods is use to add element into list
 public void add(Object data) {
  // create new node while adding new element
  Node new_node = new Node(data);
  new_node.next = null;

  // checking if current linked list is empty the assign new data at head
  if (head == null) {
   head = new_node;
  } else {
   // else find the last node
   // and add the new element there
   Node last = head;
   while (last.next != null) {
    last = last.next;
   }

   // Insert the new element at last node
   last.next = new_node;
  }

  // increment the number of elements variable
  incrementCounter();
 }

 // add element at the specified position in the linked list
 public void add(int index, Object data) {
  Node new_node = new Node(data);
  Node currentNode = head;
  if (index == 0) {
   new_node.setNext(currentNode);
   head = new_node;
  } else {
   if (currentNode != null) {
    for (int i = 0; i < index - 1 && currentNode.getNext() != null; i++) {
     currentNode = currentNode.getNext();
    }
   }
   // set the new node's next-node reference to this node's next-node
   // reference
   new_node.setNext(currentNode.getNext());

   // now set this node's next-node reference to the new node
   currentNode.setNext(new_node);
  }

  // increment the number of elements variable
  incrementCounter();
 }

 // removes the element at the specified position in this list.
 public boolean remove(int index) {

  // check if index is out of range
  if (index < 1 || index > size()) {
   return false;
  }

  Node currentNode = head;
  if (head != null) {
   for (int i = 0; i < index - 1; i++) {
    if (currentNode.getNext() == null) {
     return false;
    } else {
     currentNode = currentNode.getNext();
    }
   }
   currentNode.setNext(currentNode.getNext().getNext());

   // decrement the number of elements variable while remove element
   decrementCounter();
   return true;

  }
  return false;
 }

 // this method is used to get element at specified index or position
 public Object get(int index) {
  // check index must be grater 0 or equal to 0 (Zero)
  if (index < 0) {
   return null;
  }
  Node currentNode = null;
  if (head != null) {
   currentNode = head;
   for (int i = 0; i < index; i++) {
    if (currentNode.getNext() == null) {
     return null;
    } else {
     currentNode = currentNode.getNext();
    }
   }
   return currentNode.getData();
  }
  return currentNode;

 }

 // Method to print the LinkedList.
 public static void printLinkedList(CustomLinkedList list) {
  Node currentNode = list.head;

  System.out.print("LinkedList: ");

  // Traverse through the LinkedList
  while (currentNode != null) {
   // Print the element at current node of list
   System.out.print(currentNode.data + " ");

   // Go to next element of list
   currentNode = currentNode.next;
   // System.out.println("--p--"+currentNode.data);
  }
  System.out.println();

 }

 private static void incrementCounter() {
  counter++;
 }

 private void decrementCounter() {
  counter--;
 }

 // returns the total number of elements in linked list.
 public int size() {
  return getCounter();
 }

 private static int getCounter() {
  return counter;
 }

 public String toString() {
  String output = "";

  if (head != null) {
   Node currentNode = head.getNext();
   while (currentNode != null) {
    output += "[" + currentNode.getData().toString() + "]";
    currentNode = currentNode.getNext();
   }

  }
  return output;
 }

 public static void main(String[] args) {
  // Initialize empty linked list
  CustomLinkedList list = new CustomLinkedList();
  // list.add(0);
  list.add(1);
  list.add(2);
  list.add(3);
  list.add(4);
  list.add(5);
  list.add(6);
  list.add(7);
  list.add(8);
  // Print all elements of the LinkedList
  printLinkedList(list);
  list.remove(3);
  System.out.println("After remove element At Index 3 : element 4 is removed");
  printLinkedList(list);
  list.add(0, 5);
  System.out.println("After add element At index 0 : element 5 is added");
  printLinkedList(list);
  list.add(3, 10);
  System.out.println("After add element At index 3 : element 10 is added.");
  printLinkedList(list);
  System.out.println("Get element At index 0 :" + list.get(0));
 }
}