Showing posts with label best java blog. Show all posts
Showing posts with label best java blog. Show all posts

June 21, 2022

How to use function interface in your application | simple example for lamba expression | Interview questions

Created a simple functional Interface

/**
 * @author Stock market swing trad
 *
 */
@functionInterface
public interface InitialStatus {
public String set();

}


Implementing the function Interface


    InitialValue soldCountInitialValue = () -> Long.valueOf(0);
    InitialValue quantityInitialValue = () -> Long.valueOf(0);
    InitialValue taxInitialValue = () -> Long.valueOf(5);
    InitialValue ratingInitialValue = () -> Long.valueOf(1);
    InitialValue ratingInitialCount = () -> Long.valueOf(1);


Using the variables

itemObj.setSoldCount(soldCountInitialValue.set());

May 14, 2022

Stock trading application source code | java code | how to get stock value of share through java code | yahoo finance

/**
 * 
 */
package com.proximotech.nyseticker.service;

import java.io.IOException;
import java.math.BigDecimal;

import org.springframework.stereotype.Service;

import com.proximotech.nyseticker.model.StockWrapper;

/**
 * @author apple
 *
 */
@Service
public class StockService {

public StockWrapper findStock(final String ticker) {
try {
return new StockWrapper(yahoofinance.YahooFinance.get(ticker));
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public BigDecimal findPrice(final StockWrapper stock) throws IOException {
return stock.getStock().getQuote(true).getPrice();
}
}


Download application from git

https://javabelazy.blogspot.com/p/office.html

November 28, 2021

English to malayalam translation java code

Hi Team

English to Malayalam translation java code is available in GitHub


The translation is not 100% accurate , but the logic remains the same.you can modify the code accordingly, you can even raise the bug in the git itself. The translation will not take any time, performance is high, developed using plain java code.


https://github.com/consumerfed

Please comment and revisit the blog

October 19, 2017

Java Real Time currency convertor

import java.io.IOException;



/**
 *
 */

/**
 * @author belazy
 *
 */
public class CurrencyConvertor {

   public float convert(String currencyFrom, String currencyTo) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://quote.yahoo.com/d/quotes.csv?s=" + currencyFrom + currencyTo + "=X&f=l1&e=.csv");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpGet, responseHandler);
        httpclient.getConnectionManager().shutdown();
        return Float.parseFloat(responseBody);
    }

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

CurrencyConvertor cc = new CurrencyConvertor();
try {
            float current = cc.convert("USD", "AED");
            System.out.println(current);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

}

}

May 14, 2017

Java Technical Question in bayt.com

Ross is an event organizer. He has received data regarding the participation of employees in two different events ( say event One and event Two ). Some employees have participated in only one event and others have participated in both events. Ross now needs to count the number of employees who have taken part in both events. The record received by Ross consist of employee ids, which are unique. Write a program that accepts the employee ids participating in each event ( the first line relates to the first event and the second line relates to the second event). The program should print the number of common employee ids in both the events.

Suppose the following input is given to the program, where each line represents a different event.

1001,1002,1003,1004,1005
1106,1008,1005,1003,1016,1017,1112

Now the common employee ids are 1003 and 1005 so the program should give the output as:2

java source code

import java.util.ArrayList;
import java.util.List;

/**
 * solutions for question one
 */

/**
 * @author shimjith consumerfed
 *
 */
public class EventOrganizer {

private List<Integer> eventOne = null;
private List<Integer> eventTwo = null;
private static int count = 0;

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EventOrganizer main = new EventOrganizer();
main.getEmployeeDetails();
main.showEmployeeDetails();
main.findEmployeeDetails();
System.out.println("The employee present in both events :"+EventOrganizer.count);

}

// to get employees present in both arrays
private void findEmployeeDetails() {
// TODO Auto-generated method stub
for (int row: eventOne){

if(eventTwo.contains(row)){
count = count +1;
}
}

}

private void showEmployeeDetails() {
// TODO Auto-generated method stub
System.out.println("Employee ids of event one "+eventOne);
System.out.println("Employee ids of event two "+eventTwo);
}

private void getEmployeeDetails() {
// You can use scanner class to get values to event one and two
eventOne = new ArrayList<Integer>();
eventTwo = new ArrayList<Integer>();
eventOne.add(1001);
eventOne.add(1002);
eventOne.add(1003);
eventOne.add(1004);
eventOne.add(1005);
eventTwo.add(1106);
eventTwo.add(1008);
eventTwo.add(1005);
eventTwo.add(1003);
eventTwo.add(1016);;
eventTwo.add(1017);
eventTwo.add(1112);

}

}


out put

December 18, 2013

To check whether a number is prime or not in java

How to find Prime Number in java

How to determine a prime number in java :This program will check whether the given input is either prime number or not. it will return true or false.
copy and paste the code to notepad. compile it with javac and run it...

Instead of bufferedStream class you can use scanner class.  The logic i used is divide the given number from 2 to half of the number. if any one is divisible i stopped the loop and concluded it as not prime. if it successfully passed through all loop with out a division, then its a prime


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Ramanujan s number 1729
 */

/**
 * @author Proximotech Java lazy
 *
 */


public class PrimeOrNot {

    /**
     * @param lazy java
     */
      static int i,num,flag=0;
   
    public static void main(String[] vadassery) {
        // TODO Auto-generated method stub
   
        System.out.println("enter the integer no:");
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       try {
         num=Integer.parseInt(br.readLine());
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       for(i=2;i<num/2;i++){
           if(num%2==0)
           {
               flag=1;break;
           }
       }
       if(flag==1)
           System.out.println("The given number is a prime number");
       else
           System.out.println("The above number is not a prime number"); 
    }

}

write a program in java to check the given number is prime or not


Checking the program with ramanujans number 1729 (smallest prime number which can be expressed as the sum of the cubes of two numbers in two ways )

out put : The given number is prime

Remember the smallest prime number is 2

To print all prime number in java


Alternative method to check a number is prime or not


public class JavaPrimeNumberCheck {
    public boolean isPrimeNumber(int number){
         
        for(int i=2; i<=number/2; i++){
            if(number % i == 0){
                return false;
            }
        }
        return true;
    }
     
    public static void main(String a[]){
        JavaPrimeNumberCheck pc = new JavaPrimeNumberCheck();
        System.out.println("Is 17 prime number? "+pc.isPrimeNumber(17));
        System.out.println("Is 19 prime number? "+pc.isPrimeNumber(19));
        System.out.println("Is 15 prime number? "+pc.isPrimeNumber(15));
    }
}

 Number to word convertor in java



public
class Test {
public static void main(String[] args) {
String []a = {"","one","two","three","four","five"};
String []b = {"","ten","twenty","thirty","fourty"};
int number = 432;
int i = number;
int d = i/100;
int r = i%100;
int t = r/10;
int tr = r% 10;
System.out.println(a[d]+" Hundered and "+b[t]+" "+a[tr]);
}
}



Are you looking for prime factor in java click here

http://belazy.blog.com/

December 13, 2013

Method Overriding example in java


This is a small example for overriding in java.


Method Overriding : Implementation in sub class with same parameters and type signature Overrides the implementation in super class. Call of overriding is resolved through dynamic binding by JVM. JVM only deals with overriding.


Base class


public class Base {
   
    public void area()
    {
        System.out.println(" area inside base class ");
    }

}

October 15, 2013

Sending screenshot from client to Server through socket in java


How to send screen shot from client to server automatically in java

Did you ever think of getting screen shot from all computers in a network to a server. This code will helps you to do so....This code will capture the current desktop screen shot and sent it to server computer. This application is very useful to network administrator to track what other are doing in the computer at your organization.

ClientApp.java : is a client program that takes screen shot in regular interval.  The sendScreen function will help you to know how java program takes screen shot at intervals and sends to server machine. Here i used ImageIO class to create image buffer. There are other options too... The file is sent through a socket. the port number i used here is 1729. Server Name here used is loop back ip, where you need to specify the server computer name or ip  address.

On the Other hand
SeverApp.java will always listen to the port 1729. if any request comes there, it will catch request and save to the folder 


ClientApp.java


import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


import javax.imageio.ImageIO;


/**
 * @author lou reed
 *
 */
public class ClientApp implements Runnable {

    private static long nextTime = 0;
    private static ClientApp clientApp = null;
    private String serverName = "127.0.0.1"; //loop back ip
    private int portNo = 1729;
    //private Socket serverSocket = null;
   
    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        clientApp = new ClientApp();
        clientApp.getNextFreq();
        Thread thread = new Thread(clientApp);
        thread.start();
    }

    private void getNextFreq() {
        long currentTime = System.currentTimeMillis();
        Random random = new Random();
        long value = random.nextInt(180000); //1800000
        nextTime = currentTime + value;
        //return currentTime+value;
    }

    @Override
    public void run() {
        while(true){
            if(nextTime < System.currentTimeMillis()){
                System.out.println(" get screen shot ");
                try {
                    clientApp.sendScreen();
                    clientApp.getNextFreq();
                } catch (AWTException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch(Exception e){
                    e.printStackTrace();
                }
               
            }
            //System.out.println(" statrted ....");
        }
       
    }

    private void sendScreen()throws AWTException, IOException {
           Socket serverSocket = new Socket(serverName, portNo);
             Toolkit toolkit = Toolkit.getDefaultToolkit();
             Dimension dimensions = toolkit.getScreenSize();
                 Robot robot = new Robot();  // Robot class
                 BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
                 ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
                 serverSocket.close();
    }
}




Facebook comments