Sunday, March 12, 2023

Microservice

Use of Microservice 

In Java, a microservice architecture typically involves breaking down an application into small, independent services that can be developed, deployed, and scaled independently. Each microservice typically handles a specific function or feature of the application and communicates with other microservices through APIs. 

 How to Implement Microservice 

To implement microservices in Java, you can use a variety of tools and frameworks, such as Spring Boot, Micronaut, Quarkus, or Vert.x. 
These frameworks provide features like dependency injection, configuration management, and service discovery to make it easier to develop and deploy microservices. 
To create a microservice in Java using Spring Boot, you can follow these basic steps: 
Define the API endpoints: Define the endpoints that your microservice will expose to other services or clients. 
  1.  Implement the business logic: Write the code that handles the functionality of your microservice. Configure the application: Use Spring Boot annotations to configure the application and manage dependencies. 
  2.  Build and deploy: Build the application into a deployable format, such as a JAR file, and deploy it to a container, such as Docker or Kubernetes. 
  3.  Monitor and scale: Monitor the performance of your microservices and scale them up or down as needed to handle changing demand.
Overall, the microservice concept in Java involves building small, independent services that work together to provide a larger application. This approach can offer greater flexibility, scalability, and resilience than traditional monolithic architectures.

Java Interview Question

Java Interview Question

1. What is the difference between an abstract class and an interface?

Answer: An abstract class can have both abstract and non-abstract methods, whereas an interface can only have abstract methods. An abstract class can also have constructors, instance variables, and method implementations, whereas an interface cannot.

Abstract Class Example 

public abstract class Vehicles {
   private int numOfWheels;
   
   public Vehicles(int numOfWheels) {
      this.numOfWheels = numOfWheels;
   }
   
   public int getNumOfWheels() {
      return this.numOfWheels;
   }
   
   public abstract void drive();
}

Interface Example

public interface Drivable {
   void drive();
}

2. What is the difference between a HashMap and a Hashtable?

Answer: HashMap is not thread-safe, whereas Hashtable is thread-safe. HashMap allows null values for both keys and values, whereas Hashtable does not allow null keys or values.

Example :

Creating a HashMap and adding elements

HashMap<String, Integer> myHashMap = new HashMap<>();
myHashMap.put("John", 25);
myHashMap.put("Ravi", 30);
int value = myHashMap.get("John");

Creating a Hashtable and adding elements

Hashtable<String, Integer> myHashTbl = new Hashtable<>();
myHashTbl.put("John", 25);
myHashTbl.put("Ravi", 30);
int value = myHashTbl.get("John");

3. What is the difference between an inner class and a nested class?

Answer: An inner class is a non-static nested class, whereas a nested class can be either static or non-static. An inner class has access to the instance variables and methods of the enclosing class, whereas a static nested class does not.

Example :

Inner class 

public class OuterClass {

   private int x;
   
   public class InnerClass {
      public void printX() {
         System.out.println(x);
      }
   }

Nested class example

   public static class NestedClass {
      public void printHello() {
         System.out.println("Hello Java-Scholars");
      }
   }
}

4. What is the difference between a StringBuilder and a StringBuffer?

Answer: StringBuilder is not thread-safe, whereas StringBuffer is thread-safe. StringBuilder is faster because it is not synchronized, whereas StringBuffer is slower because it is synchronized.

Example:

Using StringBuilder

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("Java-Scholars");
String result = sb.toString();
Using StringBuffer
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("Java-Scholars");
String result = sb.toString();

5. What is the difference between an ArrayList and a LinkedList?

Answer: ArrayList is implemented as a dynamic array, whereas LinkedList is implemented as a doubly-linked list. ArrayList is faster for random access and iteration, whereas LinkedList is faster for inserting and removing elements.

Example :

Creating an ArrayList and adding elements

ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);

Creating a LinkedList and adding elements

LinkedList<Integer> myList = new LinkedList<Integer>();
myList.add(1);
myList.add(2);

6. What is the difference between a checked and an unchecked exception?

Answer: A checked exception is a type of exception that must be declared in the method signature or caught in a try-catch block. An unchecked exception is a type of exception that does not need to be declared or caught.

Example :

Checked exception

public void myMethod() throws IOException {
   // Code here
}

Unchecked exception

public void myMethod() {
   throw new NullPointerException();
}

Friday, August 16, 2019

Java Features

The various features of java language are:

1) Simple: 

The java language is called as a simple programming language because of the following reasons.
  1. The syntax of java programming language similar to another programming language like c, c++, etc and simple to migrate from other languages.
  2. Complex topics like pointers, templates, etc. are eliminated from java making it simple.
  3. In the Java language, the programmer is responsible for the only allocation of memory. The deallocation of the memory is done by the garbage collector

2) Object-Oriented: 

The java language is called an object-oriented language. Any language can be called object-oriented if the development of the application is based on objects and classes.
  1. Object: Any entity that exists physically in this real-world which requires some memory is called an object. Every object contains some properties and some actions. The properties are the data which describes the object and the actions are the tasks or the operations performed by the objects.
  2. Class: A class is a collection of common properties and common actions of a group of objects. A class can be considered as a plan or model or a blueprint for creating the objects. For every class, we can create any number of objects and without a class, the object can't be created. Example: class: Student  object: tonny, rajiv
    java-object-oriented

3) Secured: 

Security one of the most important principles of any programming language. The java language contains inbuilt security programs for projecting the data from unauthorized usage.

4) Distributed: 

Using the distributed features we can access the data available in multiple machines and it to the user. Using these features we can improve the performance of the application by making the data more available and more accessible.

5) Platform Independent or machine-independent or Architecture Neutral: 

Java program can be executed on any machine irrespective of their hardware, software, architecture, operating system, etc, therefore, it is called a platform-independent language.

C language: when we compile a C program, the compiler verifies whether the ‘C’ language instruction valid are not if valid the compiler generates .exe file  containing machine language instructions.

Demo.c ( c lang. inst.)      compiler       Demo.exe(machine lang. inst.)

The machine language instructions available in the .exe files generated by the compiler can be executed only in that machine, where it is compiled. If we want to execute the C language makes it machine dependent language.

Java language: When we compile java program, the compiler verifies whether the java language instructions are valid or not,  if valid the compiler will generate .class a file containing special java instructions(byte code instructions).

Demo.c ( c lang. inst.)    compiler      Demo.class(byte code inst.)

The special java instructions available in the .class file generated by the compiler can be executed on any machine with the help of JVM, without recompile it. This nature of java language makes it platform-independent.

6) Interpreted: 

The java language said to interpreted language as the execution of the program is done by the interpreter available inside the JVM.

7) High performance: 

The execution of the program is done by the interpreter along with the special compiler and JIT(Just-in-Time) compiler, thereby reducing the execution time and improving the performance of the application.

8) Portable: 

We can develop an application which is a collection of components which can be replaced and reused.

9) Multithreaded: 

Every thread in java program is a control. if the program contains multiple controls then we can reduce the waiting time, and provide response faster and thereby improving the performance.

10) Dynamic: 

The java program is said to be dynamic because the allocation of memory is done at execution time according to the requirement.

11) Robust: 

The java language said to be a strong programming language. Because of the following reasons: 
  1. Memory Management: In java language allocation of memory and deallocation of memory, both are efficient. During the memory allocation time, there will be no wastage of memory and deallocation done by garbage collector which also efficient as the unused memory will be removed.
  2. Exception handling: the errors the occurs at runtime because of logical failure, invalid input is called as the exception. When an exception occurs, the application will be terminated abnormally and execution incompletely. In order to code execute completely and terminate normally. We can take the help pf exception handling. The process of execution handling in java is simple and efficient.

Java


Java Introduction

java-oracle-logo, java, java introduction
Java is an open-source API (application programming interface) provided by the Oracle Corporation(currently) and its free API, anyone can use for the development of the business application/software.

Java is an Object-Oriented programming language, which is executed by a machine to reduce the burden of a user or human being by performing the operations faster without any mistakes.
It is machine-independent programming, we can run java application on any machine with the help of java virtual machine(JVM).
Program: A program is a set of instructions.
Software:  It is a set of programs, which can perform multiple tasks.

Software classified into two types:

1. System software

The software is designed to interact or communicate with the hardware device and make them work is called system software. This software is generally developed in a language like c, c++, etc.
Example: Operation System, driver, compiler, etc.

2. Application software

The software which is designed to store data, provide entertainment, do business, generate reports, etc. are called as application software. This software generally developed in a language like java, .net, python, etc.
The Application software’s are further classified into two types.

I. Standalone software:  

The software which can execute in the context of a single machine(computer) is called as standalone software.
Example: MS-Word, media player, etc.

II. Web-based software: 

The software which can be executed on any a machine in the context of browser is called as a web-based software.
Example:  Gmail, Facebook, etc.

Java History

James Gosling, Mike Sheridan, and Patrick Naughton started the first java project in 1991 for the Digital Cable Television Industry. Java is an object-Oriented, multi-purpose, cross-platform programming language. Java versions are provided in the form of Java development tools (JDK) it's completely free(Open Source).
The java language is released by Sun Microsystem in the year 1995 in three editions.

  1. JSE(java standard edition): This edition can use for developing standalone software.
  2. JEE(java enterprise edition): This edition can use for web-based application/software.
  3. JME(java mobile edition): This edition used for developing an application for mobile devices, wireless devices, embedded controllers, etc. where memory is limited.

Java Coding Example

package in.blogspot.scholars.java;

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

System.out.println("hello java programming language”);
}
}

Monday, August 5, 2019

Spring boot Example | Spring REST Example with Spring boot

In Spring Framework lots of modules like spring boot, spring web services, spring-security, spring Kafka, spring data, spring integration, spring cloud. etc. spring boot module used to create the spring-based web application.
Learn more about spring boot click on this link- Why We Used Spring boot? 

Spring boot Example

In this spring boot example provides,  how to create spring REST Application with spring boot using Maven project, spring REST, spring MVC, Devtools dependency, java 1.8, STS development tool, Spring Initializr, we are looking mainly used off the @Restcontroller, @Responsebody, @ComponentScan  annotation

Steps to Create the Springboot Application

1. Let's create the spring boot project using spring initializer,  Go to the start.spring.io and select the Maven project, fill the project name, package name, packaging jar/war, add the basic dependency like Web, Devtools, Actuator. and click on the generate project button. start the downloading. once complete the download, extract the zip folder.
Spring initializr, spring boot example
Spring Initializr
2. Open the Spring Tool Suite (STS), import the project as an existing maven project.
spring boot project, spring boot example
spring-boot project
3. Add the remaining spring-boot maven dependencies in pom.xml from the central maven repository

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.4.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>
 <groupId>in.blogspot.scholars.java</groupId>
 <artifactId>springbootexample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>springbootexample</name>
 <packaging>jar</packaging>
 <description>springbootexample project for Spring Boot</description>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
   <optional>true</optional>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-jasper -->
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-tomcat -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
  </dependency>
  <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
  </dependency>
  <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>

4. Create an Employee bean class. i.e Employee.java

package in.blogspot.scholars.java.employee;

public class Employee {

private Integer id;
private String name;
private String dept;
private String address;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

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

public String getDept() {
return dept;
}

public void setDept(String dept) {
this.dept = dept;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", dept=" + dept + ", address=" + address + "]";
}
}

5. Create a service class that contains your business logic, that is EmployeeServiceImpl.java

package in.blogspot.scholars.java.employee;

import org.springframework.stereotype.Service;

@Service
public class EmployeeServiceImpl {

public Employee getEmployeeDetails() {

Employee employee = new Employee();
employee.setId(1);
employee.setName("Narendra");
employee.setDept("IT");
employee.setAddress("India");
return employee;
}
}

6. Create a Constant class for URL mapping. It is the best programming practice to define all constants separately. i.e UrlConstant.java

package in.blogspot.scholars.java.employee;

public class UrlConstant {

public static final String MESSAGE = "/message";
public static final String EMPLOYEE_URL = "/get-employee";

}


7. Create the controller that handles all the requests coming from the dispatcher servlet and prepare the model & view object and sending a response to the dispatcher servlet. i.e. EmployeeController.java
Dispatcher servlet is a parent controller that handles every request coming from the server and sending the response to the server.

package in.blogspot.scholars.java.employee;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {

@Autowired
private EmployeeServiceImpl employeeServiceImpl;

@RequestMapping(value = UrlConstant.MESSAGE, method = RequestMethod.GET)
public String getMessage() {

return "welcome to the https://java-scholars.blogspot.com";
}

@RequestMapping(value = UrlConstant.EMPLOYEE_URL, method = RequestMethod.GET)
public Employee getEmployeeDetails() {

return employeeServiceImpl.getEmployeeDetails();
}
}

8. Finally, annotate the SpringbootexampleApplication.java class with @ComponentScan("base package name").

package in.blogspot.scholars.java.springbootexample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(value= {"in.blogspot.scholars.java.*"})
public class SpringbootexampleApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootexampleApplication.class, args);
}

}

9. How to Run a spring boot application?

Once complete the coding, configuration of the spring application.
Right-click on the project, select Run As and click on the Spring boot App or Java Application.

spring-boot app run

10. How to Test a spring application on any web browser?


Open any Web Browser, type the http://localhost:8080/get-employee
It's recommended the spring REST API testing purposed used the Postman or SOAPUI  tools.


here, localhost -for development stage or application running on the local system.
for production/testing/QA stages used the domain name or IP address instead of localhost. for example https://java-scholars.blogspot.in/get-employee or https://www.abc.com/get-employee

here, 8080 is the default port number of the Apache Tomcat server, if you want to change this port number then go to the application.properties and write the server.port=8081 or as per your choice

here, /get-employee is requested coming from the server to the controller, request handler check exact matching RequestMapping available or not, if available then sending the response. if Not available throw the  404 exceptions.

11. How to create an executable jar/war of the spring boot application? or maven command for jar/ war creation of the spring boot application.

Right-click on a project, select Run As  and click on a Maven clean,
Right-click on a project, select Run As and click on a Maven build, write the goals: package and click on Run button.

12. How to deploy spring boot application in Apache Tomcat server?

Created a jar/war location inside the target folder of your spring boot project.
When deploying the spring boot application on any server then pass the complete path of the jar/war file. Let's go to the command prompt for the deployment of jar/war.

C:\WINDOWS\system32>java -jar V:\target\springbootexample-0.0.1-SNAPSHOT.jar
Above command applicable for both packaging type(jar/war).

13. How to stop the server?

control + c

Spring boot related most important topics are-
What is spring boot?
Click here for download the project- springbootexample.zip

Saturday, August 3, 2019

Java Logical Programs | Java Programming Examples

Java features and java logical program is commonly asked in every interview room. before you go for an interview must prepare java programming examples. In IT industries,  every interviewer checking your logic based on java logical programs and java logical code example.

1. Write a java program to find the duplicate vowel and count the duplicate vowel from a given string?

input = "Scholars-Java Blogspot in"
package in.blogspot.scholars.java;

public class RemoveVowelExample {

public static String removeVowels(String input) {

String novowelString = "";

String presentVowel = "";

int vowelCount = 0;

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

// vowel does not present then print

if (!isVowel((input.charAt(i)))) {

novowelString = novowelString + input.charAt(i);

} else {

presentVowel = presentVowel + input.charAt(i);

vowelCount++;

}

}

System.out.println("present vowel = " + presentVowel);

System.out.println("COUNT present vowel into the String = " + vowelCount);

return novowelString;

}

public static boolean isVowel(char c) {

// check input each character from input string

// 5 vowels checking with your each input character String

String vowels = "auioe";

for (int i = 0; i < 5; i++) {

if (c == vowels.charAt(i))

return true;

}

return false;

}
public static void main(String[] args) {

// enter input string

String input = "Scholars-Java Blogspot in";

String removeVowels = removeVowels(input.toLowerCase());

System.out.println("final non vowel String = " + removeVowels);

}

}
Output:

present vowel = oaaaooi
COUNT present vowel into the String = 7
final non vowel String = schlrs-jv blgspt n

2. Write a java program to find/check the duplicate character and count the duplicate character from the given string?

input: "javaScholars"
package in.blogspot.scholars.java;

public class duplcateCharacterFromStringExample {

public static void main(String[] args) {

String str = "javaScholars";

int count = 0;

// store each lower case character into char Arrays

char[] input = str.toLowerCase().toCharArray();

System.out.println("Duplicate Characters are = ");

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

for (int j = i + 1; j < str.length(); j++) {

if (input[i] == input[j]) {
System.out.print(input[j] + " ");
count++;
break;
}
}
}
if (count > 0)

System.out.println("\nDuplicate character COUNT from String = " + count);

else

System.out.println("No Duplicate = " + str);

}

}
Output:

Duplicate Characters are =
a a s
Duplicate Character COUNT from String= 3

3. Write a java program to check/find the given string anagram or not?

input = "javaS";
input2 = "Vjasa ";
package in.blogspot.scholars.java;

import java.util.Arrays;

public class AnagramOrNotExample {


public static void main(String[] args) {


// If the same length of both an exact match each character to each other

// is known as Anagram

// 1. madam or mmaad or madma

String input = "javaS";

String input2 = "Vjasa ";

// remove space may contain

String str1 = input.replaceAll("\\s", "");

String str2 = input2.replaceAll("\\s", "");

// check

boolean status = true;

// check length equal or not

if (str1.length() != str2.length()) {

status = false;

} else {

// make lower case both

// convert string in each character and add into arrays

char[] ch = str1.toLowerCase().toCharArray();

char[] ch2 = str2.toLowerCase().toCharArray();

// sort ascending order

Arrays.sort(ch);

Arrays.sort(ch2);

// check string one of each character to another String of each

status = Arrays.equals(ch, ch2);

// if true

if (status) {

System.out.println("is anagram : " + input + "==" + input2);

}

// if false

if (status == false) {

System.out.println("is NOT anagram : " + input + "==" + input2);

}

}

}

}
Output:
is anagram : javaS==Vjasa

4. Write a java program to find/check given mobile number fancy number or not?

input = "9788865456"
package in.blogspot.scholars.java;

public class FancyNumberExample {

public static void main(String[] args) {

// 1. 987/321

// 2. 123/789

// 3. 111/999

String input = "9788865456";

int[] arr = new int[input.length()];

for (int i = 0; i < input.length(); i++) {
// string to char and char to int arrays
arr[i] = Character.getNumericValue((input.charAt(i)));
}
int count = 1;
for (int i = 0; i < arr.length - 1; i++)
{
// consecutive equal no, ascending order sequence sequence, descending sequence
if (arr[i + 1] == arr[i] || arr[i + 1] - arr[i] == 1 || arr[i] - arr[i + 1] == 1)
{
count++;
}
}
// If more than two continue the same number then fancy no. otherwise NOT
if (count > 2)

System.out.println("count = " + count + " Number is fancy ::" + input);

else

System.out.println("count= " + count + " Number is NOT fancy ::" + input);

}
}
Output: 

count = 8 Number is fancy ::9788865456

5. Write a java program to swap two numbers without using 3 variables?

input value1 = 20
input value2 = 10
package in.blogspot.scholars.java;

public class SwapTwoNumberExample {

public void swapTwoVariable() {
// test cases
// 1. value1 = 20, value2 = 20
// 2. value1 = 10, value2 = 20
// 3. value1 = 20, value2 = 10

int value1 = 20, value2 = 10;
System.out.println(" value1 " + value1 + "\n value2 " + value2);
if (value2 == value1) {
System.out.println(" Not required to SWAP");
}
if (value2 > value1) {
value1 = value1 + value2;

value2 = value1 - value2;
value1 = value1 - value2;
System.out.println(" SWAP IS : \n value1 " + value1 + "\n value2 " + value2);
}
if (value2 < value1)
{
{
value2 = value1 + value2;
value1 = value2 - value1;
value2 = value2 - value1;
System.out.println(" SWAP IS :\n value1 " + value1 + "\n value2 " + value2);
}
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwapTwoNumberExample calling = new SwapTwoNumberExample();
calling.swapTwoVariable();
}
}
Output:

value1 20
value2 10
SWAP IS :
value1 10
value2 20

6. Write a java program to reverse number?

input = 4537
package in.blogspot.scholars.java;

public class ReverseStringNumberExample {

public void numberReverse(int num) {

int reverse = 0;

while (num != 0) {

reverse = reverse * 10;

reverse = reverse + num % 10;

// System.out.println(reverse);

num = num / 10;

}

System.out.println("Reverse number = " + reverse);
}

public static void main(String[] args) {

// TODO Auto-generated method stub

ReverseStringNumberExample revStr = new ReverseStringNumberExample();

//input number

revStr.numberReverse(4537);
}

}
Output: 

Reverse number = 7354

7. Write a java program to reverse a string without using the reverse () method?

input = "Java Scholars";
package in.blogspot.scholars.java;

public class ReverseStringNumberExample {

// Reverse String

public void stringreverse() {

String str = "Java Scholars";

String s = "";

//int i;

int length = str.length();

for (i = length - 1; i >= 0; i--) {

s = s + str.charAt(i);

}

System.out.println("reverse string = " + s);

System.out.println();

}

public static void main(String[] args) {

// TODO Auto-generated method stub

ReverseStringNumberExample revStr = new ReverseStringNumberExample();

revStr.stringreverse();
}
}
Output: 

reverse string = sralohcS ava

8. Write a java program to print pyramid pattern of stars?

row input: 5
package in.blogspot.scholars.java;

import java.io.IOException;

public class StarTringleExample {

public static void printtriangle(int rows) {

// spaces

int s = 2 * rows - 2;

// outer loop to handle the number of rows

// rows in this case

for (int i = 0; i < rows; i++)
{
// inner loop to handle number spaces
// values changing according to the requirement
for (int j = 0; j < s; j++)
{
// print spaces
System.out.print(" ");
}
// Decrementing space after each loop
s = s - 1;
// inner loop to handle the number of columns

// values changing according to the outer loop
for (int j = 0; j <= i; j++)
{
// print stars
System.out.print("*" + " ");
}
// new line for each row
System.out.println();
}
}
public static void main(String[] args) throws Exception
{
/ / input rows
printtriangle(5);
}
}
Output:

        *       
       * *
      * * *
     * * * *
    * * * * *

9. Write a java program to the print stars pattern and print the number patterns in reverse order?

input row = 5
package in.blogspot.scholars.java;

import java.io.IOException;

public class StarTringleExample {

public static void starsreversenum(int rows) throws NumberFormatException, IOException {

int i, j, a = 1;

for (i = 1; i = rows; i++)
{
a = ((i * (i + 1)) + 1) / 2;
for (j = 1; j = i; j++)
{
System.out.print((a--) + "*");
}
System.out.println();
}
}
}
public static void main(String[] args) throws Exception {
// rows input
StarTringleExample.starsreversenum(5);
}
}
}
Output:
 
1*  
3*2*  
6*5*4*  
10*9*8*7*  
15*14*13*12*11*

10. Write a java program to check the given number Palindrome number or not? or palindrome example in java?

input = 23432
output = 23432
package in.blogspot.scholars.java;


public class PolindromeNumberStringExample {



public void polindromeNum(int num) {

int temp, check = 0, remain;


temp = num;

if (num == 0)

System.out.println("please enter the number bigger than zero");

else

while (num > 0) {

remain = num % 10;

// System.out.println("remain " + remain);

check = check * 10 + remain;

// System.out.println("check " + check);

num = num / 10;

// System.out.println("num " + num);

}

System.out.println(check);

if (check == temp) {

System.out.println("Given number " + temp + " is Palindrome");

} else {

System.out.println("Given number " + temp + " is Not Palindrome");

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

PolindromeNumberStringExample calling = new PolindromeNumberStringExample();

// input number

calling.polindromeNum(23432);

}

}
Output: 

Given number 23432 is Palindrome

11. Write a java program to check the given String Palindrome or not? or palindrome string example in java?

input = "Nitin"
package in.blogspot.scholars.java;


public class PolindromeNumberStringExample {


public void polindromeString(String input) {

String str = "";

int len = input.length();

if ((input == null) && (input.equals("")))

System.out.println("please enter the String value");

else

for (int i = len - 1; i >= 0; i--) {

str = str + input.charAt(i);

}

if (input.equalsIgnoreCase(str)) {

System.out.println("The string is palindrome =" + input);

} else {

System.out.println("The string is not palindrome." + input);

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

PolindromeNumberStringExample calling = new PolindromeNumberStringExample();

// input string

calling.polindromeString("Nitin");

}

}
Output:

The string is palindrome =Nitin

12. Write a java program to find the duplicate number element and duplicate number element count from Array?

input:
int[] arr ={ 4, 2, 4, 5, 2, 3, 1, 1 }
package in.blogspot.scholars.java;

public class DuplicateElementFromArrayExample {

public static void duplicateCount(int arr_size, int[] arr) {

int i, j;

int count = 0;

System.out.println("Repeated/Duplicate Integer elements are :");

for (i = 0; i < arr_size; i++)
{
for (j = i + 1; j < arr_size; j++)
{
if (arr[i] == arr[j])
{
count++;
System.out.print(arr[j] + " ");
}
}
}
System.out.println("\n No. of duplicates Integer element COUNT :" + count);
}
public static void main(String[] args)
{
int arr[] = { 4, 2, 4, 5, 2, 3, 1, 1 };
int arr_size = arr.length;
duplicateCount(arr_size, arr);
}
}
Output:

Repeated/Duplicate Integer elements are :
4 2 1
No. of duplicates Integer element COUNT :3

13. Write a java program to find the duplicate string element and duplicate string element count from Array?

input: 
String[] str = { "abc", "adc", "aMc", "aec", "adc", "abc" }
package in.blogspot.scholars.java;

public class DuplicateElementFromArrayExample {

public static void strCount(int Str_len, String[] str) {

int i, j;

int count = 0;

System.out.println("Repeated/Duplicate String elements are :");

for (i = 0; i < Str_len; i++)
{
for (j = i + 1; j < Str_len; j++)
{
if (str[i] == str[j])
{
count++;
System.out.print(str[i] + " ");
}
}
}
System.out.println("\n No. of duplicates String element COUNT :" + count);
}
public static void main(String[] args)
{
String[] str = { "abc", "adc", "aMc", "aec", "adc", "abc" };
int Str_len = str.length;
strCount(Str_len, str);
}
}
Output:

Repeated/Duplicate String elements are :
abc adc
No. of duplicates String element COUNT :2

14. Write a java program to find the prime number? or prime number example in java?

input: 4
package in.blogspot.scholars.java;

public class PrimeNoExample {

public static void main(String[] args) {


// prime no greater than 1 and divisible by itself

int inputnum = 4, flag = 0;

int m = inputnum / 2;

if (inputnum == 0 ||inputnum == 1) {

System.out.println(inputnum + "= not prime no.");


} else {


for (int i = 2; i <= m; i++)
{
if (inputnum % i == 0)
{
System.out.println(inputnum + "= not prime no.");
flag = 1;
break;
}
}
}
if (flag == 0)
{
System.out.println(inputnum + " is prime no.");
}
}
}
Output:

4 is not prime no.

15. Fibonacci Series in java? or Fibbonaci series example in java?

input : 10
package in.blogspot.scholars.java;

public class FibbonaciSeriesExamplescalling {

public void fibonacci() {

/*
* series of numbers in which each number ( Fibonacci number ) is the sum of the
* two preceding numbers.
*
*
*
* The simplest is the series 1, 1, 2, 3, 5, 8, etc
*
*
*
*/

int input = 10, s1 = 0, s2 = 1, s3 = 0;

System.out.print(s1 + "," + s2);

for (int i = 0; i < input; i++)
{
s3 = s1 + s2;
System.out.print("," + s3);
s1 = s2;
s2 = s3;
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
FibbonaciSeriesExamplescalling = new FibbonaciSeriesExample();
calling.fibonacci();
}
}
Output:

0,1,1,2,3,5,8,13,21,34,55,89

Friday, August 2, 2019

Learn Spring boot tutorial | Spring boot Introduction

spring boot, spring boot tutorialsIn spring boot tutorial, provides the details of the spring boot introduction, advantages of spring boot, spring boot examples, spring boot dependency and spring MVC application using spring boot example.

Spring boot Introduction

Spring-boot is a  module of spring framework provided by spring.io guys. Basically, spring boot is an open-source Java framework used to create the spring applications and microservices Spring-boot provides the core to the advanced concept to developed spring environment applications and projects.  Spring-boot  "just run" the spring web-based application as a standalone application.

Why We Used Spring boot?

When we create a spring MVC application without spring boot, in that No. of configuration metadata files, setup the server, create folder structure/project architecture, if small changes needed then required the un-deployments and deployments, data access configuration, etc.

When we create spring MVC application with spring boot, that minimizes the development time and maintenance, eliminating the lots of configuration files and server setup with the help of the application.properties, No need for deployment and redeployment using Devtools, etc

Advantages of Spring boot

  1. No need to set up the server, spring boot contains inbuilt apache tomcat and jetty servers.
  2. Just run your web-based spring application as a standalone or java application.
  3. It provides the inbuilt derby database to perform the data access layer.
  4. It minimizes the lots of setup and configuration files with the help of an application. properties
  5. We can easily implement microservices using spring boot.
  6. It reduced the code size, development times, maintenance of application and increased code reusability.
  7. Spring boot Actuator dependency, it is a tool to manage the production environment HTTP endpoint. 
  8. Spring boot Devtools dependency, its help and eliminate the deployment process on the server. (Changes any code then no need to undeployment and deployment).