Printing Prime number in java

class PrimeNo{
    public static void main(String ar[]){
        int n=50;
        boolean isPrime=false;
        for(int i=3;i<=n;i++){
            for(int j=2;j<i;j++){
                if(i%j==0){ 
                    isPrime=false;
                    break;
                }
                else
                    isPrime=true;
            }
            if(isPrime)
                System.out.println(i+" is prime");
        }
    }
}
  

Pattern [* square ]


class Pattern2{
    public static void main(String ar[]){
        int n=20;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(i==1||i==n){
                    System.out.print(" *");
                }else if(j==1||j==n){
                    System.out.print(" *");
                }else{
                    System.out.print("  ");
                }
            }
            System.out.println("");
        }
    }
}
/*
 
 * * * * * * * * * * * * * * * * * * * * *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 *                                     *
 * * * * * * * * * * * * * * * * * * * *
 
 */

Pattern

class Pattern1{
    public static void main(String ar[]){
        char []chrs={'a','b','c','d','e','f','g','h','i','j','k','l','m'};
        for(int i=0;i<chrs.length;i++){
            for(int j=0;j<2*chrs.length;j++){
                if(j<=i||(2*chrs.length-j)<=i+1){
                    System.out.print(chrs[i]);
                }else{
                    System.out.print(" ");
                }
            }
            System.out.println("");
        }
    }
}

/* OUTPUT
a                        a
bb                      bb
ccc                    ccc
dddd                  dddd
eeeee                eeeee
ffffff              ffffff
ggggggg            ggggggg
hhhhhhhh          hhhhhhhh
iiiiiiiii        iiiiiiiii
jjjjjjjjjj      jjjjjjjjjj
kkkkkkkkkkk    kkkkkkkkkkk
llllllllllll  llllllllllll
mmmmmmmmmmmmmmmmmmmmmmmmmm

*/

GCD of two numbers

class Q1iPage139{
    static int a=20,b=30;
    public static void main(String ar[]){
        int x=test(6,18);
        System.out.println(x);
    }
    static int test(int a,int b){
        int gcd=0;
        int c=(a<b)?a:b;
        for(int i=1;i<=c;i++){
                if((a%i==0)&&(b%i==0)){
                    gcd=i;
                }
        }
        return gcd;
    }
}

Program to check palindrom of string

//Program to check palindrom of string
class Q4ipage154{
    public static void main(String ar[]){
        boolean b=pal("nitin");
        System.out.println(b);
    }
    static boolean pal(String s)
    {
        boolean p=true;
        int start=0,end=s.length()-1;
        while(start<end){
            if(!(s.charAt(start)==s.charAt(end))){
                p=false;
                break;
            }
            start++;
            end--;
        }
        return p;
    }
}

Pattern

class Q3apage246{
    public static void main(String ar[]){
        int n=4;
        int a[][]=new int [n][];
        int c=0;
        for(int i=0;i<n;i++){
            a[i]=new int[i+1];
            for(int j=0;j<n;j++){
                if(j<=i){
                    a[i][j]=c;
                    c++;
                }
            }
        }
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                    if(j<=i){
                     System.out.print(a[i][j]);
                    }
            }
            System.out.println("");
        }
    }
}

OUTPUT
0
12
345
6789

Fibnacci series (rec)

class Fib{
    static int fib(int a)
    {
        if (a==1||a==2)
            return 1;
        else{
            int n=fib(a-1)+fib(a-2);
            return n;
        }
        
    }
    public static void main(String ar[])throws Exception {
        int a=10,i;
        for(i=1;i<=a;i++)
        {
            System.out.printf("%5d",fib(i));
        }
    }
}

Single digit sum

/*189=9
* 1+8+9=18
* 1+8=9 (output)
*/

class Main{
static int rem=0,s=0;
static void sum(int num){
s=0;
while(num>0){
rem=num%10;
num=num/10;
s=s+rem;
}
if(s>=10){
sum(s);
}
}
public static void main(String ar[]){
int d=1891;
sum(d);
System.out.println("Single Digit sum ="+s);
}
}

Patterns

class Pattern{
 public static void main(String ar[]){
  int n=5;
  for(int i=0;i<n;i++){
   for(int j=1;j<=(2*n);j++){
    int start=n-i;
    int end=n+i;
    if((j>=start)&&(j<=(end))){
     System.out.print(i+1);
    }
    else{
     System.out.print(" ");
    }
   }
   System.out.println("");
  }
 }
}

Patterns

class Pattern{
 public static void main(String ar[]){
  int n=20;
  for(int i=0;i<n;i++){
   for(int j=1;j<=(2*n);j++){
    int start=n-i;
    int end=n+i;
    if((j>=start)&&(j<=(end))){
     System.out.printf("%2d",i+1);
    }
    else{
     System.out.printf("%2s"," ");
    }
   }
   System.out.println("");
  }
 }
}

Printing 2D array using recurrence method

class Pattern2DArray{
import java.io.*;
class Matrix{
 static int i=0,j=0;
 public static void main(String ar[])throws IOException{
  int a[][]={{1,2,3},{2,2,2},{1,2,3}}; 
  printArray(a);
 }
 public static void printArray(int arr[][]){
  if(i>arr.length-1)
  {
   return;
  }
  else
  {
   System.out.print(" "+arr[i][j]);
   
   if(i<arr.length && j==arr[i].length-1){
    i++;
    j=0;
    System.out.println();
    printArray(arr);
   }else{
    j++;
    printArray(arr);
   }
  }
 }
}

Printing array using recurrence method

import java.io.*;
class PrintArray{
 static int i=0,j=0;
 public static void main(String ar[])throws IOException{
  int a[]={23,23,23,5,45,4,65,6,34,7,56,7,88,78,7,5,45,6,4}; 
  printArray(a);
 }
 public static void printArray(int arr[]){
  if(i>arr.length-1)
  {
   return;
  }
  else
  {
   System.out.println(" "+arr[i]);
   i++;
   printArray(arr);
  }
 }
}

Matrix operations

import java.io.*;
class Matrix{
 public static void main(String ar[])throws IOException{
  int a[][]={{1,2,3},{2,2,2},{1,2,3}};
  int b[][]={{1,2,3},{2,2,2},{1,2,3}};
  int c[][]=new int[3][3];
  /*
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  System.out.println("First Array");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    System.out.println("Enter element of "+i+","+j);
    a[i][j]=Integer.parseInt(br.readLine());
   }
  }
  
  System.out.println("Second Array");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    System.out.println("Enter element of "+i+","+j);
    b[i][j]=Integer.parseInt(br.readLine());
   }
  }
  */
  //adding
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){  
    c[i][j]=a[i][j]+b[i][j];
   }
  }
  
  System.out.println("First Array");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    System.out.print(a[i][j]+" "); 
   }
   System.out.println("");
  }
  System.out.println("Second Array");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    System.out.print(b[i][j]+" "); 
   }
   System.out.println("");
  }
  System.out.println("Addition of Arrays");
  for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
    System.out.print(c[i][j]+" "); 
   }
   System.out.println("");
  }
 }
}

LCM

class LCM{
 public static void main(String ar[]){ 
  int a=8,b=12;
  double x=((a*b)/gcd(a,b));
  System.out.println("LCM  = "+x);
 }
 static int gcd(int a,int b)
 {
  if (a>=b&&a%b==0)
   return(b);
  else if(a<b)
   return(gcd(b,a));
  else
   return(gcd(b,a%b));
 }
}

GCD

GCD
class GCD{
 public static void main(String ar[]){
  int x=gcd(12,16);
  System.out.println("gcd = "+x);
 }
 
 static int gcd(int a,int b)
 {
  if (a>=b&&a%b==0)
   return(b);
  else if(a<b)
   return(gcd(b,a));
  else
   return(gcd(b,a%b));
 }
}

Program to represent complex numbers and adding them

class ComplexNumber {
 int r=0;
 int i=0;
 String c;
 ComplexNumber(int r,int i){
  this.r=r;
  this.i=i;
  if(i>=0)
   c=""+r+"+"+i+"i";
  else
   c=""+r+i+"i";
 }
 public String toString(){
  return c;
 }
 public ComplexNumber add(ComplexNumber c){
  int r=this.r+c.r;
  int i=this.i+c.i;
  return new ComplexNumber(r,i);
 }
}
class Complex{
 public static void main(String ar[]) {
  ComplexNumber c1=new ComplexNumber(2,3);
  ComplexNumber c2=new ComplexNumber(1,-2);
  ComplexNumber c3=c1.add(c2);
  System.out.println(c1);
  System.out.println(c2);
  System.out.println(c3);
 }
}

Client Server program in java

Java has many options to create distributed applications. One of them is Networking. java.net package provides platform to create distributed applications in easy way. Here, I am giving simple client server example to demonstrate java networking.
Server program :
package net;
import java.net.*;
import java.io.*;
class ServerDemo1{
public static void main(String ar[])throws Exception{
ServerSocket ss=new ServerSocket(1234);
Socket clientSocket=ss.accept();
InputStream in=clientSocket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
OutputStream out=clientSocket.getOutputStream();
while(true){
String m=br.readLine();
//if(m!=null && !(m.length()<1)){
System.out.println("Data Recieved From Client \n"+m);
//}
out.write(m.toUpperCase().getBytes());
out.write(13);
out.write(10);
out.flush();
}
}
}
Client Program :
package net;

import java.net.*;
import java.io.*;
public class ClientDemo1{
 public static void main(String ar[])throws Exception{
  Socket serverSocket=new Socket("localhost",1234);
  InputStream in=serverSocket.getInputStream();
  BufferedReader br=new BufferedReader(new InputStreamReader(in));
  OutputStream out=serverSocket.getOutputStream();
  Console c=System.console();
  while(true){
   String msg=c.readLine("Enter Message to Server and \"q\" to stop  \n");
   if(msg.equals("q"))break;
   out.write(msg.getBytes());
   out.write(13);
   out.write(10);
   String m=br.readLine();
   System.out.println(m);
   out.flush();
  }
  
 }
} 
Server program output 

 Client Program output

 

Submit data fields using java program.

In java networking you can fill the form program and send data fields to server. server will treat them as usual. Only you need to get URLConnection object from URL object and write data fields to OutputStream got through URLConnection Object.
Example :
package net;
import java.net.*;
import java.io.*;
//sending form data 
public class Net1{
 public static void main(String ar[])throws Exception{
  URL url=new URL("http://localhost:8080/networking/serv1");
  URLConnection con=url.openConnection();
  con.setDoOutput(true);
  OutputStreamWriter out=new OutputStreamWriter(con.getOutputStream());
  
  out.write("t1=abc");
  out.write("&t2=123");
  out.close();
  InputStream in= con.getInputStream();
  while(true){
   int x=in.read();
   if(x==-1)break;
   System.out.print((char)x);
  }
  
 }
}

EJB3 | Stateless session bean

To build a statelesss session bean in EJB3, you need to create one interafce and on class. Interface is implemented by class and methods declared in the interaface are available to client for remote access. Bean class and interaface should be public. Bean class is annotated with the annotation @Stateless(mappedName="something") and interafce is annotated with @Remote annotation. Both are compiled and packed in jar file.

Coding for Remote Interface
package p1;
import javax.ejb.Remote;
@Remote
public interface AdderIntf{
    int add(int x,int y);
}
Coding for Bean class
package p1;
import javax.ejb.Stateless;
@Stateless(mappedName="abc")
public class Adder implements AdderIntf{
    public int add(int x,int y){
        System.out.println("x="+x+" , y="+y);
        int z=x+y;
        return z;
    }
}
Both are compiled and packaged in jar file. you can you following command to package in jar file.
>jar cvf myejb.jar p1
Here p1 is the package in with two class files are produced by compiler.

Building client for statelesss session bean
Client for EJB may be application program, servlet or jsp. At the time of coding of client program, we need to pass server specific coding to Context object. Following program is using the EJB hosted  on weblogic server. So you can see some weblogic specific coding here.
import javax.naming.*;
import java.util.*;
class Add{
    public static void main(String ar[])throws Exception{
            Properties p=new Properties();
            p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
            p.put(Context.PROVIDER_URL,"t3://localhost:7001");
            InitialContext ctx=new InitialContext(p);
            p1.AdderIntf a1=(p1.AdderIntf)ctx.lookup("abc#p1.AdderIntf");
            int x=a1.add(10,20);
            System.out.println(x);
             
    }
}
Above program will connect to weblogic server and invoke the method add of the EJB having JNDI name abc#p1.AdderIntf and result is received by this program.

Calculator in java swing



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class gui1{
    static double a=0;
    static int op=0;
    public static void main(String ar[]){
        
        JFrame f1=new JFrame("Calculator");
        f1.setLayout(null);
        final JTextField t1=new JTextField(100);
        t1.setBounds(10,10,200,30);
        JButton b0=new JButton("0");
        JButton b1=new JButton("1");
        JButton b2=new JButton("2");
        JButton b3=new JButton("3");
        JButton b4=new JButton("4");
        JButton b5=new JButton("5");
        JButton b6=new JButton("6");
        JButton b7=new JButton("7");
        JButton b8=new JButton("8");
        JButton b9=new JButton("9");
        JButton dot=new JButton(".");
        JButton add=new JButton("+");
        JButton sub=new JButton("-");
        JButton equal=new JButton("=");
        JButton div=new JButton("%");
        JButton mul=new JButton("x");
    
        JPanel buttonPanel=new JPanel();
        buttonPanel.setBounds(10,60,200,150);
        buttonPanel.setBackground(Color.gray);
        //buttonPanel.pack();
        buttonPanel.setLayout(new GridLayout(4,4,5,5));
        buttonPanel.add(b7);
        buttonPanel.add(b8);
        buttonPanel.add(b9);
        buttonPanel.add(div);
        buttonPanel.add(b4);
        buttonPanel.add(b5);
        buttonPanel.add(b6);
        buttonPanel.add(mul);
        buttonPanel.add(b1);
        buttonPanel.add(b2);
        buttonPanel.add(b3);
        buttonPanel.add(sub);
        buttonPanel.add(b0);
        buttonPanel.add(dot);
        buttonPanel.add(equal);
        buttonPanel.add(add);
        
        class MyListener1 implements ActionListener{
            public void actionPerformed(ActionEvent e){
                String cmd=e.getActionCommand();
                if(cmd.equals("+")){
                    a=Double.parseDouble(t1.getText());
                    op=1;
                    t1.setText("");
                }else if(cmd.equals("-")){
                    a=Double.parseDouble(t1.getText());
                    op=2;
                    t1.setText("");
                }else if(cmd.equals("x")){
                    a=Double.parseDouble(t1.getText());
                    op=3;
                    t1.setText("");
                }
                else if(cmd.equals("%")){
                    a=Double.parseDouble(t1.getText());
                    op=4;
                    t1.setText("");
                    
                }else if(cmd.equals("=")){
                    double b=Double.parseDouble(t1.getText());
                    double c=0
                    switch(op){
                        case 1:c=a+b;break;
                        case 2:c=a-b;break;
                        case 3:c=a*b;break;
                        case 4:c=a/b;break;
                        default :c=0;
                    }
                    t1.setText(""+c);
                }
                else if(cmd.equals("0")){
                    t1.setText(t1.getText().concat("0"));
                }else if(cmd.equals("1")){
                    t1.setText(t1.getText().concat("1"));
                }else if(cmd.equals("2")){
                    t1.setText(t1.getText().concat("2"));
                }else if(cmd.equals("3")){
                    t1.setText(t1.getText().concat("3"));
                }else if(cmd.equals("4")){
                    t1.setText(t1.getText().concat("4"));
                }else if(cmd.equals("5")){
                    t1.setText(t1.getText().concat("5"));
                }else if(cmd.equals("6")){
                    t1.setText(t1.getText().concat("6"));
                }else if(cmd.equals("7")){
                    t1.setText(t1.getText().concat("7"));
                }else if(cmd.equals("8")){
                    t1.setText(t1.getText().concat("8"));
                }else if(cmd.equals("9")){
                    t1.setText(t1.getText().concat("9"));
                }else if(cmd.equals(".")){
                    t1.setText(t1.getText().concat("."));
                }
                
            }
        }
        
        
        MyListener1 ml=new MyListener1();
        add.addActionListener(ml);
        sub.addActionListener(ml);
        mul.addActionListener(ml);
        div.addActionListener(ml);
        equal.addActionListener(ml);
        b0.addActionListener(ml);
        b1.addActionListener(ml);
        b2.addActionListener(ml);
        b3.addActionListener(ml);
        b4.addActionListener(ml);
        b5.addActionListener(ml);
        b6.addActionListener(ml);
        b7.addActionListener(ml);
        b8.addActionListener(ml);
        b9.addActionListener(ml);
        dot.addActionListener(ml);
        
        f1.add(t1);
        f1.add(buttonPanel);
        f1.setBounds(300,200,230,250);
        f1.setVisible(true);
    }
}




JUnit test : example

Here following is the class to be tested using JUnit

public
 class MyClass {
    public int add(int a,int b){
        return a+b;
    }
    public int sub(int a,int b){
        return a-b;
    }
    public int mul(int a,int b){
        return a*b;
    }
    public int div(int a,int b){
        return a/b;
    }
}


class that contains three testing method to test add method of class MyClass
import static org.junit.Assert.assertEquals;
import org.junit.*;
public class MyClassTest {
          @Test
          public void add() {
              MyClass c=new MyClass();
              assertEquals(30, c.add(10,20));
          }
          @Test
          public void add2() {
              MyClass c=new MyClass();
              assertEquals(310, c.add(10,20));
          }
          @Test
          public void add3() {
              MyClass c=new MyClass();
              assertEquals(30, c.add(10,20));
          }
          
          public static void main(String args[]) {
                org.junit.runner.JUnitCore.main("MyClassTest");
    }
  }


  Now set junit-4.5.jar into classpath , compile and run .
  similarly  you can write test cases for other methods.

String hadnling

String is the sequence of character represented by the object of String class in java. Two other classes’ string buffer and string builder can be used for same thing. String object provides some predefined method those are used to manipulate the string.
String object is said to be the immutable this means that you can not manipulate the string object. But you can work with that object. When you manipulate the string object then new string object is created and it consists of manipulated contents. But it is hard to observe by programmer without experience.
Here to solve this problem you can use the String buffer class to create the string object in which you can manipulate the string contents with the same object. That is the object of string class the mutable.
String buffer is the thread safe.

Another class to create the mutable string objects is string builder class. But it is no thread safe.

Creating String

There are many ways to create the string object

1
You can declare string reference variable and assign the string lateral to it, then string object is created automatically and the reference of that object is stored in the reference variable you declared. for example
String str=”this my first string”;

2
You can create the string object using new operator. What you want to write in string is passed in the constructor of string class. there are 11 constructor those are used to create the string through different ways
String str=new String(“this is my first string”);

3
Creating the string using character array
char[] chs = { 'h', 'e', 'l', 'l', 'o', '.'};
String srt = new String(chs);

4
Creating the string using sub character array
char[] chs = { 'h', 'e', 'l', 'l', 'o', '.'};
String srt = new String(chs,2,2);

5
If you leave the string constructor blank, the n it creates the empty string.
String str=new String();

6
There is the constructor  String(byte[] bytes) which can Constructs a new String by decoding the specified array of bytes using the platform's default charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
byte b[]={65,66,67,68,68,70};
String str3=new String(b);
System.out.println(str3);
Output: ABCDDF
7
Creating the string of the sub array of byte from specified position of specified length using the constructor  String(byte[] bytes, int offset, int length)

byte b[]={65,66,67,68,68,70};
String str6=new String(b,2,3);
System.out.println(str6);
Output: CDE
8
Creating string from sub array byte by decoding the bytes using specified CharSet. Some Character set are following.

US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
ISO-8859-1   ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
UTF-8 Eight-bit UCS Transformation Format
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
Try{
     byte b7[]={65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80};
     String str7=new String(b7,0,13,"ISO-8859-1");
     System.out.println(str7);
}catch(UnsupportedEncodingException e){System.out.println(e);}
This constructor throws an exception.
9
Creating string of whole byte array
This is same as above only difference is that we passing complete byte array in the constructor.
Try{
     byte b7[]={65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80};
     String str7=new String(b7,"ISO-8859-1");
     System.out.println(str7);
}catch(UnsupportedEncodingException e){System.out.println(e);}

10
Crating string using array of Unicode characters

int unicodes[]={'\u0041','\u0042','\u0043','\u0044','\u0045','\u0046'};
String str8=new String(unicodes,0,5);
System.out.println(str8);
Output: ABCDE
11
Creating string using anther string
        String str1="This is first string";       
        String str2=new String(str1);
        System.out.println(str2);
12
Creating string from string buffer
                        StringBuffer sb=new StringBuffer("Hemraj");
                        String str12=new String(sb);
                        System.out.println(str12);
13
Creating string from string builder
                        StringBuilder sbu=new StringBuilder("Hemraj");
                        String str13=new String(sbu);
                        System.out.println(str13);


class MyString
{
    public static void main(String args[])
    {
        String str1="This is first string";
        System.out.println(str1);
        
        String str2=new String("This is second string");
        System.out.println(str2);
        
        byte b[]={65,66,67,68,69,70};
        String str3=new String(b);
        System.out.println(str3);
        
        
        String str6=new String(b,2,3);
        System.out.println(str6);

        byte b7[]={65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80};
        try{
            String str7=new String(b7,0,13,"ISO-8859-1");
            System.out.println(str7);
        }catch(UnsupportedEncodingException e){System.out.println(e);}
        
        int unicodes[]={'\u0041','\u0042','\u0043','\u0044','\u0045','\u0046'};
        String str8=new String(unicodes,0,5);
        System.out.println(str8);
        
        String str11=new String(str8);
        System.out.println(str11);
        
        StringBuffer sb=new StringBuffer("Hemraj");
        String str12=new String(sb);
        System.out.println(str12);
        
        StringBuilder sbu=new StringBuilder("Hemraj");
        String str13=new String(sbu);
        System.out.println(str13);
    }
}

Output:

This is first string
This is second string
ABCDEF
CDE
ABCDEFGHIJKLM
ABCDE
ABCDE
Hemraj
Hemraj

Popular Posts