Thursday 9 November 2023

How to implement Quick Sort Alogrithm in Java

The quick sort partitions an array and then calls itself recursively twice to sort the resulting two subarray. This algorithm is quite efficient for large sized data sets as its average and worst case complexity are of O(nlogn) where n are no. of items


package in.jk.sort;

public class QuickSortApplication {

public int[] numbers = { 5, 1, 8, 3, 6, 7, 9, 4, 2, 10 };

public int partition(int left, int right) {

int pivot = numbers[right];
int leftPointer = left - 1;

for (int i = left; i <= right - 1; i++) {

if (numbers[i] < pivot) {
leftPointer++;
swap(leftPointer, i);
}
}

int leftPointerIncriment = leftPointer + 1;
swap(leftPointerIncriment, right);
return leftPointerIncriment;

}

public void quickSort(int left, int right) {

if (left < right) {
int parttion = this.partition(left, right);
quickSort(left, parttion - 1);
quickSort(parttion + 1, right);
}
}

public void swap(int left, int right) {

int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
}

public static void main(String[] args) {

QuickSortApplication quickSortApplication = null;
                quickSortApplication =QuickSortApplication ();
int left = 0;
int right = quickSortApplication .numbers.length - 1;
quickSortApplication .quickSort(left, right);

System.out.println("Sorted Array :: ");
for (int element : quickSortApplication .numbers) {
System.out.print(element + " ");
}
}
}


Output :

Sorted Array :: 
1 2 3 4 5 6 7 8 9 10 

Monday 28 June 2021

How to create Spring MVC Application with Springboot


Springboot MVC Application :

In Springboot MVC application employee form accept the employee details forward to 
employee details page where display employee details with two static resource image file .
Following files are required for creating Spring boot MVC application .

Directory Structure of Springboot MVC Application 







EmployeeController.java

package in.jk.Springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import in.jk.Springboot.request.EmployeeRequest;

@Controller
public class EmployeeController {
@RequestMapping("/employee")
public ModelAndView employee() {
System.out.println("Employee Controller ");
ModelAndView modelAndView = new ModelAndView("employee","command",new EmployeeRequest());
return modelAndView;
}
@RequestMapping("/employeeDetails")
public ModelAndView employeeDetails(@ModelAttribute("employeeRequest")EmployeeRequest employeeRequest ) {
ModelAndView modelAndView = new ModelAndView("employeeDetails","command",employeeRequest);
return modelAndView;
}

}

EmployeeRequest.java

public class EmployeeRequest {
private String name;
private String company;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "EmployeeRequest [name=" + name + ", company=" + company + ", address=" + address + "]";
}


SpringbootMVCConfiguration.java

package in.jk.Springboot.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class SpringbootMVCConfiguration implements WebMvcConfigurer {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ResourceHandlerRegistration resourceRegistration = registry
            .addResourceHandler("resources/**");
        resourceRegistration.addResourceLocations("/resources/**");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/**");
         registry.addResourceHandler("/images/**").addResourceLocations("/images/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/**");
       

       
    }
     
   

}

SpringbootApplication .java

package in.jk.Springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@SpringBootApplication
@EnableWebMvc
@Configuration
public class SpringbootApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
System.out.println("Springboot Application Started :: ");
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}


}

employee.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Johny</title>
</head>
<body>

<h2>Enter Employee Details</h2>

<form:form method="POST" action="employeeDetails">
<table>
<tr>
<td><form:label path="name">Enter Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="company">Company</form:label></td>
<td><form:input path="company" /></td>
</tr>
<tr>
<td><form:label path="address">Address</form:label></td>
<td><form:input path="address" /></td>
</tr>

<tr>
<td colspan="2"><input type="submit" value="Login" /></td>
</tr>
</table>
</form:form>
</div>

</body>
</html>

employeedetails.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Details</title>
</head>
<body>

<div id="johnyDetails">

 <div id="image" style="font-size: 11px; margin-left: 34px">
 <img  src="images/Hailee.PNG" height="300" width="300"> 
 <img  src="images/Johny.jpg" height="300" width="300"> 
 
 </div>
 <br></br>
 
Employee Name    : ${employeeRequest.name} <br></br>
Employee company : ${employeeRequest.company}<br></br>
Employee Address : ${employeeRequest.address}

</body>
</html>


<?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 https://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.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>in.jk</groupId>
<artifactId>Springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.0.0.RELEASE</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

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

</project>


Employee Form










Employee Details 












Thursday 20 May 2021

How to Change Desktop background in Java using Java Native Access (JNA) Library



Java Native Access JNA

Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native .




HaileePhotoDesktopSetter.java 

package us.javaj.johny.hailee.desktop;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg;
import com.sun.jna.win32.StdCallLibrary;

public class HaileePhotoDesktopSetter {

public static void main(String[] args) {
HaileePhotoDesktopSetter.changeDesktopWallpaper();

}

private interface MyUser32 extends StdCallLibrary {

MyUser32 INSTANCE = (MyUser32) Native.loadLibrary("user32", MyUser32.class);

boolean SystemParametersInfoA(int uiAction, int uiParam, String fnm, int fWinIni);
}

public static void changeDesktopWallpaper() {

// -----------------------------------

String johny = "Johny Invoke the Desktop Background Setter with Love in Hailee Stienfeld ::";
System.out.println();
System.out.println("------------------------------Hailee Johny --------------------------------------");
System.out.println();
System.out.println(johny);
System.out.println();

String filePath = "E:\\Hailee-Johny\\Hailee_Stienfeld_Johny_S\\Desktop\\Hailee.jpg";
HaileePhotoDesktopSetter.setWallpaper(filePath);
System.out.println("Desktop Images Set Succussfully ");
System.out.println("Image File Path :: "+filePath);

}

public static void setWallpaper(String filePath) {

Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, 
                                              "Control Panel\\Desktop", "FitWallpaper",filePath);
// WallpaperStyle = 10 (Fill), 6 (Fit), 2 (Stretch), 0 (Tile), 0 (Center)
// For windows XP, change to 0
int SPI_SETDESKWALLPAPER = 0x14;
int SPIF_UPDATEINIFILE = 0x01;
int SPIF_SENDWININICHANGE = 0x02;
// User32.System
boolean result =                MyUser32.INSTANCE.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0,
        filePath,SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

}

}


Desktop Wallpaper before running above code 
















Desktop Wallpaper before running after code

Output in java console 
-------------------------------- Hailee Johny --------------------------------------

Johny Invoke the Desktop Background Setter with Love in Hailee Stienfeld ::

Desktop Images Set Succussfully 
Image File Path :: E:\Hailee-Johny\Hailee_Stienfeld_Johny_S\Desktop\Hailee.jpg 








Saturday 7 November 2020

How to call Kotlin code in Java Application: Java and Kotlin Interoperability


Java is fully compatible with Kotlin . So to call java code in kotlin first write following java and 
kotlin code two separate file .

KotlinApplication.kt

fun main(args:Array<String>){

println("Kotlin Application Started ..... ")

}

fun navigateToKotlinApplication(){

println("Welcome in Kotlin Application ..... ")

}

JavaApplication.java

public class JavaApplication {

  public static void main(String []args){

  System.out.println("Java Application Started ...... ");
  System.out.println("---------------------------------- ");
  System.out.println("Navigating to Kotlin Application ......");
  System.out.println("--------------------------------- ");

  KotlinApplicationKt.navigateToKotlinApplication();

  }
}

Commands to compile and run above two code 

1 . First Compile KotlinApplication.kt file 

     kotlinc KotlinApplication.kt

Note :-  After Compiling of KotlinApplication.kt  kotlinc compiler conventionally generate KotlinApplicationKt.class   by default  kotlinc compiler append Kt in suffix of kotlin file name.

2 .  Running KotlinApplicationKt.class file 

      kotlin KotlinApplicationKt

3 . Compiling Java code JavaApplication.java 

    javac JavaApplication.java

4 . Running Java Application
     
    java  JavaApplication


Output in Console.....





How to call Java code in Kotlin Application: Java and Kotlin Interoperability


Java is fully compatible with Kotlin . So to call java code in kotlin first write following java and kotlin code two separate file .

KotlinApplication.kt

fun main(args:Array<String>){
println("Kotlin Application Started ....... ");

var javaApplication = JavaApplication();

println("-------------------------------------------");
println("Navigating to Java Application  ....... ");
println("-------------------------------------------");

javaApplication.naivgateToJavaApplication();


}

JavaApplication.java

public class JavaApplication{

     public JavaApplication(){}

     public static void main(String []args){
    
     System.out.println("Java Application Started ..... ");
   
}

public void naivgateToJavaApplication(){

     System.out.println("Welcome in Java Application .......");

}

}


To Compile and run above two file there is two method . 

First Method to Compile and run java code in kotlin application 

Compile using kotlinc and Running using Kotlin


1 . Complie java file 
javac JavaApplication.java

2 .Running java file  
java JavaApplication

3.Compling kotlin file by setting class path of JavaApplication.class file 
kotlinc -cp . KotlinApplication.kt 

Note :-
After Compiling of KotlinApplication.kt  kotlinc compiler conventionally generate 
KotlinApplicationKt.class
by default  kotlinc compiler append Kt in suffix of kotlin file name. 


4. Now at last Runing KotlinApplicationKt.class by seting class path of JavaApplication.class file 
 kotlin -cp . KotlinApplicationKt

Output in Console ......























Second Method to Compile and run java code in kotlin application 

Complie and package into java jar using kotlinc and Runing  java jar using Java

Running with Java Jar using Java

1 .Compile java file 

javac JavaApplication.java

2 .Running java file 

java  JavaApplication

3.Compling kotlin file by setting class path of JavaApplication.class file 

kotlinc -cp . KotlinApplication.kt -include-runtime -d kotlinapplication.jar

4. Updating kotlinapplication.jar with JavaApplication.class file 

jar -uf KotlinApplication.jar JavaApplication.class

5. Running  KotlinApplication.jar file 

java -jar KotlinApplication.jar


Output in Console .....






First program to print Hello World message in Kotlin


Write following code in any text editor save the file .

Kotlin.kt

import java.time.LocalDateTime;

fun main (args : Array<String>){

val currentTime = LocalDateTime.now();

println("Hello Kotlin World ....")

println("Welcome in Kotlin World ...currtent Time is ::  $currentTime")

}


Command to compile code and package in jar

kotlinc Kotlin.kt -include-runtime -d Kotlin.jar

Command to run Kotlin.jar file

java -jar Kotlin.jar


Output Console .....


Hello Kotlin World ....
Welcome in Kotlin World ...currtent Time is ::  2020-10-21 T 12:31:21.879