Two way interaction of client server in java

// here from both ends the message will be sent and read


//client code

public class TwoWayInteractionClient {

   
    public static void main(String[] args) throws IOException {
       
        Socket obj = new Socket("localhost",8844);
        DataOutputStream dout = new DataOutputStream(obj.getOutputStream());
        dout.writeUTF("This message is from client side");
        dout.flush();
       
       
        //ServerSocket rec = new ServerSocket(8134);
        DataInputStream din = new DataInputStream(obj.getInputStream());
        String newdata = (String)din.readUTF();
        System.out.println(" the new msg is " +newdata);
       
    }
   
   
}

output
the new msg is This msg is send from server


//server code

public class TwoWayInteractionServer {
     public static void main(String[] args) throws IOException {
       
    ServerSocket obj1 = new ServerSocket(8844);
        Socket obj = obj1.accept();
        DataInputStream din = new DataInputStream(obj.getInputStream());
        String str = (String)din.readUTF();
        System.out.println("The message from client is  " +str);
       
       // while two way interaction no need to create new port
        DataOutputStream dout =  new DataOutputStream(obj.getOutputStream());
        dout.writeUTF("This msg is send from server");
        dout.flush();
     }
   
   
}

output
The message from client is  This message is from client side











Client server callback of message

//code for client

public class MyClient {
 
 
    public static void main(String[] args) throws IOException {
     
        Socket obj = new Socket("localhost",8040);
        DataOutputStream dout = new DataOutputStream(obj.getOutputStream());
        dout.writeUTF("This message is from client side");
        dout.flush();
     
     
    }
}





// code for server

public class MyServer {
    public static void main(String[] args) throws IOException {
     
        ServerSocket obj1 = new ServerSocket(8040);
        Socket obj = obj1.accept();
        DataInputStream din = new DataInputStream(obj.getInputStream());
        String str = (String)din.readUTF();
        System.out.println("The message from client is  " +str);

     
    }
 
 
 
}

output (in server console)
This message is from client side



//here first we have to run server code then client code ..
//the message sent by the client will be readed in server concole
// the message are delivered through port no which is listened at sockets














Sequence Input Output Stream

import java.io.*;


// the purpose this api is to combine content of two input stream file  together
public class SequenceInputStreamEx    {
    public static void main(String[] args) throws Exception {
     
        FileOutputStream file1 = new FileOutputStream("F:\\file1.txt");
     
        FileOutputStream file2 = new FileOutputStream("F:\\file2.txt");

        String s1 = "He is awaken";
        byte b[]= s1.getBytes();
        file1.write(b);
        String s2 = "He will conquer all";
        byte c[]=s2.getBytes();
        file2.write(c);
        file1.close();
         file2.close();


// will put the above data in two files respectively
     

*********************************************************************************
// will combine the two file data , here we display in console and write in file also.     

 public static void main(String[] args) throws Exception {

        FileInputStream  file1 = new FileInputStream("F:\\file1.txt");
        FileInputStream  file2 = new FileInputStream("F:\\file2.txt");
     
        FileOutputStream fout = new FileOutputStream("F:\\SeqFile.txt");
     
        SequenceInputStream seqFile = new SequenceInputStream(file1, file2); // the two file data are combined together
     
        int i;
     
        while((i=seqFile.read())!=-1)
        {
            fout.write(i);          //writting the combined data in differnt file
         
            System.out.print((char)i);
        }
     

     
    }
}


output

He is awakenHe will conquer all

Use of Buffered , ByteArray Input and Output Stream



import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import java.io.*;


public class BufferOutputStreamrExample {


    public static void main(String[] args) throws FileNotFoundException, IOException {

        FileOutputStream  file = new FileOutputStream("F:\\check.txt");
     
     
        BufferedOutputStream bout = new BufferedOutputStream(file); //collection of data //here it is now connected to fileoutputStream to flush large amount of data together
        String s = "shashi is not dead";
        byte b[] = s.getBytes();
        bout.write(b);
        bout.flush();//it is used for flushing the buffer output stream data .
        bout.close();
        file.close();
       
    }
   
*********************************************************************************
    // whereas in byte array output stream we can write it to a different file

    public static void main(String[] args) throws FileNotFoundException, IOException {

        FileOutputStream  file = new FileOutputStream("F:\\check.txt");
     
     ByteArrayOutputStream bout1 = new ByteArrayOutputStream();
        bout1.write(65); // byte gives the ascii code so 65==A
        bout1.writeTo(file);


    // like  bout.writeTo(file1);
   
}

*********************************************************************************

   
     public static void main(String[] args) throws FileNotFoundException, IOException {
        FileInputStream  file = new FileInputStream("F:\\check.txt");
        BufferedInputStream bin = new BufferedInputStream(file); //collection of data //here it is now connected to fileoutputStream
     
     int i=0 ;
         while((i=bin.read())!=-1)
         {
             char ch =(char)i;
             System.out.println(ch);
           
         }
       
        bin.close();
        file.close();
       
         
}

******************************************************************************

public static void main(String[] args) throws FileNotFoundException, IOException {

byte []g = {35,37,38}; // be spefic while using byte as it has differnt code for different symbols.
      ByteArrayInputStream bin = new ByteArrayInputStream(g);// it will only read the byte data
 int i=0 ;
         while((i=bin.read())!=-1)
         {
             char ch =(char)i;
             System.out.println(ch);
           
         }
        }

output :- #
%
&


*******************************************************************************
}

File Input Output Stream




import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author SHASHI
 */
public class FileOutputStream1 {
    public static void main(String[] args) throws IOException {
        try {
            FileOutputStream file = new FileOutputStream("F:\\check.txt"); // will create file with specified name and in given location
 
            file.write(35); //be specific while writting the byte values .. it has different id  for diferent symbols
            file.close(); // a good practise
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileOutputStream1.class.getName()).log(Level.SEVERE, null, ex);
        }

FileInputStream f = new FileInputStream("F:check.txt"); // will check for this file
 int i =f.read();  // for reading u have to specify the content i.e, u r going to read integer content
        System.out.println(" the content is " +i);
     
    }
   
   
}
OUTPUT

the content is  17// whatever written in the file

Thread Priority


public class ThreadPriority extends Thread {
   
    public void run (){
        try {
            for (int i = 0; i < 4; i++) {
                 Thread.sleep(1000);
                  System.out.println("The current thread is  " +i+"  ," +Thread.currentThread().getName());
            }
         
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadPriority.class.getName()).log(Level.SEVERE, null, ex);
        }
 
}
    public static void main(String[] args) {
        ThreadPriority obj = new ThreadPriority();
         ThreadPriority obj1 = new ThreadPriority();
        obj.setPriority(Thread.MIN_PRIORITY);
        obj1.setPriority(Thread.MAX_PRIORITY);
       
        obj.start();
        obj1.start();
        //its all about priotising the threads
    }
   
}

output

The current thread is  0  ,Thread-1
The current thread is  0  ,Thread-0
The current thread is  1  ,Thread-1
The current thread is  1  ,Thread-0
The current thread is  2  ,Thread-1
The current thread is  2  ,Thread-0
The current thread is  3  ,Thread-1
The current thread is  3  ,Thread-0
BUILD SUCCESSFUL (total time: 4 seconds)


//see the priority of ececution of thread 1 .. it always start before thread 0

Thread Join



public class ThreadJoin extends Thread{
   
    public void run(){
        for (int i = 0; i < 4; i++) {
         
        try {
            Thread.sleep(1000);
            System.out.println("thread sleep "+i);
            System.out.println(" current thread name "+ Thread.currentThread().getName()); // getting current thread name
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoin.class.getName()).log(Level.SEVERE, null, ex); // not for beginners
        }}}   
    public static void main(String[] args) {
       
   
        try {
            ThreadJoin obj = new ThreadJoin();
            ThreadJoin obj1 = new ThreadJoin();
            ThreadJoin obj2 = new ThreadJoin();
            ThreadJoin obj3 = new ThreadJoin();
            System.out.println("thread 1 name "+obj.getName());  // getting and setting of Thread name
            obj.start();
            obj.join(); // used to emphasis that any thread which has to run will run after this thread completion
           
             obj1.start();
              obj1.join(5000);// it is just a priority checker
             obj2.start();
             obj3.start();
// we now set the thread name
            obj.setName("sj");
            System.out.println("after name change " + obj.getName());// here we access the thread name
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoin.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
    }
}

OUTPUT


thread 1 name Thread-0
thread sleep 0
 current thread name Thread-0
thread sleep 1
 current thread name Thread-0
thread sleep 2
 current thread name Thread-0
thread sleep 3
 current thread name Thread-0
thread sleep 0
 current thread name Thread-1
thread sleep 1
 current thread name Thread-1
thread sleep 2
 current thread name Thread-1
thread sleep 3
 current thread name Thread-1
after name change sj
thread sleep 0
thread sleep 0
 current thread name Thread-2
 current thread name Thread-3
thread sleep 1
thread sleep 1
 current thread name Thread-3
 current thread name Thread-2
thread sleep 2
thread sleep 2
 current thread name Thread-2
 current thread name Thread-3
thread sleep 3
thread sleep 3
 current thread name Thread-3
 current thread name Thread-2
BUILD SUCCESSFUL (total time: 12 seconds)





Thread Sleep




public class ThreadSleep extends Thread {
 
   
    public void run (){
       
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000) ;
                System.out.println("thread is about to sleep"+i); // repeated for 1 sec interval
            } catch (Exception e) {
                System.out.println(e);
            }
         
        }
}
    public static void main(String[] args) {
        ThreadSleep obj = new ThreadSleep();
       // obj.start();
     
   
        //obj.start();// this shows that we can start a thread twice but only by taking different references
       //obj.stop();
   
         ThreadSleep obj1 = new ThreadSleep();
        //when two run method are called simultaneously then they are treated as seperate object and are executed seperately
         obj.run();
        obj1.start();
        // calling run method directly will run the run method directly and if we call 2 run methods they will run one by one
// obj.run();
     //   obj1.run();
    }
 
}


OUTPUT

thread is about to sleep0
thread is about to sleep1
thread is about to sleep2
thread is about to sleep3
thread is about to sleep4
thread is about to sleep0
thread is about to sleep1
thread is about to sleep2
thread is about to sleep3
thread is about to sleep4
BUILD SUCCESSFUL (total time: 10 seconds)

Multithreading by runnable interface

public class multithreading implements Runnable{
      //reaching  thread class other by implementing runnable interface

 
    public void run() {
        System.out.println("Thread is running ");
    }
   
    public static void main(String[] args) {
        multithreading obj =new multithreading();
        Thread t1= new Thread(obj);
        t1.start();
   
    }
   
   
}

OUTPUT


Thread is running 

Multithreading by extend method




public class multithreading extends Thread {
// we extend to thread class, the class object is treated aa s thread object.
 
    public void run() {
        System.out.println("Thread is running ");
    }
   
    public static void main(String[] args) {
        multithreading obj =new multithreading();
        obj.start(); // means class object start then automaticaly run method starts. and whatever their is insicde run method it get executed
 
    }
   
   
}

OUTPUT
Thread is running

Nested Interface

//parent interface
 interface Showable{
    void show();
   
static final class a{
   static final int data=1;// we can create class inside interface
}

//child interface
interface Message{ 
    void msg();
   
}
}

public class ShowInterface implements Showable.Message {

    @Override
    public void msg() {System.out.println("i am in nested interface ");
       
    }
   
    public static void main(String[] args) {
        ShowInterface obj = new ShowInterface(); //obj :- a reference to parent interface
        obj.msg();
    }
}



                      OUTPUT

i am in nested interface












Example of nested Switch

public class NestedSwitch {
     public enum subject {dbms, csa};
    public static void main(String[] args) {
        int year=4;
        char branch ='c';
        subject [] s =subject.values();
     
     
// first switch statement

      switch (year)
        {
            case 1 :
                System.out.println("year 1");
                break;
            case 4:
                System.out.println("its 4th year");
             

// 2nd Switch statement
     switch  (branch){
                    case 'm':
                        System.out.println("its mechanical");
                        break;
                       
                    case 'c':
                        System.out.println("Its cse and its top subject are ");
                     
                        for(subject s1:s){ //for enhanced loop of enum
                           
                       
       //3rd switch statement           
            switch (s1)
                        {
                            case csa:
                                System.out.println("csa");
                                break;
                            case dbms:
                                System.out.println("dbms");
                                break;
                                default:
                                    System.out.println("no subject");
                        }
                        }
                       
                       
               break;
                    default :
                        System.out.println("check your branch");
                }
                break; // caution to put break here
            default:
                System.out.println("check your year");
        }
       
    }
   
   
}






                        output

its 4th year
Its cse and its top subject are
dbms
csa

Different uses of loop

public class LoopClasses {
static int i=5;
   
    public static void main(String[] args) {

// while infinite loop

      while(true)  {
          System.out.println("the value of i is "+i);
      }


*********************************************************************************
     //do while infinite loop

       do {           
            System.out.println(" "+i);
        } while (true);

       
*********************************************************************************       // use of break statement

 do {   
            i++;
            System.out.println(""+i);
            break;  // use of break
        } while (i<10);

*********************************************************************************


// labeled for loop
aa:

        for (int j = 0; j < 10; j++) {
            System.out.println(" "+j);
            for (int k = 0; k < 10; k++) {
                if(j==k)
                {
                  break aa;
                 
                }
            }
        }
System.out.println(" i am out aa");

*********************************************************************************
//use of continue statement

          for (int j = 0; j < 5; j++) {
             
              if (j==3) {
               continue; // when j==3 it redirect back to for loop and do not let it go to print j value at 3
                 //  System.out.println("ok "); unreachable
              }
             
              System.out.println(" "+ j);
        }



*********************************************************************************
// java for each loop

int ar[] = {2,3,4,5};

for(int i:ar)
{
    System.out.println(" "+i);
}


*********************************************************************************
//for infinite loop

        for (;;) {
            System.out.println("sj");
        }




    }
   
}

Use of inner class

public  class  UseOfInnerClass {
static int d=5;
  static  class  inner {
        void msg(){
            System.out.println("i am in inner class " +d); // for accessing d the classs is made static        //because static variable can be acessed by static class only
        }
    }
   
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
     
     UseOfInnerClass.inner ob =new UseOfInnerClass.inner(); // calling method of inner class
        ob.msg();
}
}


output

i am in inner class 5

The power decision



This  is the story of a boy who was exceptional, but he in order to maintain his family tradition he sacrificed his physical pleasure.

He could not decide what to do and what not.
He remained confused and this confusion continued in his other walks of life.

After a long time, a twist came in his life. He started destroying himself in love toward a girl who has no emotion for him. He did not value his self-esteem against her.

He made the mistake of prioritizing her and de-prioritizing all works of life.
He was having full confidence in his skills that one day he will back up all mistakes of life.
But he did not do that at "right time" and as a result, he loses his self-esteemed once again at a place where he desires to be respected.

The point I am making for that boy because he has not taken the right decision at right time.
Like that there are many people who do the same mistake.
For someone, it comes out of lust and for someone it comes out of greediness.
The title is justified as one has to take the right decision at right time in life and after that time he again has to take some right decision to get the pleasure of life.

The one who does both enjoy the life ...but he also needs to keep patience.