Program to demonstrate DataInputStream class Using Conditional Operator

/* Program to demonstrate DataInputStream class Using Conditional Operator */

import java.io.DataInputStream;   // to load DataInputStream class
class P22B
{   
    public static void main(String args[])
    {
        int x,y;
        // creating object of class DataInputStream.
                   DataInputStream in = new DataInputStream(System.in);

        try
           {

        System.out.print(" Enter a number  : ");
        x = Integer.parseInt(in.readLine());
   
        if(x>0)
             y=1;
        else if(x<0)
            y=-1;
             else
            y=0;

        System.out.println(" x = "+x+"   y = "+y);
        }

        catch(Exception e) {  System.out.println("I/O Error");   }
    }
}

/* Note : This program might give some Note at compile time, ignore it and go ahead. */





/* Using Conditional Operator */

import java.io.DataInputStream;   // to load DataInputStream class
class P22C
{   
    public static void main(String args[])
    {
        int x,y;
        // creating object of class DataInputStream.
                   DataInputStream in = new DataInputStream(System.in);

        try
           {

        System.out.print(" Enter a number  : ");
        x = Integer.parseInt(in.readLine());
   
        y = (x>0)? 1: ( (x<0) ? -1 : 0 );   // using conditional operator

        System.out.println(" x = "+x+"   y = "+y);
        }

        catch(Exception e) {  System.out.println("I/O Error");   }
    }
}

    /* Note : This program might give some Note at compile time, ignore it and go ahead. */    
READ MORE - Program to demonstrate DataInputStream class Using Conditional Operator

Program to demonstrate System.out.write()

/* Program to demonstrate System.out.write() */

class WriteDemo
{
    public static void main(String args[ ])
    {
        int i; char c ; float f;double d;

        i = 'J';
        c = 'A';
        f = 'V';
        d = 'A';

        System.out.write(i);
        System.out.write(c);
        System.out.write((int)f);   // convertion from float to integer   
        System.out.write((int)d);   // convertion from double to integer   
        System.out.write('\n');   
    }
}   
       
   
READ MORE - Program to demonstrate System.out.write()

Program to demonstrate Wrapper Class Methods

/* Program to demonstrate Wrapper Class Methods */

import java.io.*;

class WrapperClassDemo
{
   
    public static void main(String args[])
    {
        // Converting number to object
        Float principalAmt = new Float(0);
        Float interestRate = new Float(0);
       
        int num_of_years=0;

   
            try
            {
            DataInputStream in = new DataInputStream(System.in);
            System.out.print("Enter Principal Amount : ");
            System.out.flush();
            String principalString = in.readLine();
            principalAmt = Float.valueOf(principalString); // String object to number object

            System.out.print("Enter Interest Rate : ");
            System.out.flush();
            String interestString = in.readLine();
            interestRate = Float.valueOf(interestString); // String object to number object


              System.out.print("Enter Number of years : ");
            System.out.flush();
            String yearString = in.readLine();
            num_of_years = Integer.parseInt(yearString); // Numeric Strings to numbers
            }

            catch(IOException e)
            {
            System.out.println("I/O Error");
            System.exit(1);
            }


        float TotalAmount = loan(principalAmt.floatValue(),interestRate.floatValue(),num_of_years);
        System.out.println("------------------------------");
        System.out.println("Total Amount : "+TotalAmount);
        System.out.println("------------------------------");
    }

    static float loan(float p,float r,int n)
    {
        int year = 1;
        float sum = p;
        while(year <= n)
        {
            sum = sum * (1+r);
            year = year + 1;
        }
        return sum;
    }
}   
       

READ MORE - Program to demonstrate Wrapper Class Methods

Program to demonstrates various Vector Operation

/* Program to demonstrates various Vector Operation */
import java.util.*;

class VectorDemo
{
    public static void main(String args[ ])
    {
        // initial size is 4, increment is 2
        Vector v = new Vector(4,2);

        System.out.println("Initial size : "+v.size());
        System.out.println("Initial Capacity : "+v.capacity());

        v.addElement(new Integer(1));
        v.addElement(new Integer(2));
        v.addElement(new Integer(3));
        v.addElement(new Integer(4));
        v.addElement(new Integer(5));

        System.out.println("Capacity after five additions : "+v.capacity());
        v.addElement(new Double(5.25));
        System.out.println("Current Capacity : "+v.capacity());
        v.addElement(new Double(10.28));
        v.addElement(new Integer(8));

        System.out.println("Current Capacity : "+v.capacity());
        v.addElement(new Float(20.25));
        v.addElement(new Integer(10));

        System.out.println("Current Capacity : "+v.capacity());
        v.addElement(new Integer(11));
        v.addElement(new Integer(12));

        System.out.println("\nFirst element :"+(Integer)v.firstElement());
        System.out.println("Last element :"+(Integer)v.lastElement());

        if(v.contains(new Double(5.20)))
            System.out.println("Vector contains 5.20");

        //****** Enumerate the elements in the Vector *********
        Enumeration vEnum = v.elements();

         System.out.println("\n Elements in vector :");
        while(vEnum.hasMoreElements())
            System.out.print(vEnum.nextElement() +"   ");
        System.out.println();
    }
}

READ MORE - Program to demonstrates various Vector Operation

Program to print two-dimensional Square Root Table

/* Program to print two-dimensional Square Root Table */

import java.text.*;    // to include DecimalFormat class

class TwoDArray5
{
    public static void main(String args[])
    {
        double a[][]= new double[10][10];
        int i,j;
        double x,y;
        DecimalFormat df = new DecimalFormat("0.00"); // formatting
       
        System.out.println("--------Square Root Table--------\n");

        for(i=0,x=0.0;i<10;i++,x=x+1.0)
            for(j=0,y=0.0;j<10;j++,y=y+0.1)           
             a[i][j] = Math.sqrt(x+y);
       
        for(j=0,y=0.0;j<10;j++,y=y+0.1)
             System.out.print("    "+df.format(y));

        for(j=0;j<10;j++)
            System.out.print("==============");

        System.out.println();
        for(i=0,x=0.0;i<10;i++,x=x+1.0)
        {   
            System.out.print(x+" | ");
            for(j=0;j<10;j++)
            System.out.print("   "+df.format(a[i][j]));
            System.out.println();
        }
    }
}
       
               
READ MORE - Program to print two-dimensional Square Root Table

Program for Matrix Multiplication

/*  Program for Matrix Multiplication */

class TwoDArray4
{
    public static void main(String args[ ])
    {
        int i,j,k;
        int multi[][]= new int[3][4];
           int set1[ ][ ] = { {3,5 }, {4,2}, {4,1} } ;
           int set2[ ][ ] = { {1,2,4,3}, {1,5,3,2}} ;
           System.out.print("The first 3X2 matrix is :\n");
           for (i=0 ; i<3 ; i++)
           {
                 for (j=0 ; j<2 ; j++)
                     System.out.print(set1[i][j]+"\t");
                 System.out.println(" ");
           }
           System.out.println(" ");

           System.out.println("The second 2X4 matrix is : ");
           for (i=0 ; i<2 ; i++)
           {
                 for (j=0 ; j<4 ; j++)
                       System.out.print(set2[i][j]+"\t");
                 System.out.println(" ");
            }
            System.out.println(" ");

        for (i=0 ; i<3 ; i++)
                {
                 for (j=0 ; j<2 ; j++)
                 {
                      for (k=0 ; k<4 ; k++)
                       multi[i][k] += set1[i][j]*set2[j][k] ;
                 }
            }

        System.out.println("The resultant addition 3X4 matrix is :") ;
            for (i=0 ; i<3 ; i++)
            {
                  for (j=0 ; j<4 ; j++)
                    System.out.print(multi[i][j]+"\t");
                 System.out.println(" ");
            }       
    }
}




READ MORE - Program for Matrix Multiplication

Program for Matrix Addition

/*  Program for Matrix Addition */

class TwoDArray3
{
    public static void main(String args[ ])
    {
        int i , j;
        int add[][]= new int[3][3];
           int set1[ ][ ] = { {1,3,5},{7,9,11},{13,15,17} } ;
           int set2[ ][ ] = { {2,4,6},{8,10,12},{14,16,18} } ;
           System.out.print("The first 3X3 matrix is :\n");
           for (i=0 ; i<3 ; i++)
           {
                 for (j=0 ; j<3 ; j++)
                     System.out.print(set1[i][j]+"\t");
                 System.out.println(" ");
           }
           System.out.println(" ");
           System.out.println("The second 3X3 matrix is : ");
           for (i=0 ; i<3 ; i++)
           {
                 for (j=0 ; j<3 ; j++)
                       System.out.print(set2[i][j]+"\t");
                 System.out.println(" ");
            }
            System.out.println(" ");
            for (i=0 ; i<3 ; i++)
            {
                  for (j=0 ; j<3 ; j++)
                      add[i][j] = set1[i][j] + set2[i][j] ;
            }
            System.out.println("The resultant addition 3X3 matrix is :") ;
            for (i=0 ; i<3 ; i++)
            {
                  for (j=0 ; j<3 ; j++)
                    System.out.print(add[i][j]+"\t");
                 System.out.println(" ");
            }       
    }
}
READ MORE - Program for Matrix Addition

Program that display average of marks for each subject

/*  Program that display average of marks for each subject*/

class TwoDArray2
{
    public static void main(String args[ ])
    {
        int i , j ;
        int marks[][] ={ {65,68,75,59,77},
                 {62,85,57,66,80},
                 {71,77,66,63,86} } ;
        float avg ;
        System.out.print("\t\t");
        for (i = 0 ; i < 5 ; i++)
            System.out.print("subj"+(i+1)+"\t");

        System.out.println("\n");
        for (i=0 ; i<3 ; i++)
        {
            System.out.print(" student"+(i+1)+"\t");
            for(j=0 ; j<5 ; j++)
                System.out.print(marks[i][j]+"\t");
            System.out.print("\n");
        }
        System.out.print("\n\nThe Average of each subject is : \n") ;

        for (j=0 ; j<5 ; j++)
        {
            System.out.print("Subject"+(j+1)+" : ") ;

            for (i=0,avg=0 ; i<3 ; i++)
                avg = avg + (float)marks[i][j] ;

            avg = avg / 3 ;                              
            System.out.print(avg+"\n");
        }
       
    }
}
READ MORE - Program that display average of marks for each subject

Program that adds up the individual elements of 2 D Array

/*  Program that adds up the individual elements of 2 D Array*/
   
class TwoDArray1
{
    public static void main(String args[ ])
    {
         int i , j , sum ;
         int elements[ ][ ] = { {0,2,4,6,8,10,12},
                    {14,16,18,20,22,24,26},
                    {28,30,32,34,36,38,40} } ;
              for ( i = 0,sum = 0 ; i < 3 ; i++)
          {
                 for (j=0 ; j<7 ; j++)
                       sum = sum + elements[i][j] ;
          }
          System.out.println("The result of addition = "+ sum) ;     
    }
}
READ MORE - Program that adds up the individual elements of 2 D Array

Program to demonstrates the - trim( )

/* Program to demonstrates the - trim( ) */

class trimDemo
{
    public static void main(String args[ ])
    {
        String s1 = "         Mahatma Gandhi        ";
        String temp = s1.trim();

        System.out.println("Original String is : "+s1);
        System.out.println("String after calling trim() : "+temp);
    }
}
READ MORE - Program to demonstrates the - trim( )

Program to demonstrates the - toCharArray( )

/* Program to demonstrates the - toCharArray( ) */

class toCharArrayDemo
{
    public static void main(String args[ ])
    {
        String s =" Java is Object Oriented Language";
        char ch[]= new char[s.length()];

        ch=s.toCharArray();
        System.out.println("All characters in a String object is converted to character Array..");
        System.out.println(ch);
    }
}
READ MORE - Program to demonstrates the - toCharArray( )

Program to demonstrate - toString()

/* Program to demonstrate - toString() */

class Rectangle
{
    int length;
    int width;

    Rectangle(int l,int w)
    {       
        length = l;
        width = w;
    }

    public String toString()
    {
        return "Dimensions are "+length+" by "+width+".";
    }
   
}


class toStringDemo
{
    public static void main(String args[])
    {
        Rectangle rect = new Rectangle(20,15);
        String s = "Rectangle rect : " +rect;  // concatenate Rectangle object

        System.out.println(rect);   // convert Rectangle to String
        System.out.println(s);
    }
}
READ MORE - Program to demonstrate - toString()

Program for Matrix Multiplication

/*  Program for Matrix Multiplication */

class ThreeDArray
{
    public static void main(String args[ ])
    {
        int a[][][]={ { {5,0,2}, {0,0,9}, {4,1,0}, {7,7,7}},
                                 { {3,0,0}, {8,5,0}, {0,0,0}, {2,0,9}}
                               };
        int count = 0;

        for (int i = 0; i < 2; i++)
                  for (int j= 0; j < 4; j++)
                         for (int k = 0; k < 3; k++)
                                     if (a[i][j][k]==0)   
                         ++count;

        System.out.println("This Array has "+count+" zeros.");
    }
}



READ MORE - Program for Matrix Multiplication

Program to demonstrates the - substring()

/* Program to demonstrates the - substring() */

class substringDemo
{
    public static void main(String args[ ])
    {
        String s="India,Nepal,Bhotan,ShriLanka,China";
        String temp;

        System.out.println("Original String is : "+s);

        temp = s.substring(12);
        System.out.println("Substring from index 12 to end of string is : "+temp);

        temp = s.substring(0,5);
        System.out.println("Substring from index 0 to 4 is : "+temp);


    }
}
           
       
   
READ MORE - Program to demonstrates the - substring()

Program to concatenates three strings

/* Program to concatenates three strings */

class StringDemo3
{
    public static void main(String args[ ])
    {
        String name = "Indira";
        String str="Her name is "+name+" Gandhi.";
        System.out.println(str);
    }
}
READ MORE - Program to concatenates three strings

Construct string from subset of char array

/* Construct string from subset of char array */

class StringDemo2
{
    public static void main(String[] args)
    {
        byte ASCII[]={65,66,67,68,69,70};
   
        String str1=new String(ASCII);
        System.out.println("String1 : "+str1);
   
        String str2=new String(ASCII,1,3);
        System.out.println("String2 : "+str2);
    }
}
READ MORE - Construct string from subset of char array

Construct one string from another

/* Construct one string from another */

class StringDemo1
{
    public static void main(String[] args)
    {
        char name[]={'I','N','D','I','A'};
        String str1= new String(name);
        String str2= new String(str1);

        System.out.println("String1 :"+str1);
        System.out.println("String2 :"+str2);
    }
}
READ MORE - Construct one string from another

Program to demonstrate StringBuffer Methods

/* Program to demonstrate StringBuffer Methods */

class StringBufferDemo
{
    public static void main(String args[ ])
    {
        // using length() and capacity()
        StringBuffer sb= new StringBuffer("Java");
        System.out.println("\n StringBuffer : "+sb);

        System.out.println("\n********** length() and capacity() **************");
        System.out.println("\n Length : "+sb.length());
        System.out.println("\n Capacity : "+sb.capacity());

        // using ensureCapacity()
        System.out.println("\n\n********** ensureCapacity() **************");
        System.out.println("\n Allocating room for 50 extra characters");

        sb.ensureCapacity(50);
        System.out.println(" \n New Capacity after calling ensureCapacity(50) : "+sb.capacity());

        // using setLength()
        System.out.println("\n\n********** setLength() **************");
        System.out.println("When you increase the size of the buffer , null characters are added to the end of the existing buffer.");

        sb.setLength(2);
        System.out.println("\nNew Length after calling setLength(2) : "+sb.length());
        System.out.println("\n StringBUffer after setting new length : "+sb);

        // using charAt() and setCharAt()
        sb = new StringBuffer("Java");
        System.out.println("\n\n********** charAt() and setCharAt() **************");
        System.out.println("\nStringBuffer : "+sb);
        System.out.println("\ncharAt(0) before : "+sb.charAt(0));

        sb.setCharAt(0,'K');
        System.out.println("\nNew StringBuffer : "+sb);
        System.out.println("\ncharAt(0) after : "+sb.charAt(0));
       
        // using append()
        System.out.println("\n\n********** append() **************");
        StringBuffer sb1 = new StringBuffer(40);

        String s = sb1.append(" X = ").append(100).append(".").toString();
        System.out.println("\nAfter calling append(), String is : \n");
        System.out.println(s);

        // using insert()
        System.out.println("\n\n********** insert() **************");
        sb = new StringBuffer("Java is a true oriented Language");
        System.out.println("\nStringBuffer : "+sb);

        sb.insert(15, "object-");
        System.out.println("\n calling insert().....");
        System.out.println("\nAfter inserting 'object-' in StringBuffer, New String is :"+sb);

        // using reverse()
        System.out.println("\n\n********** reverse() **************");
        sb = new StringBuffer("JAVA");
        System.out.println("\nStringBuffer : "+sb);
        sb.reverse();
        System.out.println("\nAfter calling reverse() new StringBuffer : "+sb);

        // using delete() and deleteCharAt()
        System.out.println("\n\n********** delete() and deleteCharAt() **************");
        sb = new StringBuffer("Java is a true object-oriented Language");
        System.out.println("\nStringBuffer : "+sb);
        sb.delete(9,14);
        System.out.println("\n calling delete().....");
        System.out.println("\nAfter deleting 'true' from StringBuffer, New StringBuffer : \n"+sb);

        sb.deleteCharAt(0);
        System.out.println("\n calling deleteCharAt().....");
        System.out.println("\nAfter deleting first character, New StringBuffer: \n"+sb);

        // using replace()
        System.out.println("\n\n********** replace() **************");
        sb = new StringBuffer("He is Superstar.");
        System.out.println("\nStringBuffer : "+sb);

        sb.replace(3,5,"was");
        System.out.println("\ncalling replace()......");
         System.out.println("\nAfter replacing 'is' with 'was', New StringBuffer : "+sb);

        // using substring()
        System.out.println("\n\n********** substring() **************");
        sb = new StringBuffer("He is Superstar.");
        System.out.println("\nStringBuffer : "+sb);

        s = sb.substring(6,11);
        System.out.println("\n calling substring().....");       
        System.out.println("Retriving 'Super' from StringBuffer, New StringBuffer : "+s);       

    }
}
READ MORE - Program to demonstrate StringBuffer Methods

try,catch and finally blocks in Exception Handling


The try Block:

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:
try {
    code
}
catch and finally blocks . . .
The segment in the example labeled code contains one or more legal lines of code that could throw an exception.
To construct an exception handler for the writeList method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to do this. You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short.
private List<Integer> list;
private static final int SIZE = 10;

PrintWriter out = null;

try {
    System.out.println("Entered try statement");
    out = new PrintWriter(new FileWriter("OutFile.txt"));
    for (int i = 0; i < SIZE; i++) {
        out.println("Value at: " + i + " = " + list.get(i));
    }
}
catch and finally statements . . .
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it;

The catch Blocks:

 

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}
Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.

The following are two exception handlers for the writeList method — one for two types of checked exceptions that can be thrown within the try statement:
try {

} catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException: "
                        + e.getMessage());
    throw new SampleException(e);

} catch (IOException e) {
    System.err.println("Caught IOException: "
                        + e.getMessage());
}
 

Catching More Than One Type of Exception with One Exception Handler:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|):
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}
Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.


The finally Block:

 The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling  it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Note: 

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Important:
The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.
If you are using Java SE 7 or later, consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed

 

READ MORE - try,catch and finally blocks in Exception Handling

Types of Exceptions

1. checked exception:
   
 These are exceptional conditions that a well-written application should anticipate and recover from. Example:suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

2. error:

 These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
Example: suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.

Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.

3.runtime exception:
  
 These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. 
Example: consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.



READ MORE - Types of Exceptions

What Is an Exception and it's Advantages?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).

                                                        Call Stack

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.

                                                       

Advantages of Exceptions:

Advantage 1: Separating Error-Handling Code from "Regular" Code

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.

Advantage 2: Propagating Errors Up the Call Stack

 

A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods. Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program: method1 calls method2, which calls method3, which finally calls readFile.
method1 {
    call method2;
}

method2 {
    call method3;
}

method3 {
    call readFile;
 

Advantage 3: Grouping and Differentiating Error Types

 

 


READ MORE - What Is an Exception and it's Advantages?

Program to demonstrate append() and insert() Functions

import java.lang.System;
import java.lang.String;
import java.lang.StringBuffer;

public class StringBufferApp {
 public static void main(String args[]) {
  StringBuffer sb = new StringBuffer(" is ");
  sb.append("Hot");
  sb.append('!');
  sb.insert(0,"Java");
  sb.append('\n');
  sb.append("This is ");
  sb.append(true);
  sb.setCharAt(21,'T');
  sb.append('\n');
  sb.append("Java is #");
  sb.append(1);
  String s = sb.toString();
  System.out.println(s);
 }
}
READ MORE - Program to demonstrate append() and insert() Functions

Program to demonstrate some usefull method in java

import java.lang.System;
import java.lang.String;

public class StringApp {
 public static void main(String args[]) {
  String s = " Java Developer's Guide ";
  System.out.println(s);
  System.out.println(s.toUpperCase());
  System.out.println(s.toLowerCase());
  System.out.println("["+s+"]");
  s=s.trim();
  System.out.println("["+s+"]");
  s=s.replace('J','X');
  s=s.replace('D','Y');
  s=s.replace('G','Z');
  System.out.println(s);
  int i1 = s.indexOf('X');
  int i2 = s.indexOf('Y');
  int i3 = s.indexOf('Z');
  char ch[] = s.toCharArray();
  ch[i1]='J';
  ch[i2]='D';
  ch[i3]='G';
  s = new String(ch);
  System.out.println(s);
 }
}

/*

 Java Developer's Guide
 JAVA DEVELOPER'S GUIDE
 java developer's guide
[ Java Developer's Guide ]
[Java Developer's Guide]
Xava Yeveloper's Zuide
Java Developer's Guide
*/
READ MORE - Program to demonstrate some usefull method in java

Program to demonstrates the - startsWith() and endsWith()

/* Program to demonstrates the - startsWith() and endsWith() */

class startsWith_endsWithDemo
{
    public static void main(String args[ ])
    {
    String s1="Yahoo";

    System.out.println(s1+" starts with 'Ya' : "+s1.startsWith("Ya"));
    System.out.println(s1+" ends with 'hoo' : "+s1.endsWith("hoo"));
    System.out.println(s1+" starts with 'hoo'(starting from index 2 for comparison) : "+s1.startsWith("hoo",2));
   }
}
READ MORE - Program to demonstrates the - startsWith() and endsWith()

Program to demonstrates the - replace( )

/* Program to demonstrates the - replace( ) */

class replaceDemo
{
    public static void main(String args[ ])
    {
        String s1 = "Bye Bye !!";
        String s2= s1. replace('y','e');

        System.out.println("Original String is : "+s1);
        System.out.println("String after calling relace() : "+s2);
    }
}
READ MORE - Program to demonstrates the - replace( )

Program to demonstrates the - regionMatches( )

/* Program to demonstrates the - regionMatches( ) */

class regionMatchesDemo
{
    public static void main(String args[ ])
    {
            String s1="Java is object oriented Language.";
            String s2="C++ is object oriented Language.";
            String s3="VC++ IS OBJECT ORIENTED LANGUAGE.";
        boolean b ;

        System.out.println("String 1 : "+s1);
        System.out.println("String 2 : "+s2);
        System.out.print(" Comparing some region of s1 and s2...");
        b = s1.regionMatches(8,s2,7,6);
        System.out.println(b);

        System.out.println("\nString 1 : "+s1);
        System.out.println("String 3 : "+s3);
        System.out.print(" Comparing some region of s1 and s3(ignoring case)...");
        b= s1.regionMatches(true,8,s3,8,6);
        System.out.println(b);
    }
}
READ MORE - Program to demonstrates the - regionMatches( )

Read multiple lines from console using a DataInputStream

/* Read multiple lines from console using a DataInputStream */

import java.io.*;   

class ReadDemo3
{
    public static void main(String args[ ]) throws IOException
    {
        //create a DataInputStream using System.in.
                DataInputStream in = new DataInputStream(System.in);   
             String str[] = new String[500];

        System.out.println("Enter lines of text ");
        System.out.println("Enter 'stop' to quit ");
       
        for(int i =0;i<500;i++)
        {
            str[i] = in.readLine( );
            if(str[i].equals("stop")) break;       
        }
        System.out.println("\n Your File is :");
       
        // display the lines
        for(int i =0;i<500;i++)
        {
            if(str[i].equals("stop")) break;
            System.out.println(str[i]);
        }         
    }
}   
READ MORE - Read multiple lines from console using a DataInputStream

Use a DataInputStream to read characters from the console

/* Use a DataInputStream to read characters from the console */

import java.io.DataInputStream;    // load class for reading purpose

class ReadDemo1
{
    public static void main(String args[ ])
    {
        // creating object of class DataInputStream.
                   DataInputStream in = new DataInputStream(System.in);   
                   char c;

        try
        {
            System.out.println("Enter character 'E' to Exit : ");
            // read characters
            do
            {
                c = (char)in.read();
                System.out.println(c);       
            }while(c!='Q');
       
        }
          catch(Exception e)
                { 
                          System.out.println("I/O Error");
                }
    }
}   
READ MORE - Use a DataInputStream to read characters from the console

Read a string from console using a DataInputStream

/* Read a string from console using a DataInputStream */

import java.io.*;   

class ReadDemo2
{
    public static void main(String args[ ]) throws IOException
    {
        //create a DataInputStream using System.in.
                DataInputStream in = new DataInputStream(System.in);   
             String str;

        System.out.println("Enter lines of text ");
        System.out.println("Enter 'stop' to quit ");
       
        do
        {
            str = in.readLine( );
            System.out.println(str);       
        }while(!str.equals("stop"));       
    }
}   
READ MORE - Read a string from console using a DataInputStream

Program to display squares and cubes of first ten numbers

/* Program to display squares and cubes of first ten numbers */

class ForDemo3
{
    public static void main(String args[])
    {
        int num , square , cube ;

        System.out.println("\nThe squares and cubes of first ten numbers :\n");
        System.out.println("=================================================\n\n");
        System.out.println("Number\tSquare\tCube\n");

        for (num=1 ; num<11 ; num++)
        {
            square = num * num ;
            cube = num * square ;
            System.out.println(num+"\t"+square+"\t"+cube);
        }
    }
}
READ MORE - Program to display squares and cubes of first ten numbers

Program To Create Table of 31 to 40

/*  Program To Create Table of 31 to 40  */

import java.io.*;
class Tables
{
 public static void main(String[] arg)
 {
  for(int i=1;i<=10;i++)
   {
    
    for(int j=31;j<=40;j++)
    {
     System.out.printf("%3d |",(j*i));
    }  
   System.out.println(" "); 
  }
  }
}
READ MORE - Program To Create Table of 31 to 40

Program To Create Table of 2 to 10

/*  Program To Create Table of  2  to 10 */
import java.io.*;
class Tables
{
 public static void main(String[] arg)
 {
  for(int i=1;i<=10;i++)
   {
    
    for(int j=2; j<=10;j++)
    {
     System.out.printf("%3d |",(j*i));
    }  
   System.out.println(" "); 
  }
  }
}
READ MORE - Program To Create Table of 2 to 10

Program To Create Table of 11 to 20

/*   Program To Create Table of 11 to 20  */
import java.io.*;
class Tables
{
 public static void main(String[] arg)
 {
  for(int i=1;i<=10;i++)
   {
   
    for(int j=11;j<=20;j++)
    {
     System.out.printf("%3d |",(j*i));
    } 
   System.out.println(" ");
  }
  }
}
READ MORE - Program To Create Table of 11 to 20

using break to exit a for loop

/*  using break to exit a for loop */


class BreakDemo1
{
    public static void main(String args[])
    {
        for(int i =0;i<100;i++)
        {
            if(i==10) break;      //terminate loop if i is 10
            System.out.println("i ="+i);
        }
        System.out.println("End of Loop");
    }
}
READ MORE - using break to exit a for loop

Program to take Input from User

/*  Program to take Input from User */

import java.io.DataInputStream;

class Read
{
    public static void main(String args[])
    {
        int i;
        float f;
        DataInputStream in= new DataInputStream(System.in);
        try
        {
   
        System.out.println("Enter Integer number:");
        i=Integer.parseInt(in.readLine());

        System.out.println("Enter Float number:");
        f = Float.valueof(in.readLine()).floatvalue();
        }
        catch(Exception e)
        {

        }

        System.out.println("Integer Number is : "+i);
        System.out.println("Float Number is : "+f);
    }
}
READ MORE - Program to take Input from User

Program to convert Rs. into paise

/* Program to convert Rs. into paise */

class P17
{
    public static void main(String args[])
    {
        double rs=75.95;
        double paise1,paise2;
   
        paise1= rs*100;       
        System.out.println("Rs."+rs+" = "+(long)paise1+" paise");

        rs= 18.75;
        paise2= rs*100;       
        System.out.println("Rs."+rs+" = "+(long)paise2+" paise");

    }
}
READ MORE - Program to convert Rs. into paise

Program to compute distance light travels

/* Program to compute distance light travels */

class P13
{
    public static void main(String args[])
    {
        int lightspeed;
        long days, seconds,distance;
       
        //approximate speed of light in miles per second
        lightspeed = 186000;
       
        days = 1000; // specify number of days here

        seconds = days * 24 * 60 * 60;    // convert to seconds

        distance = lightspeed * seconds;   // compute distance
   
        System.out.print(" In "+days);
        System.out.print(" days light will travel about ");
        System.out.print(distance+" miles");
    }
}
READ MORE - Program to compute distance light travels

Program to demonstrate Bitwise Logical operators

/* Program to demonstrate Bitwise Logical operators */

class BitLogic
{
    public static void main(String args[])
    {
        int A=35,B=15,C=3;
        System.out.println("A is : "+A);
           System.out.println("B is : "+B);
        System.out.println("A | B  is : "+(A|B));
        System.out.println("A & B  is : "+(A&B));
        System.out.println("A ^ B  is : "+(A^B));
                int D = ~C & 0x0f;
        System.out.println(" ~ C is : "+D);


    }
}
READ MORE - Program to demonstrate Bitwise Logical operators

Program to demonstrate Bitwise Operator Assignments

/* Program to demonstrate Bitwise Operator Assignments */

class BitAssign
{
    public static void main(String args[])
    {
        int A=1,B=2,C=3;

        A |=4;
        B >>=1;
        C <<=1;
        A ^=C;
      
        System.out.println(" A = "+A);
        System.out.println(" B = "+B);
        System.out.println(" C = "+C);
    }
}
READ MORE - Program to demonstrate Bitwise Operator Assignments

Addition and Subtraction of Integer numbers

/*Program to demonstrate the addition and subtraction of Integer numbers*/
 
class AddSubInt
{

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

      System.out.println("i is " + i);
      System.out.println("j is " + j);
 
      int k = i + j;
      System.out.println("i + j is " + k);
   
      k = i - j;
      System.out.println("i - j is " + k);

  }

}
READ MORE - Addition and Subtraction of Integer numbers

Program to demonstrate the addition and subtraction of double numbers


/* Program to demonstrate the addition and subtraction of double numbers*/


class AddSubDoubles
{

     public static void main (String args[]) 
    {

        double x = 7.5;
        double y = 5.4;

        System.out.println("x is : " + x);   
    System.out.println("y is : " + y);
 
        double z = x + y;
        System.out.println("x + y is : " + z);
   
        z = x - y;
        System.out.println("x - y is : " + z);

     }

 }
READ MORE - Program to demonstrate the addition and subtraction of double numbers

program to demonstrates inner class

/* program to demonstrates inner class */

class Outer
{
    int outer_a = 200;

    void show()
    {
        Inner i = new Inner();
        i.display();
    }

    // This is an inner class
    class Inner
    {
        void display()
        {
            System.out.println(" Display variable 'a' of outer class = "+outer_a);
        }
    }
}

class InnerClassDemo
{
    public static void main(String args[])
    {
        Outer o = new Outer();
        o.show();
    }
READ MORE - program to demonstrates inner class

Program to add, delete and print an item in shopping list

/* Program to add, delete and print an item in shopping list  */

import java.util.*;
import java.io.DataInputStream;     // to load DataInputStream class        
   
class P34
{
    public static void main(String args[ ])
    {
        Vector v = new Vector(5,2);
        int count=0,i,choice, position;
        String str = new String();
        boolean flag = false;
        String ans = "yes";
        DataInputStream in = new DataInputStream(System.in);

        count =args.length;
        for(i=0;i<count;i++)
            v.addElement(args[i]);
        try
        {
            System.out.println("\n*********** Super Market **********\n");
            do
            {
            System.out.println("\nSelect Any option (1 to 5)");
            System.out.println("\t1.   Delete an item ");
            System.out.println("\t2.   Add an item at a specific location ");
            System.out.println("\t3.   Add an item at the end of the list ");
            System.out.println("\t4.   Display Shopping List ");
            System.out.println("\t5.   Exit ");
            choice = Integer.parseInt(in.readLine());

            System.out.println();
            switch(choice)
            {
                case 1:
                    /* Delete an Item */
                    System.out.print("Enter the item which you want to delete from shopping list : ");
                    str = in.readLine();
                    flag = v.removeElement(str);
                    if(flag==false)
                         System.out.println(" Item is not in the shopping list");
                    break;
                case 2:
                    /* Add an item at a specific location */
                    System.out.print("Enter the item which you want to add in shopping list : ");
                    str = in.readLine();
                    System.out.print("Enter a specific location where you want to add an item : ");
                    position = Integer.parseInt(in.readLine());
                    v.insertElementAt(str,position-1);
                    break;
                case 3:
                    /* Add an item at the end of the list */
                    System.out.print("Enter the item which you want to add in shopping list : ");
                    str = in.readLine();
                    v.addElement(str);
                    break;
                case 4:
                    /* Display Shopping List */
                    Enumeration vEnum = v.elements();

                     System.out.println("\nItems in Shopping list are:");
                    while(vEnum.hasMoreElements())
                        System.out.println("\t"+vEnum.nextElement() +"   ");
                    //System.out.println();
                    break;
                default:
                    System.exit(0);
            }
            System.out.print("Do you Want to continue ? (Yes/No) : ");
            ans=in.readLine();
            }while(ans.equalsIgnoreCase("yes"));
           
        }
        catch(Exception e)  {   System.out.println("I/O Error");   }

       
    }
}

READ MORE - Program to add, delete and print an item in shopping list

Program that accepts a shopping list of five items from the command line and stores them in a vector

/* Program that accepts a shopping list of five items from the command line and stores them in a vector */

import java.util.*;
   
class P33
{
    public static void main(String args[ ])
    {
        int count=0,i;
        Vector v = new Vector(5,2);

        count =args.length;
        for(i=0;i<count;i++)
            v.addElement(args[i]);

        //****** Enumerate the elements in the Vector *********
        Enumeration vEnum = v.elements();

         System.out.println("\nItems in Shopping list are:");
        while(vEnum.hasMoreElements())
            System.out.println("\t"+vEnum.nextElement() +"   ");
        System.out.println();
    }
}

READ MORE - Program that accepts a shopping list of five items from the command line and stores them in a vector

Program to store various types of objects in Vector

/* Program to store various types of objects in Vector */

import java.util.*;

class Person
{
    String FirstName = new String();
    String LastName = new String();

    Person(String Fname, String Lname)
    {
        FirstName = Fname;   
        LastName = Lname;
    }

    public String toString()
    {
        return ""+FirstName+" "+LastName;
    }
}
       
class P32
{
    public static void main(String args[ ])
    {
        // initial size is 4, increment is 2
        Vector v = new Vector(4,2);

        System.out.println("Initial size : "+v.size());
        System.out.println("Initial Capacity : "+v.capacity());

        v.addElement(new Integer(1));
        v.addElement(new Integer(2));

        v.addElement(new Float(5.25));
       
        Person p1 = new Person("Mahatma","Gandhi");
        v.addElement(p1);

        v.addElement(new Double(20.53));

        Person p2 = new Person("Abdul","Kalam");
        v.addElement(p2);

        v.addElement(new Integer(3));


        System.out.println("\nFirst element :"+(Integer)v.firstElement());
        System.out.println("Last element :"+(Integer)v.lastElement());


        //****** Enumerate the elements in the Vector *********
        Enumeration vEnum = v.elements();

         System.out.println("\nElements in vector :");
        while(vEnum.hasMoreElements())
            System.out.println(vEnum.nextElement() +"   ");
        System.out.println();
    }
}

READ MORE - Program to store various types of objects in Vector

Program that throws a 'NoMatchException' when a string is not equal to “India”

/* Program that throws a 'NoMatchException' when a string is not equal to “India” */

class NoMatchException extends Exception
{
    private String str;
   
    NoMatchException(String str1)
    {
        str=str1;
    }

    public String toString()
    {
        return "NoMatchException --> String is not India and string is "+str;
    }
}

class P31
{   
       
    public static void main(String args[ ])
    {
        String str1= new String("India");
        String str2= new String("Pakistan");   
           
        try
        {
            if(str1.equals("India"))           
                System.out.println(" String is : "+str1);
            else           
           
                throw new NoMatchException(str1);
           
            if(str2.equals("India"))
                System.out.println("\n String is : "+str2);
            else
                throw new NoMatchException(str2);            
        }
        catch(NoMatchException e)
        {
            System.out.println("\nCaught ...."+e);
        }
    }
}       
READ MORE - Program that throws a 'NoMatchException' when a string is not equal to “India”

Program to demonstrates try and multiple catch

/* Program to demonstrates try and multiple catch  */

import java.io.DataInputStream;     // to load DataInputStream class        

class P30
{
    public static void main(String args[])
    {
        int result,no1,no2=20,position;
        int arr[]= new int[20];
        DataInputStream in = new DataInputStream(System.in);
        try
        {
            System.out.print("Enter number : ");
            no1= Integer.parseInt(in.readLine());
            result = no2/no1;
            System.out.println(no2+"/"+no1+" = "+result);
           
            System.out.print("Enter position of array where you want to store result : ");
            position = Integer.parseInt(in.readLine());
            if(position>20)
                throw new ArrayIndexOutOfBoundsException("Demo");
            if(position<0)
                throw new NegativeArraySizeException("Demo");
            arr[position]=result;   
        }
        catch(ArithmeticException e)
        {
            System.out.println(" Division by zero --> "+e);
            result=0;
            System.out.println(" Result is : "+result);
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println(" Array size is 20 --> "+e);
        }
        catch(NegativeArraySizeException e)
        {
            System.out.println(" Array size should be positive --> "+e);
        }
        catch(Exception e)
        {
            System.out.println("I/O Error");  
        }
         System.out.println("End of program..... ");
    }
}

   
READ MORE - Program to demonstrates try and multiple catch

Program which uses toStirng() method

/* Program which uses toStirng() method   */

import java.io.DataInputStream;     // to load DataInputStream class        

class Person
{
    String FirstName = new String();
    String LastName = new String();

    Person(String Fname, String Lname)
    {
        FirstName = Fname;   
        LastName = Lname;
    }

    public String toString()
    {
        return " Name of Person is : "+FirstName+" "+LastName+".";
    }
}
       
class P29
{
    public static void main(String args[ ])
    {
        Person p = new Person("Abdul","Kalam");
        System.out.println(p);
    }
}
READ MORE - Program which uses toStirng() method

Program to sort a list of sir names

/* Program to sort a list of sir names   */

import java.io.DataInputStream;     // to load DataInputStream class        

class P28
{
    public static void main(String args[ ])
    {
        String str[]=new String[5];
        int i,j,len=0;
       
        DataInputStream in = new DataInputStream(System.in);

        try
        {
             for(i=0;i<5;i++)
             {
                 System.out.print(" Enter Sirname of Student "+(i+1)+" : ");
                 str[i] = in.readLine();
             }
        }
        catch(Exception e) {  System.out.println("I/O Error");   }

        System.out.println(" Sorted list is : ");
        for(j =0;j<str.length;j++)
        {
            for(i = j+1;i<str.length;i++)
            {
                if(str[i].compareTo(str[j])<0)
                {
                    String t=str[j];
                    str[j]=str[i];
                    str[i]=t;
                }
            }
            System.out.println("\t"+str[j]);
        }
    }
}
 
READ MORE - Program to sort a list of sir names

Program for Question-Answer

/* Program for Question-Answer */

import java.io.DataInputStream;     // to load DataInputStream class        

class P26
{
    public static void main(String args[ ])
    {
        String ans = new String();
        boolean flag=false;
        DataInputStream in = new DataInputStream(System.in);

        System.out.println("You have only three attempts to give answer of following Question");
        for(int i=0;i<3;i++)
        {
            try
            {
                 System.out.print(" Who is the inventor of C++ ? : ");
                 ans = in.readLine();
            }
            catch(Exception e) {  System.out.println("I/O Error");   }

            if(ans.equals("Bjarne Stroustrup")||ans.equals("bjarne stroustrup"))
            {
                System.out.println(" Good ");
                flag = true;
                break;
            }
            else if(i<=1)
                    System.out.println(" Try again..... ");
        }

        if(flag==false)
        {
            System.out.println("\n Your three attempts are over..... ");
            System.out.println("\n C++ was invented by Bjarne Stroustrup in 1979");
        }
    }
}           
           
READ MORE - Program for Question-Answer

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|