Square CSS

Showing posts with label play java. Show all posts
Showing posts with label play java. Show all posts

Monday, May 25, 2020

Supplier : Functional Interface Java 8

Introduction


In this tutorial we will look at the use of Supplier a functional interface introduced in java 8.

Refer The video Tutorial for detail


 

Use Case 


Supplier is a functional interface which is used to return data without accepting anything as parameter.The sample code is shown below.




    //this accepts an argument & return a result. Supplier<String> supplier=new Supplier<String>() { @Override public String get() { return "Data from supplier functional interface "; } };


The above case Supplier will not receive anything but return the result. The function is returning a String.


Conclusion 


In this tutorial we saw the use case of functional interface - Supplier. which is introduced in java 8 to act as supplier without receiving any parameter. 

Function : Functional Interface Java 8

Introduction


In this tutorial we will look at the use of Function a functional interface introduced in java 8.

Refer The video Tutorial for detail


 

Use Case 


Function is a functional interface which accepts one argument and returns another.The sample code is shown below.


    //this interface accepts one argument and return one result. Function<Integer,String> function=new Function<Integer,String>() { @Override public String apply(Integer t) { return "The data is: "+t; } }


The above case Function will receive one argument and return one result. The function is receiving Integer t and returning a String.

Conclusion 


In this tutorial we saw the use case of functional interface - Function. which is introduced in java 8 as request response perimeter.

Consumer : Functional Interface Java 8

Introduction


In this tutorial we will look at the use of Consumer a functional interface introduced in java 8.

Refer The video Tutorial for detail


 

Use Case 


Consumer is a functional interface which is used to modify value based on some data.The sample code is shown below.



    //return type is void Consumer<Integer> consumer=new Consumer<Integer>() { @Override public void accept(Integer i) { System.out.println("Nothing is returned in case of consumer"); } }


The above case will not return anything it will just consume some data to process it.

Conclusion 


In this tutorial we saw the use case of functional interface - Consumer. which is introduced in java 8 to modify data by consuming it in response.

Java 8 : Default Method In Interface

Introduction


Java 8 comes with use of default method in an interface. Multiple Interfaces can have the same default method.

Refer The Video For More Detail




Uses of Default Method


We can create a method with default keyword and the method will be referred from the interface.


  public interface DefaultInterface{
public default void getDefault() {
        //Custom Code
      }
  }


In case if two interface have same default method then at the time of compilation only the editor will ask for the implementation of default method. 



  public interface DefaultInterface1 {
public default void getDefault() {
               System.out.println("Default Interface1");
       }
  }


public interface DefaultInterface2 {
public default void getDefault() {
                System.out.println("Default Interface2");

       }
  }


When a class implements the above two interface then the user needs to override the default method of either of the interface. This will remove the diamond problem which occurs in multiple inheritance.



  public class ImplementInterfaceWithDefaultMethod
implements DefaultInterface1,DefaultInterface2{

    @Override
   public void getDefault() {
DefaultInterface1.super.getDefault();
        
   }


Conclusion


The default method can be created inside the interface since Java 8. It can be used by calling the Interface with its default method using super keyword.


@EnableCaching : Maintain Cache In Spring


Introduction : 

We can enable cache in spring by the use of @EnableCaching and @Cachable.


Refer Video Tutorial For Detail :




@EnableCaching


The annotation @EnableCaching should be used on the class level to configure the class for enabling cache. This annotation should be used to make it configurable for cache maintenance.



  @EnableCaching //provided annotation on class level
  public class CachingDemo{
         //Custom Code
  }


@Cachable

The annotation @Cachable should be used above the methods which needs to maintain cache.
Once the request is complete the response is stored in cache for same request coming in future.
The response is mapped to the key for further requests. 


@Cacheable("userInfo") //provided cacheable annotation along with userInfo as key
public String checkCache() { //Custom Code }


Conclusion


Major annotation to be used for caching in spring is @EnableCaching and @Cachable. The key should be provide where the cached is used so that the cache data should be mapped to the key.

Tuesday, January 22, 2019

Hibernate Tutorial : Introduction

Hibernate is an open source lightweight, Object Relational Mapping framework to interact Java classes with databases. It implements the specifications of JPA as a persistence layer.

Benefits 


Following are the benefits of using hibernate:

  • It is a lightweight framework which increases the efficiency of a project.
  • It helps in the interaction of java model class with the table of a database.
  • It maintains the first-level cache thus increasing the efficiency.
  • It implements the specifications of JPA thus helps to avoid the use of database-specific language.
  • It helps in writing queries both in native and hibernate query language.

Object Relational Mapping


Object Relational Mapping is a technique through which an object can interact with the database. 
The java code creates an object and the fields of this object get mapped with the column of the table in the database.


The different field of an object will be mapped with the different columns of a table. Internally this process is achieved with the help of JDBC (Java Database Connectivity).

Conclusion


In this tutorial, information is provided about the overview of Hibernate. In the next tutorial, the setup regarding hibernate will be elaborated.



 ☛ Next >> Hibernate Tutorial: Setting Up Environment

                    This series of tutorials is for Hibernate. The tutorial will cover ... 


Monday, January 21, 2019

Hibernate Tutorial: Setting Up Environment

This series of tutorials is for Hibernate. The tutorial will cover from setting up Hibernate to fetching the details from the database using criteria. This series of tutorials will provide in-depth knowledge of Hibernate Framework with examples associated with them.





Introduction


Hibernate is an open source ORM (Object Relational Mapping) framework which provides database connectivity for JAVA. It maps Java POJO (Plain Old Java Object) or model classes to the database tables and performs most of the database persistence tasks.


Setting Up Environment


Prerequisites

One should have little knowledge of Hibernate, Eclipse, and Maven(how the dependencies are created using pom.xml).

Setup

In this setup, the project is created using Maven, using Eclipse as IDE.Go to New > Maven Project then click on Next.





Click on the option to Create a simple project and click on Next.


Provide the Group id, Artifact id, Name, and Description then click on Finish.


Now provide the following dependencies in the pom.xml file.






<dependencies>
     
      <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>            
             <version>5.1.15</version>
       </dependency>

       <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.3.Final</version>
      </dependency>

      <dependency>
           <groupId>javassist</groupId>
           <artifactId>javassist</artifactId>
           <version>3.12.1.GA</version>
      </dependency>

      <dependency>
           <groupId>ch.qos.logback</groupId>
           <artifactId>logback-core</artifactId>
           <version>0.9.28</version>
      </dependency>

      <dependency>
           <groupId>ch.qos.logback</groupId>
           <artifactId>logback-classic</artifactId>
           <version>0.9.28</version>
           <scope>test</scope>
      </dependency>

       <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
        </dependency>

</dependencies>







Go to src/main/resources and create a hibernate.cfg.xml file.
Here ".cfg" depicts that the file is a configuration file for hibernate.
Inside this file provide the following data for hibernate configuration.






<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">   
<hibernate-configuration>

       <session-factory>
   
               <property name = "hibernate.dialect">
                             org.hibernate.dialect.MySQLDialect
               </property>
               <property name = "hibernate.connection.driver_class">             
                             com.mysql.jdbc.Driver
               </property>
               <property name = "hibernate.connection.url">
                             jdbc:mysql://localhost:3306/playjava
               </property>
               <property name = "hibernate.connection.username">
                             root
               </property>
               <property name = "hibernate.connection.password">
                             playjava
               </property>
               <property name="hibernate.show_sql">
                             true
               </property>
               <property name="hbm2ddl.auto">
                            update
               </property>

               <mapping class="com.sumit.playjava.Demo"/>

    </session-factory>

</hibernate-configuration>



When the POJO is required to be mapped to the database using hibernate then the file name should be provided in the mapping class. As an example in the configuration file, Demo.java file is created in the package com.sumit.playjava at path src/main/java.
The class file should be annotated with @Entity to consider hibernate as the mapping file.

Conclusion


This is about the setting up of hibernate environment. In the next post tutorial will be about setting data in the database.

Friday, December 14, 2018

N Queen Problem : Using Backtracking

N Queen problem is one of the common interview questions which is asked in many popular companies. This problem is solved using backtracking.

Problem Statement:


We are given N x N chessboard and N queens. The queens should be placed in such a way that no two queens should lie in the same column, the same row and the same diagonal.

Algorithm:


 

1. Start from leftmost part ;

2. If got the solution return true;

3. Check for the queen to be placed in the current column. If placed in the current column then

    check recursively for the solution and mark row of the current column with "Q".

4. If at any point during recursion solution comes out to be wrong then backtrack and unmark

    the marked places.

5. Return false if no solution is found else print the solution.


     

Solution:



Refer the video tutorial:



Saturday, December 1, 2018

Create Tetris Game Using Java

Application Coding and Game Creation:

Nowadays top companies are looking for talented people who are well in the data structure and application coding. To check application coding the companies may ask to create sample games within a given time frame on their system. So sometimes it becomes useful to have basic ideas of game creation.

Tetris Game:

In this tutorial, a basic game is created using Java. The name of the game is Tetris.
This is the same game which also used to come in the game plays which were quite handy.



Sample code:


The sample code is provided for reference.


  import java.awt.Color;
  import java.awt.Graphics;
  import java.awt.Point;
  import java.awt.event.KeyEvent;
  import java.awt.event.KeyListener;
  import java.util.ArrayList;
  import java.util.Collections;

  import javax.swing.JFrame;
  import javax.swing.JPanel;

  public class MyGame extends JPanel {

public static void main(String[] args) {
JFrame f = new JFrame("MyGame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(12*26+10, 26*23+25);
f.setVisible(true);


final MyGame game = new MyGame();
game.init();
f.add(game);

f.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}

public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
game.rotate(-1);
break;
case KeyEvent.VK_DOWN:
game.rotate(+1);
break;
case KeyEvent.VK_LEFT:
game.move(-1);
break;
case KeyEvent.VK_RIGHT:
game.move(+1);
break;
case KeyEvent.VK_SPACE:
game.dropDown();
game.score += 1;
break;
}
}

public void keyReleased(KeyEvent e) {
}
});
new Thread() {
@Override public void run() {
while (true) {
try {
Thread.sleep(1000);
game.dropDown();
} catch ( InterruptedException e ) {}
}
}
}.start();
}

private final Point[][][] MyShapes = {
// I-Piece
{
{ new Point(0, 1), new Point(1, 1), new Point(2, 1), new Point(3, 1) },
{ new Point(1, 0), new Point(1, 1), new Point(1, 2), new Point(1, 3) },
{ new Point(0, 1), new Point(1, 1), new Point(2, 1), new Point(3, 1) },
{ new Point(1, 0), new Point(1, 1), new Point(1, 2), new Point(1, 3) }
},

// J-Piece
{
{ new Point(0, 1), new Point(1, 1), new Point(2, 1), new Point(2, 0) },
{ new Point(1, 0), new Point(1, 1), new Point(1, 2), new Point(2, 2) },
{ new Point(0, 1), new Point(1, 1), new Point(2, 1), new Point(0, 2) },
{ new Point(1, 0), new Point(1, 1), new Point(1, 2), new Point(0, 0) }
},

// L-Piece
{
{ new Point(0, 1), new Point(1, 1), new Point(2, 1), new Point(2, 2) },
{ new Point(1, 0), new Point(1, 1), new Point(1, 2), new Point(0, 2) },
{ new Point(0, 1), new Point(1, 1), new Point(2, 1), new Point(0, 0) },
{ new Point(1, 0), new Point(1, 1), new Point(1, 2), new Point(2, 0) }
},

// O-Piece
{
{ new Point(0, 0), new Point(0, 1), new Point(1, 0), new Point(1, 1) },
{ new Point(0, 0), new Point(0, 1), new Point(1, 0), new Point(1, 1) },
{ new Point(0, 0), new Point(0, 1), new Point(1, 0), new Point(1, 1) },
{ new Point(0, 0), new Point(0, 1), new Point(1, 0), new Point(1, 1) }
}
};

private final Color[] MyColors = {
Color.cyan, Color.MAGENTA, Color.orange, Color.yellow, Color.black, Color.pink,
               Color.red };

private Point pt;
private int currentPiece;
private int rotation;
private ArrayList<Integer> nextPieces = new ArrayList<Integer>();

private long score;
private Color[][] well;

private void init() {
well = new Color[12][24];
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 23; j++) {
if (i == 0 || i == 11 || j == 22) {
well[i][j] = Color.PINK;
} else {
well[i][j] = Color.black;
}
}
}
newPiece();
}
public void newPiece() {
pt = new Point(5, 2);
rotation = 0;
if (nextPieces.isEmpty()) {
Collections.addAll(nextPieces, 0, 1, 2, 3);
Collections.shuffle(nextPieces);
}
currentPiece = nextPieces.get(0);
nextPieces.remove(0);
}

private boolean collidesAt(int x, int y, int rotation) {
for (Point p : MyShapes[currentPiece][rotation]) {
if (well[p.x + x][p.y + y] != Color.black) {
return true;
}
}
return false;
}

public void rotate(int i) {
int newRotation = (rotation + i) % 4;
if (newRotation < 0) {
newRotation = 3;
}
if (!collidesAt(pt.x, pt.y, newRotation)) {
rotation = newRotation;
}
repaint();
}

public void move(int i) {
if (!collidesAt(pt.x + i, pt.y, rotation)) {
pt.x += i;
}
repaint();
}

public void dropDown() {
if (!collidesAt(pt.x, pt.y + 1, rotation)) {
pt.y += 1;
} else {
fixToWell();
}
repaint();
}
public void fixToWell() {
for (Point p : MyShapes[currentPiece][rotation]) {
well[pt.x + p.x][pt.y + p.y] = MyColors[currentPiece];
}
clearRows();
newPiece();
}

public void deleteRow(int row) {
for (int j = row-1; j > 0; j--) {
for (int i = 1; i < 11; i++) {
well[i][j+1] = well[i][j];
}
}
}

public void clearRows() {
boolean gap;
int numClears = 0;
for (int j = 21; j > 0; j--) {
gap = false;
for (int i = 1; i < 11; i++) {
if (well[i][j] == Color.black) {
gap = true;
break;
}
}
if (!gap) {
deleteRow(j);
j += 1;
numClears += 1;
}
}
switch (numClears) {
case 1: score += 100;break;
case 2: score += 300;break;
case 3: score += 500;break;
case 4: score += 800;break;
}
}
private void drawPiece(Graphics g) {
g.setColor(MyColors[currentPiece]);
for (Point p : MyShapes[currentPiece][rotation]) {
g.fillRect((p.x + pt.x) * 26,
   (p.y + pt.y) * 26,
   25, 25);
}
}

@Override
public void paintComponent(Graphics g)
{
g.fillRect(0, 0, 26*12, 26*23);
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 23; j++) {
g.setColor(well[i][j]);
g.fillRect(26*i, 26*j, 25, 25);
}
}
g.setColor(Color.WHITE);
g.drawString("Score : " + score, 19*12, 25);

drawPiece(g);
}
  }

The game will start as soon as the java application will be started.

Refer the video tutorial.




 ☛ Next >> Algorithm: Tower of Hanoi

                    Tower of Hanoi consists of three towers called as pegs with n number of ... 

Some Algorithms

Algorithm: Tower of Hanoi

Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

Popular Posts