Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

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

Wednesday, August 3, 2016

Java Facts

Just In Time (JIT) Compilation:

Java is designed as a interpreted language. Java code is converted into byte code and that is interpreted by JVM. As we know interpreted languages are slows compared to compiled language because compiled code is ore closer to machine architecture. But java seems to have no major issue with its performance because of the
  • Highly optimized byte code, and
  • JIT compilation
Some selected portion of java byte code is converted into machine code on the fly.

Final Method Increases Performance:

In Java we can define a method as final to avoid overriding. And when we do so there is a chance of performance increase. If the final method is short then java will not call the method instead it will copy the byte code of that particular routine at the place of its call. This technique is called inline calls in Java similar to inline function in C++ where we can explicitly define an inline function (although the final decision is made by compiler). For a final method call can be resolved in compiler time called early binding.


Saturday, July 23, 2016

Java 8 Features | Default Method For Interface

Default Method For Interface

There are some new features that are introduced into Java 8 and one of them is the default method

Interfaces in java are known to be fully abstract i.e. we can not define any method within an interface. But now in Java 8 we can define method inside an interface that is a default method.

It gives you a way to write default implementation for a method. Here is a example.

Code



interface SpeedStar {
    public String getName();

    public default void power() {
        System.out.println("I'm the fastest man alive!");
    }
}

class Flash implements SpeedStar {
    private String name;
    public Flash(String name) {
        this.name = name;
    }

    public String getName() {
        return "I'm " + name + ".";
    }
}

public class Demo
{
    public static void main(String[] arg) {
        Flash f = new Flash("Barry Allen");
        System.out.println(f.getName());
        f.power();
    }
}

Output

I'm super fast!
I'm Barry Allen.

Thursday, April 28, 2016

Java Chat Program Using TCP Socket | Java Networking

Java Chat Program

When we are developing a client/server model based application, first we need to make a decisions that whether the application is to run over TCP or over UDP.

TCP is connection-oriented and provides a reliable byte stream channel through which data flows between two end systems. UDP is connection-less and sends independent packets of data from one end system to the other, without any guarantees about delivery.


Client Side Code
import java.util.*;
import java.io.*;
import java.net.*;

public class ClientTCP 
{
    public static void main(String[] args) throws Exception {
        Socket s = new Socket("localhost", 30000);  
        DataInputStream dis = new DataInputStream(s.getInputStream());
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        String msg = "";
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.print("Client: ");
            msg = sc.nextLine();
            dos.writeUTF(msg);
            if (msg.equals("stop")) {
                break; 
            }
            msg = dis.readUTF();
            System.out.println("Server: " + msg);           
        }
        dis.close();
        dos.close();
        s.close();
    }
}
Server Side Code
import java.util.*;
import java.net.*;
import java.io.*;

public class ServerTCP
{
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(30000);
        Socket s = ss.accept(); 
        System.out.println("connection established...");
        DataInputStream dis = new DataInputStream(s.getInputStream());
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        String msg = "";
        Scanner sc = new Scanner(System.in);
        while(true) {
            msg = dis.readUTF();
            System.out.println("Client: " + msg);
            if (msg.equals("stop")) {
                break; 
            }
            System.out.print("Server: ");
            msg = sc.nextLine();
            dos.writeUTF(msg);         
        }
        dis.close();
        dos.close();
        s.close();
        ss.close();
    }
}

Output

Make sure to run the server program first and then the client program.

Wednesday, March 2, 2016

Calculator Application Using Java

Calculator Application Using Java AWT

Here is the java code for a simple calculator application that will look like this.

Code:

import java.awt.*;
import java.awt.event.*;

public class CalGUI implements ActionListener, KeyListener {

    String[] s =  {"", "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", "=", "+", "C"};
    Frame f;
    Button[] b = new Button[16];
    TextField text;
    int x = 35, y = 100;
    float res = 0.0f;   
    String msg = "";
    char op;

    public CalGUI() {
        f = new Frame("Calculator");
        f.setSize(400, 450);
        f.setResizable(false);
        f.setLayout(null);
        f.setBackground(Color.gray);
        text = new TextField(45);
        text.setFocusable(false);
        text.setBounds(25, 40, 350, 40);
        text.setEditable(false);
        text.setFont(new Font("Consolas",1,20));
        f.add(text);
        for (int i = 1; i < s.length; i++) {
            b[i-1] = new Button(s[i]);
            b[i-1].setFont(new Font("Consolas",1,20));
            b[i-1].setBackground(Color.LIGHT_GRAY);
            b[i-1].setBounds(x, y, 80, 80);
            x=x+80;
            if(i % 4 == 0 && i != 0) {y = y + 80; x = 35;}
            f.add(b[i-1]);
        }
        
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        
        for(int i = 0; i < b.length; i++) {
            b[i].addActionListener(this);
        }
        f.addKeyListener(this);
        
    }
    
    public void keyPressed(KeyEvent ke)
    {
        char ch = ke.getKeyChar();
        if (ch >= '0' && ch <= '9') {
            msg += ch;
            text.setText(msg);
        }
        else if(ch == '=') {
            switch(op) {
                case '+': 
                    res = res + Integer.parseInt(text.getText()); 
                    break;
                case '-':
                    res = res - Integer.parseInt(text.getText()); 
                    break;
                case '*':
                    res = res * Integer.parseInt(text.getText()); 
                    break;
                case '/':
                    res = res / (float)Integer.parseInt(text.getText()); 
                    break;
                    
            }
            text.setText("Ans. " + res);
            msg="";
        }
        else if(ch == 'C') {
            text.setText("");
            res = 0;
            msg ="";
        }
        else {
            res = Integer.parseInt(text.getText());
            text.setText("");
            msg = "";
            switch(ch) {
                case '+': op = '+'; break;
                case '*': op = '*'; break;
                case '/': op = '/'; break;
                case '-': op = '-'; break;
            }
        }
        
    }
    
    public void actionPerformed(ActionEvent e) {
        String str = e.getActionCommand();
        char ch = str.charAt(0);
        if (ch >= '0' && ch <= '9') {
            msg += str;
            text.setText(msg);
        }
        else if(ch == '=') {
            switch(op) {
                case '+': 
                    res = res + Integer.parseInt(text.getText()); 
                    break;
                case '-':
                    res = res - Integer.parseInt(text.getText()); 
                    break;
                case '*':
                    res = res * Integer.parseInt(text.getText()); 
                    break;
                case '/':
                    res = res / (float)Integer.parseInt(text.getText()); 
                    break;
                    
            }
            text.setText("Ans. " + res);
            msg="";
        }
        else if(ch == 'C') {
            text.setText("");
            res = 0;
            msg ="";
        }
        else {
            res = Integer.parseInt(text.getText());
            text.setText("");
            msg = "";
            switch(ch) {
                case '+': op = '+'; break;
                case '*': op = '*'; break;
                case '/': op = '/'; break;
                case '-': op = '-'; break;
            }
        }
    }
    
    public static void main(String[] arg) {
        new CalGUI();
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        char ch = arg0.getKeyChar();
        if (ch >= '0' && ch <= '9') {
            msg += ch;
            text.setText(msg);
        }
        else if(ch == '=') {
            switch(op) {
                case '+': 
                    res = res + Integer.parseInt(text.getText()); 
                    break;
                case '-':
                    res = res - Integer.parseInt(text.getText()); 
                    break;
                case '*':
                    res = res * Integer.parseInt(text.getText()); 
                    break;
                case '/':
                    res = res / (float)Integer.parseInt(text.getText()); 
                    break;
                    
            }
            text.setText("Ans. " + res);
            msg="";
        }
        else if(ch == 'C') {
            text.setText("");
            res = 0;
            msg ="";
        }
        else {
            res = Integer.parseInt(text.getText());
            text.setText("");
            msg = "";
            switch(ch) {
                case '+': op = '+'; break;
                case '*': op = '*'; break;
                case '/': op = '/'; break;
                case '-': op = '-'; break;
            }
        }
        
    }

    @Override
    public void keyReleased(KeyEvent arg0) {}
}