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

method overloading with different return type


/**
 * method overloading with different return type
 *
 *
 */

public class MethodOverloading {
   
    // Simple one
    void print(int a ) {

        System.out.println("Method with integer parameter");
       
    }
   
    void print()
    {
        System.out.println("Default method");
       
    }
   
    // with different return type
    int show(int u)

    {
        int a= 5;
        return a;
       
    }
   
    void show()
    {
        System.out.println("default method with different return type ");
    }
   
   
   
    public static void main(String[] args) {
       
        System.out.println("Welcome to Sterlite");
       
        // first we make reference of class
        MethodOverloading methodOverloading;
        // now we create object of that class
        methodOverloading= new MethodOverloading();
       
        // now we call the method inside class
        methodOverloading.print(); // default call
        methodOverloading.print(4);
       
       
        methodOverloading.show();
       
         
    }
   

}


*************************** OUTPUT ***************************************

Welcome to Sterlite
Default method
Method with integer parameter
default method with different return type





*****************************************************************************
Thus, method overloading works with different return types and with different parameter as arguments.












Use of Static keyword


package dice;
import java.util.Random;

public class Dice {
static int no_of_sides = 6;
int face_value = 0;
int roll() {
Random r = new Random();
this.face_value = r.nextInt(no_of_sides) + 1;
return this.face_value;
}
static class FirstDice {
static String color = "red";
}
static class SecondDice {
static String color = "black";
}
public static void main(String[] args) {
Dice d = new Dice();
System.out.println("The first die has color " + FirstDice.color + " and has face value after rolling as " + d.roll());
System.out.println("The second die has color " + SecondDice.color + " and has face value after rolling as " + d.roll());
}
}


/**    comments
Here, we have used the static keyword to call the variable(colour ) directly in main method.
We made the inner class(firstDice) static and then the variable colour static to display the colour of  first dice in main method.
Also, in the main method which is static, any variable which needs to be accessed should be static and for the non-static, the variable, function or method, which needs to be  accessed should be accessed by creating an instance of the class, which we have done for calling the function roll in the main method.

**/

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

Method Overriding

******************** Demonstrating method Overloading *****************************

CLASS 1


package overridingclasses;

/**
 *MobileClass.java
 * @author SHASHI
super class 
 here method and constructor is defined

 */
public class MobileClass {
    
  //variable declaration
    String Manufacture;
    int cost;
    
//constructor to set value
    public MobileClass(String manu, int price) {
        this.Manufacture= manu;          // this to assign value to variable with constructor input
        this.cost= price;
    }
    
   String getModel(){                                 // created method to display value from constructor domain
       System.out.println("Method of mobile class");
       return Manufacture;
    }
    
}


*********************************** *********************************************
CLASS 2


package overridingclasses;

/**
 *AndroidClass.java
 * @author SHASHI
 */
public class AndroidClass extends MobileClass {             //Class extending to super class  

    AndroidClass(String manu, int cost) {                   // constructor to take input common to both class
        super(manu, cost);                                         //super to call value from super class
    }

    String getModel() {                                                //method to do calculation
        System.out.println("method of android class");
        return Manufacture;
    }
}


***************************************************************************8
CLASS 3


package overridingclasses;

/**
 *OverRidingClasses.java
 * @author SHASHI

main class performing overriding  of methods
 */
public class OverRidingClasses {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
         MobileClass ob1 = new AndroidClass("Huwai", 1987);  // created object of android class 
        System.out.println(ob1.getModel());         // called common method but it display only subclass method this is overriding concept.
    }

}


********************************************************************************
OUTPUT
Method of mobile class






















Demonstrating Method Overloading


package OverLoadingSampleClass;

/**
 *OverLoading.java
 * @author SHASHI
*
* here we are demonstrating a basic example of overloading of methods
* the print method has 3 different parameters but the method name is same so a method having the same name but different parameter can be considered under method overloading method
 */
public class OverLoading {
   
  void  print(String s){                                     //metnhod with string parameter
        System.out.println("String through overloading is  "+s);
    }
 void  print (int i)                                               //method with int parameter
    {
       
        System.out.println("Integer no through overloading is "+ i);
    }
 void   print (String s, int i){                             //same method with string and int parameter
        System.out.println(" overloaded string is "+ s + " and overloaded integer is "+i);
    }




}
class  OverloadDemo {             //class made outside of package class to call the methods of that class
     
     public static void main(String[] args) {
          OverLoading ob = new OverLoading();
     
         ob.print("sj");
        ob.print(99);
        ob.print("reliance", 33);
     }
   
 }



********************************** output **********************************
String through overloading is  sj
Integer no through overloading is 99
 overloaded string is reliance and overloaded integer is 33

Pattern of PYRAMID

public class PYRAMID {

   
    public static void main(String[] args) {
       
        int x=1,y=1,n=4;
       
        for (int i = 1; i <=n; i++) {
           
            for (int j = n; j >=i; j--)
            {
                System.out.print(" ");
               
            }
                for (int k = 1; k <=x; k++)
                {
                    System.out.print("*");   
                   
                } x=x+2;
               
                System.out.println("");
               
               
            }
           
           
           
           
        }
       
       
        }




/******************* OUT PUT******************************/

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




A complete working Java program to demonstrate all insertion methods on linked list

package linked.list;
/**
*
* @author SHASHI
*/
// A complete working Java program to demonstrate all insertion methods
// on linked list
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Inserts a new node after the given prev_node. */
public void insertAfter(Node prev_node, int new_data)
{
/* 1. Check if the given Node is null */
if (prev_node == null)
{
System.out.println(“The given previous node cannot be null”);
return;
}
/* 2 & 3: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 4. Make next of new Node as next of prev_node */
new_node.next = prev_node.next;
/* 5. make next of prev_node as new_node */
prev_node.next = new_node;
}
/* Appends a new node at the end. This method is 
defined inside LinkedList class shown above */
public void append(int new_data)
{
/* 1. Allocate the Node &
2. Put in the data
3. Set next as null */
Node new_node = new Node(new_data);
/* 4. If the Linked List is empty, then make the
new node as head */
if (head == null)
{
head = new Node(new_data);
return;
}
/* 4. This new node is going to be the last node, so
make next of it as null */
new_node.next = null;
/* 5. Else traverse till the last node */
Node last = head;
while (last.next != null)
last = last.next;
/* 6. Change the next of last node */
last.next = new_node;
return;
}
/* This function prints contents of linked list starting from
the given node */
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+” “);
tnode = tnode.next;
}
}
/* Driver program to test above functions. Ideally this function
should be in a separate user class. It is kept here to keep
code compact */
public static void main(String[] args)
{
/* Start with the empty list */
LinkedList llist = new LinkedList();
// Insert 6. So linked list becomes 6->NUllist
llist.append(6);
// Insert 7 at the beginning. So linked list becomes
// 7->6->NUllist
llist.push(7);
// Insert 1 at the beginning. So linked list becomes
// 1->7->6->NUllist
llist.push(1);
// Insert 4 at the end. So linked list becomes
// 1->7->6->4->NUllist
llist.append(4);
// Insert 8, after 7. So linked list becomes
// 1->7->8->6->4->NUllist
llist.insertAfter(llist.head.next, 8);
System.out.println(“\nCreated Linked list is: “);
llist.printList();
}
}

OUTPUT


Created Linked list is:
1 7 8 6 4