• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Java

Frame Java Example

By Dinesh Thakur

The java.awt.Frame component is a Windows graphics system which has a title bar and borders, behaving like a normal GUI window. How is a subclass of java.awt.Container can contain other components being that its primary purpose. The default alignment components added to a Java.awt.BorderLayout.

When working with Frame objects, the following steps are basically followed to get a window to appear on the screen.

1. Create an object of type Frame.

2. Give the Frame object a size using setSize () method.

3. Make the Frame object appear on the screen by calling setVisible () method.

4. In order to close the window by clicking the close(X) button, you will have to insert the code for window closing event.

Following is a table that lists some of the methods of this class:

 

Method

Description

Frame ()

Constructs a new instance, invisible and without title.

Frame (String)

Constructs a new instance, invisible and entitled given

dispose ()

Releases the resources used by this component

getTitle ()

Gets the title of the window.

isResizable ()

Determines whether or not the window is sizable.

setMenuBa (MenuBar)

Adds the specified menu bar of the window.

setResizable (Boolean)

Specifies whether or not the window is sizable.

setTitle (String)

Specifies the window title.

import java.awt.*; 
import java.awt.event.*;
class FrameJavaExample
{
    public static void main (String args[])
    {
             Frame frame = new Frame("Frame Java Example");
             //set the size of the frame
             frame.setSize(300,250);
             frame.addWindowListener(new WindowAdapter()
                          {
                             public void windowClosing(WindowEvent e)
                              {
                                System.exit(0);
                               }
                           });
                            frame.setVisible(true);
     }
}

Frame Java Example

SequenceInputStream in Java Example

By Dinesh Thakur

The SequencelnputStream class allows you to concatenate (or combine) two or more input streams serially and make them appear as if they were a single input stream. Each input stream is read beginning from the first one until end of file (EOF) is reached, where upon it reads from the second one and so on, until end of file is reached on the last of the contained input streams.

In order to create SequencelnputStream, the following two constructors are provided.

SequencelnputStream(IntputStream s1, InputStream s2)

This constructor creates a SequencelnputStream that reads from the InputStream s1 until its EOF is reached, then closes it and switched to reading from InputStream s2 until itsEOF is reached.

SequencelnputStream(Enumeration e)

This constructor creates a SequencelnputStream initialized to the specified enumeration of InputStreams.

Now let us consider a program that uses SequencelnputStream to concatenate two files.

import java.io.*;  
class SequenceInputStreamExample
{
     public static void main(String[] args)
    {
        int ch;
        try
        {
          FileInputStream file1 = new  FileInputStream  ("std.dat");
          FileInputStream file2 = new FileInputStream  ("mydata.dat");
          SequenceInputStream fin=new SequenceInputStream(file1,file2);
          while((ch=fin.read())!=-1)
              System.out.println(ch);
              fin.close();
          }
          catch(IOException e)  { e.printStackTrace(); }
        }
     }

PrintWrite in Java Example

By Dinesh Thakur

The java.io.PrintWriter is another very convenient I/O class that makes writing text to a file as easy as writing text to the console. The PrintWri ter class defines several constructors, the one we would be using is as follows.

Printwriter(OutputStream oStream, boolean autoFlush)

Here, oStreamis an object oftype OutputStream and autoFlush is an boolean variable which if set to true flushes the output stream every time a prin tln () method is invoked.

PrintWriter includes different versions of the print () and prin tln () methods of all types such as int, float etc. including Object. Thus, you can use these methods in the same way as they have been used in System. out. If the argument is not a primitive type, the printWriter methods will call the Object’s toString () method and then print out the result.

Now let us consider a program that reads lines of text typed at the keyboard and then writes the same text into a file by appending a line number at the front of each line.

import java.io.*; 
import java.util.Scanner;
public class PrintWriterExample
{
      public static void main(String[] args) throws FileNotFoundException
      {
         Scanner input = new Scanner(System.in);
         System.out.println("Enter Name of File to Read : ");
         String inputfileName = input.next();
         System.out.print("Enter Name of File in Which Data to be Written : ");
         String outputfileName = input.next();
         FileReader reader = new FileReader(inputfileName);
         Scanner in = new Scanner(reader);
         PrintWriter out = new PrintWriter(outputfileName);
         int lineNumber = 1;
         while (in.hasNext())
         {
              String line = in.nextLine();
              out.print(lineNumber + " : " + line);
              lineNumber++;
         }
             System.out.println("Data Written Successfully");
      }
   }

PrintWrite in Java Example

BufferedReader and Writer Example in Java

By Dinesh Thakur

The java.io.BufferedReader and java.io.BufferedWriter classes are the character based equivalents of the byte oriented BufferedlnputStream and BufferedOutputStream classes.

When a program reads from a BufferedReader, text is taken from buffer (a block of memory) rather than directly from the underlying input stream until the buffer is empty. At this point, a read request to the underlying character stream extracts a new block of data, which refills the buffer. When a program writes to a BufferedWriter, the text is placed in the buffer. The text is moved to the underlying output stream or other target only when the buffer files ·up or when the writer is explicitly flushed, which can make writes much faster than would otherwise.

In order to create BufferedReader, one of the following two constructors can be used.

BufferedReader(Reader in}

BufferedReader(Reader in, int bufferSize}

The first argument in is Reader object which is the underlying character input stream from which data will be read. If the buffer size is not set, the default size of 8192 characters is used. Similarly, to create BufferedWriter, one of the following two constructors are used.

BufferedWriter(Writer out)

BUfferedWriter(Writer out, int bufferSize}

The first argument out isa Writer object which is the underlying character output stream to which buffered data is written. If buffer size is not set, the default size of 8192 characters is used. The BufferedReader and BufferedWriter classes have the usual methods associated with Reader and Writer classes like read () , wri te (), close () etc. In addition, they also provide the following methods.

• String readLine () : The readLine () method of the BufferedReader class reads a single line of text and returns it as a string. The return string is null when the operation attempts to read past the end of the file (EOF).

• void newline () .: The newLine () method of the BufferedWri ter class sends the preferred end of line character (or characters) for the platform being used to run the program.

Now let us consider a program that reads a file and converts its contents to uppercase and write them to a new file.

import java.io.*;       
public class BufferedReaderWriter
{
       public static void main(String[] args)
       {
             try
            {
                   BufferedReader br = new BufferedReader(new FileReader("java.txt"));
                   BufferedWriter bw = new BufferedWriter(new FileWriter("java1.txt"));
                   int ch;
                   while ((ch = br.read()) != -1)
                           {  
                                 if (Character.isLowerCase((char) ch))
                                    bw.write(Character.toUpperCase((char) ch));
                                 else
                                         bw.write((char) ch);
                           }
                                 br.close();
                                 bw.close();
            }
                                 catch(Exception e) { e.printStackTrace();}
        }
}

BufferedReader and Writer Example in Java

FileReader and FileWriter in Java Example

By Dinesh Thakur

Java provides java.io.FileReader and java.io.FileWriter classes for reading from and writing characters to a file. The FileReader and FileWri ter classes can be used almost identically to the FileInputStream and FileOutputStream character stream classes.

In order to open a file for reading characters, create a FileReader object. For this, the FileReader class provides the following commonly used constructors,

• FileReader(File fileObj)

• FileReader(String filename)

Here, filename specifies the name of the file and fileObj is a file object that describes the file. If the file to be opened doesnot exist, both these constructors throw java.io.FileNotFoundException.

In order to open a file for writing characters, create a FileWriter object. For this, FileWriter class provides the following commonly used constructors

FileWriter(File file obj)

FileWriter(String filename)

FileWriter(File fileObj, boolean append)

FileWriter(String filename, boolean append)

Here, filename specifies the name of the file and fileObj is a file object that describes the file. If the file doesnot exist, a new file would be created. If the file exists, the first two constructors overwrite the existing contents of the file. To retain the existing contents and append the new data at the end of the file, use the last two constructors and set the second argument append to true.

These constructors throw an IOException on failure.

Now let us consider a program that writes some text into a file and then reads the contents of the file character by character

import java.io.*; 
class FileReaderWriter
{
      public static void main(String[] args)
     {
         int ch;
         String str="Welcome Java World";
         try
         {
           FileWriter fileWrite = new FileWriter("java.txt");  
           fileWrite.write(str);
           fileWrite.close();
         }
         catch(IOException e)  { e.printStackTrace();}
         try
         {
              FileReader fileRead=new FileReader("java.txt");
              while((ch=fileRead.read())!=-1)
              System.out.print((char)ch);
              fileRead.close();
          }
              catch(IOException e)  { e.printStackTrace();}
      }
}

FileReader and FileWriter in Java Example

RandomAccessFile in Java Examples

By Dinesh Thakur

Java also allows you to access the contents of a file in random order i.e. data items can be read and written in any order. This is especially useful in direct access applications such as banking systems, airline reservation systems, Automatic Teller Machine (ATM) etc. where the desired information must be located immediately. Random access files (or direct access files) are analogous to arrays, where each element is accessed directly by means of its index number. Java provides java.io.RandomAccessFile class that enables you to perform random access file input and output operations as opposed to sequential file I/O offered by ByteStream and CharacterStream classes.

When a data file is opened for random read and write access, an internal file pointer is set at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data item. For example, when reading an in t value using readlnt() , 4 bytes are read from the file and the file pointer moves 4 bytes ahead from the previous file pointer position.

Similarly, when reading a double value using readDouble () , 8 byte are read from the file pointer and the file pointer moves 8 bytes ahead from the previous file pointer position.

import java.io.*; 
class RandomFileExample
{
     public static void main(String[] args)
    {
          try
          {
        
              RandomAccessFile file = new RandomAccessFile("std.dat","rw");    
              file.setLength(0);
              for(int i=0;i<50;i++)
                   file.writeInt(i);
                   System.out.println("Length of File After Writing Data is : "+file.length());
                   file.seek(0);
                   System.out.println("First Number is : "+file.readInt());
                   file.seek(1*4);
                   System.out.println("Second Number is : "+file.readInt());
                   file.writeInt(101);
                   file.seek(file.length());
                   file.writeInt(50);
                   System.out.println("Current Length of File is : "+file.length());
          }
                   catch(Exception e)
                  {
                        e.printStackTrace();
                  }
    }
}

RandomAccessFile in Java Examples

ObjectIOStream in Java Example

By Dinesh Thakur

Java also supports writing and reading objects to stream (such as a file). The process of reading and writing objects in a file is called object serialization. Writing an object to a file is called serializing the object and reading the object back from a file is called deserializing an object. In Java, serialization occurs automatically. Objects can be converted into a sequence of bytes, or serialized, by using the java.io.ObjectOutputStream class and they can be deserialized or converted from bytes into a structured object, by using java.io.ObjectlnputStream class.

import java.io.*; 
class Employee implements Serializable
{      
     int empid;
     String ename;
     double salary;  
     Employee(int id,String name,double sal)
     {      
       empid = id;
       ename = name;
       salary = sal;
     }
     void showInformation()
     {
       System.out.println("Empid : " + empid);
       System.out.println("Empid : " + ename);
       System.out.println("Salary : " + salary);
       System.out.println();
     }
}
     
class ObjectIOStreamExample
{
       public static void main(String[] args)
       {          
           Employee empData[] = {new Employee(1,"Dinesh",50000),
                             new Employee(2,"Shubhra",15000),
                             new Employee(3,"Punar",26000) };
           try
           {   
                FileOutputStream fout = new FileOutputStream("std.dat");
                ObjectOutputStream objOut = new ObjectOutputStream(fout);
                for(int i=0; i<empData.length;i++)
                      objOut.writeObject(empData[i]);
                      objOut.close();
           }
           catch(Exception e){e.printStackTrace();}
           try
           {           
              FileInputStream fin = new FileInputStream("std.dat");
              ObjectInputStream objIn = new ObjectInputStream(fin);          
              Employee emp = (Employee) objIn.readObject();
              emp.showInformation();
              emp = (Employee) objIn.readObject();
              emp.showInformation();
              emp = (Employee) objIn.readObject();
              emp.showInformation();            
              objIn.close();
           }
           catch(Exception e){e.printStackTrace();}
        }
}

ObjectIOStream in Java Example

BufferedInputStream , BufferedOutputStream in java example

By Dinesh Thakur

The BufferedOutputStream class is a subclass of FilterOutputStream that stores written data in an internal buffer (a protected byte array field named buf) until the buffer is full or the stream is explicitly flushed using the flush ()method. Then it writes the data onto the underlying output stream all at once. This class does not declare any new methods of its own, rather all the methods are inherited from the OutputStream class.

The BufferedIntputStream class is a subclass of FilterlnputStream which reads as many data as possible into its internal buffer (a protected byte array field named buf) in a single read () call and then each read ()call reads data from the buffer instead of the underlying stream. When the buffer runs out of data, the buffered stream refills its buffer from the underlying stream. This class does not declare any new methods of its own, rather all the methods are inherited from the InputStream class.

import java.io.*; 
class BufferIOStreamExample
{
    public static void main(String[] args)
    {
      int ch;
         try
         {
                FileOutputStream fout=new FileOutputStream("std.dat");
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                for(int i=1;i<=10;i++)
                     bout.write(i*i);
                     bout.close();
          }
                     catch(IOException e)  { e.printStackTrace(); }
         try
         {
                     FileInputStream fin=new FileInputStream("std.dat");
                     BufferedInputStream bin = new BufferedInputStream(fin);
                     while((ch=bin.read())!=-1)
                     System.out.print(ch +" ");
                     bin.close();
         }
                     catch(IOException e)  { e.printStackTrace(); }
    }
}

BufferedInputStream , BufferedOutputStream in java example

DataInputStrem, DataOutputStream in Java Example

By Dinesh Thakur

When you need to process primitive types, Java provides DatalnputStream and DataOutputStream classes.

The DatalnputStream class is a subclass of FilterlnputStream that reads bytes from a stream and converts them into appropriate primitive type values or strings.

The DatalnputStream class implements the Datalnput interface that defines the methods for reading primitive types values or strings from a byte input stream.

import java.io.*; 
class DataIOStreamExample
{
    public static void main(String[] args)
   {
       try
      {
         
          FileOutputStream fin=new FileOutputStream ("Std.dat");
          DataOutputStream din = new DataOutputStream(fin);
          din.writeInt(101);
          din.writeUTF("Dinesh Thakur");
          din.writeDouble(99.5);
          din.writeLong(98765432);
          din.close();
       }
          catch(IOException e)  { e.printStackTrace();} 
       try
      {
          FileInputStream fin=new FileInputStream("std.dat");
          DataInputStream din=new DataInputStream(fin);
          System.out.println("Roll Number : " + din.readInt());
          System.out.println("Name : "+din.readUTF());      
          System.out.println("Percentage : "+ din.readDouble());
          System.out.println("Phone Number :"+  din.readLong());
          din.close();
       }
          catch(IOException e)  { e.printStackTrace(); }
    }
}

DataInputStrem, DataOutputStream in Java Example

Write byte array to a file using FileOutputStream | Java Examples

By Dinesh Thakur

In this Java Example in the main () method of the class FileIOStream, an instance fileOutput of FileOutputStream is created to write to the file mydata.dat. Then using the for loop, we write the square of the value stored in the index variable i using the write () method to the file mydata.dat. The output stream is then closed by calling the close () method.

In order to read bytes from the file mydata.dat, we create an instance filelnput of the FilelnputStream class. We then read the bytes from the mydata.dat file one by one and display it on the screen. For this, we use the while loop in which the expression

(ch = filelnput.read())!= -1

reads a byte from the input stream, assigns it to the variable ch and checks whether it is -1 or not. If it is not equal to -1 then the byte is displayed on the screen. If ch = -1 then it indicates that end of file (EOF) is reached and the loop terminates. Finally, the program closes the input stream and terminates.

import java.io.*; 
class FileIOStream
{
          public static void main(String[] args)
      {
             int ch; 
             try
            { 
                 //Create an instance of the output statream
                 FileOutputStream fileOutput = new FileOutputStream("mydata.dat");
                 //write data to the stream
                for(int i=1;i<=10;i++)
                    fileOutput.write(i);
                    fileOutput.close(); //close the output stream
            }
            catch(IOException e)   { e.printStackTrace(); }
            try
           {
                //Create an instance of the input stream
                FileInputStream fileInput=new FileInputStream("mydata.dat");
                //reading data from a file, unil Eof is reached
                while((ch=fileInput.read())!= -1)
                System.out.print(ch + " ");
                fileInput.close(); //close the input stream
           }
           catch(IOException e)  { e.printStackTrace(); }
      }
}

Write byte array to a file using FileOutputStream

File Class Methods in Java with Examples

By Dinesh Thakur

In order in create File object, the File class provides the following constructors.

• File (String pathname): Creates a File object associated with the file or directory specified by pathname. The pathname can contain path information as well as a file or directory name.

To create an object for the file named HelloJavaExample.java in the current directory (java) in the Window OS, use the following statements.

For absolute path,

File file = new File(“C:\\java\\ HelloJavaExample.java”);

For relative path,

File file = new File(“HelloJavaExample.java”);

• File (File dir, String name) Creates a File object with the given file or directory name in the directory specified by the dir parameter of type File. If the dir parameter is null, this constructor then creates a File object using the current directory. For example, the statement

File dir = new File(“C:/java/classes”);

File f2 = new File(dir, ” HelloJavaExample.java”);

creates a File object f2 with the filename HelloJavaExample.java existing in the directory specified by File object dir.

import java.io.*; 
 class FileCreate
 {
            public static void main(String[] args)
       {
                 File file = new File("HelloJavaExample.java");
                 System.out.println("File Exists : "+file.exists());
                 System.out.println("Length of File is : "+file.length());
                 System.out.println("Can Read File : "+file.canRead());
                 System.out.println("Can Write to File : "+file.canWrite());
                 System.out.println("whether File is a Directory : "+file.isDirectory());
                 System.out.println("whether File is a File : "+file.isFile());
                 System.out.println("File name is : "+file.getName());
                 System.out.println("File absolute path is : "+file.getAbsolutePath());
                 System.out.println("File path is : "+file.getPath());
                 System.out.println("File parent directory is : "+file.getParent());
                 System.out.println("File last modified on : "+ new java.util.Date(file.lastModified()));
 
        }
}

File Class Methods in Java with Examples

Calculate Average of Three Variables Using Classes in Java Example

By Dinesh Thakur

[Read more…] about Calculate Average of Three Variables Using Classes in Java Example

Java Example to Calculate Area of Rectangle Using Classes, Values Not Given

By Dinesh Thakur

[Read more…] about Java Example to Calculate Area of Rectangle Using Classes, Values Not Given

Calculate Area of Rectangle Using Class in Java Example

By Dinesh Thakur

In this Java Example we declares a class named Rect. It contains two integer member variables, l and b (for length and breadth). Since no access specifier is used, these variables are considered public. Public means that any other class can freely access these two members.

We create an object by name rect of class Rect by instantiating the class. When we create a new object, space is allocated for that object and for its member’s l and b. Then the values are assigned to l and b variables as 20 and 60 respectively. After this, the variables l and b of object rect are multiplied and the result is stored in variable a which is then displayed on the screen.

class Rect
{
            int l,b;
}
class CalAreaofRectangle
{
            public static void main (String args[])
            {
                        int a;
                        Rect rect = new Rect();
                        rect.l=20;
                        rect.b=60;
                        a=rect.l*rect.b;
                        System.out.println("Area of Rectangle is : "+a);
            }
}

Calculate Area of Rectangle Using Class

In previous, Java example, the object rect directly allows to assign values to its data members l and b in main() because both are considered public:

rect.l=20;

rect.b=60;

In the following example, the values of the data members l and b are changed with the help of method: setval()

class Rect 
{
            int l,b;
            void setval(int x,int y)
            {
                        l=x;
                        b=y;
            }
            int area()
            {
                        return (l*b);
            }
};
class CalculateAreaofRectangle
{
           
            public static void main (String args[])
            {
                        Rect rect = new Rect();
                        rect.setval (50,8);
                        System.out.println("Area of Rectangle is : "+rect.area());
            }
};

Calculate Area of Rectangle Using Class in Java Example

To set the values of the variables l and b, we use this method:

rect.setval(20,10);

This Java statement calls rect’s setval method with two integer parameters 20 and 10 and that method assigns new values to variables l and b respectively.

We append the method name to an object reference with an intervening period (.). Also, we provide any arguments to the method within enclosing parentheses. If the method does not require any arguments, use empty parentheses. Syntax for calling a method through object:

objectReference.methodN ame(argument List);

or

objectReference.methodName();

ObjectReference must be a reference to an object.

Example:

rect.area();

We can use the dot notation to call the area() method to compute the area of the new rectangle.

StringBuffer Class in Java Example

By Dinesh Thakur

StringBuffer represents grow able and write able character sequences. We can modify the StringBuffer object, i.e. we can append more characters or may insert a substring in middle. StringBuffer will automatically grow to make room for such additions and is very flexible to the modifications.

StringBuffer Constructors

 

StringBuffer defines these three constructors:

StringBuffer()

It reserves room for 16 characters without reallocation.

StringBuffer(int size)

It accepts an integer argument that explicitly sets the size of the buffer.

StringBuffer(String str)

It accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.

length( ) and capacity( )

The current length of a StringBuffer can be found by the length() method, while the total allocated capacity can be found through the capacity() method.

Syntax:

int length()

int capacity()

ensureCapacity( )

If we want to preallocate room for a certain number of characters after a StringBuffer has been constructed, we can use ensureCapacity() to set the size of the buffer.

Syntax:

void ensureCapacity(int capacity)

Here, capacity specifies the size of the buffer.

setLength()

It is used to set the length of the buffer within a StringBuffer object.

Syntax:

void setLength(int len)

Here, len specifies the length of the buffer. This value must be nonnegative. When we increase the size of the buffer, null characters are added to the end of the existing buffer. If we call setLength() with a value less than the current value returned by length(), then the characters stored beyond the new length will be lost.

charAt() and setCharAt( )

A single character can be obtained from a StringBuffer by the charAt() method. We can even set the value of a character within a StringBuffer using setCharAt().

Syntax:

char charAt(int loe}

void setCharAt(int loc, char ch)

loc specifies the location of the character being obtained. For setCharAt(), loc specifies the location of the character being set, and ch specifies the new value of that character. For both methods, loc must be nonnegative and must not specify a location beyond the end of the buffer.

getChars()

To copy a substring of a StringBuffer into an array, use the getChars() method.

Syntax:

void getChars(int si, int e, char t[ ], int ti)

Here, si specifies the index of the beginning of the substring, and e specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from si through e-l. The array that will receive the characters is specified by t. The index within t at which the substring will be copied is passed in ti.

append( )

The append() method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object..

Syntax:

StringBuffer append(String str)

StringBuffer append(int num)

StringBuffer append(Object obf)

String.valueOf() is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append().

The append() method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokes append() on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString() to turn the modifiable StringBuffer back into a constant String

import java.io.*;
public class ReversedString
{
            public static String reverseIt(String s)
            {
                        int i, n;
                        n = s.length();
                        StringBuffer d = new StringBuffer(n);
                        for (i = n - 1; i >= 0; i--)
                                    d.append(s.charAt(i));
                        return d.toString();
            }
            public static void main (String args[]) throws IOException
            {
                        BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
                        String p,q;
                        System.out.println("Enter a string");
                        p=k.readLine();
                        q=reverseIt(p);
                        System.out.println("Original String is "+p);
                        System.out.println("Reversed String is "+q);
            }
}

Insert()

The insert() method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append(), it calls String.valueOf () to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object.

Syntax:

StringBuffer insert(int loc, String str)

StringBuffer insert(int loc, char ch)

StringBuffer insert(int loc, Object obj)

Here, loc specifies the location at which point the string will be inserted into the invoking StringBuffer object.

public class StringInsert           
{
          public static void main(String args[])
            {
                        StringBuffer sb = new StringBuffer(" in ");
                        sb.append("God");
                        sb.append('!');
                        sb.insert(0,"Beleive");
                                sb.append('\n');
                        sb.append("God is Great");
                        sb.setCharAt(20,'I');
                        String s = sb.toString();
                        System.out.println(s);
            }
}

reverse()

 

We can reverse the characters within a StringBuffer object using reverse()·

import java.io.*;
class StringReverse
{
            public static void main(String args[])
            {
                        StringBuffer k=new StringBuffer("Hello Java");
                        System.out.println(k);
                        k.reverse();
                        System.out.println(k);
            }
}

delete( ) and deleteCharAt( )

StringBuffer delete(int s, int e)

StringBuffer deleteCharAt(int loc)

The delete() method deletes a sequence of characters from the invoking object. Here, s specifies the starting location of the first character to remove, and e specifies location one past the last character to remove. Thus, the substring deleted runs from s to e-l. The resulting StringBuffer object is returned.

The deleteCharAt() method deletes the character at the location specified by loco It returns the resulting StringBuffer object.

Replace()

It replaces one set of characters with another set inside a StringBuffer object.

Syntax:

StringBuffer replace(int s, int e, String str)

The substring being replaced is specified by the location sand e. Thus, the substring at s through e-l is replaced by str string.

substring( )

It returns a portion of a StringBuffer.

Syntax:

String substring(int s)

String substring(int s, int e)

The first form returns the substring that starts at s and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at s and runs through e-l.

public class StringBuffer2 
{
            public static void main (String args[])
            {
                        StringBuffer p= new StringBuffer("God is Great");
                        char k[] = new char[20];
                        char q;
                        p.getChars(7,11,k,0);
                        System.out.println("Original string is "+p);
                        p.delete(4,6);
                        System.out.println("string after deleting a word "+p);
                        p.insert(4,"is");
                        System.out.println("string after inserting a word "+p);
                        p.deleteCharAt(4);
                        System.out.println("string after deleting a character"+p);
                        p.replace(4,5,"always");
                        System.out.println("string after replacing a word is "+p);
                        q=p.charAt(0);
                        System.out.println("the first character of string is "+q);
            }
}

String Classes in Java Examples

By Dinesh Thakur

[Read more…] about String Classes in Java Examples

String Comparison in Java Example

By Dinesh Thakur

The String class includes several methods that compare strings or substrings within strings. To perform a comparison that ignores case differences, use equalsIgnoreCase(). This method considers lowercase and upper case characters as same while comparing strings. That is, it considers A-Z to be the same as a-z.

Syntax:

boolean equalsIgnoreCase(String str)

 

Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise.

import java.io.*; 
class StringComparison
{
            public static void main(String args[]) throws IOException
            {
                        BufferedReader dd=new BufferedReader(new InputStreamReader(System.in));
                        String ww;
                        System.out.println("Enter Few Strings or Enter stop to Exit ");
                        do
                        {
                                    ww=dd.readLine();     
                        }while(!ww.equalsIgnoreCase("stop"));
            }
}

String Comparison in Java Example

String Concatenation in Java Example

By Dinesh Thakur

Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. We can also concatenate strings with other types of data after converting them into strings. Java converts other data types into its string representation by calling valueOf() defined by String. For the simple types, valueOf() returns a string equivalent of the value with which it is called. For objects, valueOf()calls the toString() method on the object.

String Concatenation in Java Example

Here is an example in which unite several strings :

String first = “Hello”;

String second = “Java”;

System.out.println (first + second); / / HelloJava

String output = first + second + “”;

int number = 2 ;

System.out.println (output + number);

/ / HelloJava 2

In the example, initialize two variables of type String and asked them values. On the third line joining the two strings and file the results – the method println (), in order to print it on the bracket, next line joining the two strings and add a space at the end. returned result recorded in a variable called output. The last line unite the contents of the output string with the number 2 (the content of variable number) and file the result again to print. The returned result will be automatically converted to type String, because the two variables are of a different type .

Concatenation (adhesion of two strings ) strings is slow operation and should be used carefully . The use of Class StringBuilder StringBuffer or in need of iterative ( repetitive ) operations on strings .

class StringConcat         
{
            public static void main(String args[])
            {
                        String t = "Hello ";
                        String m = "Java";
                        System.out.println(t+ m);
            }
}

String Concatenation in Java Example

Multiplication of Two Matrix in Java Example

By Dinesh Thakur

[Read more…] about Multiplication of Two Matrix in Java Example

Java Example to Find the Sum of Two 3×3 Matrices

By Dinesh Thakur

Matrix addition means addition of respective positions. That is, element of 0th row 0th column of first matrix will be added with 0th row and 0th column of second matrix and placed in resultant matrix at 0th row and 0th column position. And this way all the element positions of first matrix are added with the respective positions of second matrix and stored in resultant matrix at the same position.

import java.io.*;
class AddMatrix
{
            public static void main(String args[])
            throws IOException
            {
                        BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
                        int m1[][]=new int[3][3];
                        int m2[][]=new int[3][3];
                        int m3[][]=new int[3][3];
                        int i,j;
                        String m;
                        System.out.println("Enter Elements of First Matrix of Order 3 x 3");
                        for(i=0;i<=2;i++)
                        {
                                    for(j=0;j<=2;j++)
                                    {
                                                m=k.readLine();
                                                m1[i][j]=Integer.parseInt(m);
                                    }
                        }
                        System.out.println("Enter Elements of Second Matrix of Order 3 x 3");
                        for(i=0;i<=2;i++)
                        {
                                    for(j=0;j<=2;j++)
                                    {
                                                m=k.readLine();
                                                m2[i][j]=Integer.parseInt(m);
                                    }
                        }
                        for(i=0;i<=2;i++)
                        {
                                    for(j=0;j<=2;j++)
                                    {
                                                m3[i][j]=m1[i][j]+m2[i][j];
                                    }
                        }
                        System.out.println("The First Matrix Entered is ");
                        for(i=0;i<=2;i++)
                        {
                                    for(j=0;j<=2;j++)
                                    {
                                                System.out.print(m1[i][j]+"\t");
                                    }
                                    System.out.println();
                        }
                        System.out.println("The Second Matrix Entered is ");
                        for(i=0;i<=2;i++)
                        {
                                    for(j=0;j<=2;j++)
                                    {
                                                System.out.print(m2[i][j]+"\t");
                                    }
                                    System.out.println();
                        }
                        System.out.println("The Addition of Matrix is ");
                        for(i=0;i<=2;i++)
                        {
                                    for(j=0;j<=2;j++)
                                    {
                                                System.out.print(m3[i][j]+"\t");
                                    }
                                    System.out.println();
                        }
            }
}

Java Example to Find the Sum of Two 3x3 Matrices

 

One of the another Example we can see.

 

import java.io.*; 
 class matrix
    {
          int h[][]=new int[3][3];
          void setmat() throws IOException
             {
                 int i,j;
                 BufferedReader gg=new BufferedReader(new InputStreamReader(System.in));
                 String m;
                 for(i=0;i<=2;i++)
                   {
                     for(j=0;j<=2;j++)
                       {
                         m=gg.readLine();
                         h[i][j]=Integer.parseInt(m);
                       }
                  }
             }
                      void showmat()
                      {
                         int i,j;
                        for(i=0;i<=2;i++)
                          {
                            for(j=0;j<=2;j++)
                                {
                                    System.out.print(h[i][j]+"\t");  
                                }
                                    System.out.println();
                           } 
                       }
                                  void addmat(matrix u, matrix v)
                                            {
                                                int i,j;
                                                for(i=0;i<=2;i++)
                                                    {
                                                       for(j=0;j<=2;j++)
                                                          {
                                                             h[i][j]=u.h[i][j]+v.h[i][j];
                                                           }
                                                    }
                                            }
                                              
     };
        class mataddclass
          {
               public static void main(String args[])
                {
                    matrix ml=new matrix();
                    matrix m2=new matrix();
                    matrix m3=new matrix();
                    System.out.println("Enter elements for matrix l of order 3x3:");
                    try
                     {
                      ml.setmat();
                     }
                          catch(IOException e){}
                          System.out.println("Enter elements for matrix 2 of order 3x3:");
                           try
                             {
                              m2.setmat();
                             }
                              catch(IOException e){}
                              m3.addmat(ml,m2);
                              System.out.println("Elements of first matrix are ");
                              ml.showmat();
                              System.out.println("Elements of second matrix are ");
                              m2.showmat();
                              System.out.println("Addition of matrices are ");
                              m3.showmat();
                 }
          }

addition of two 3x3 matrices in java

2×4 Matrix in Java Example

By Dinesh Thakur

[Read more…] about 2×4 Matrix in Java Example

nxn Matrix in Java Example

By Dinesh Thakur

[Read more…] about nxn Matrix in Java Example

Increment and Decrement Operators in Java Examples

By Dinesh Thakur

Java has two very useful operators. They are increment (++) and decrement (- -) operators. The increment operator (++) add 1 to the operator value contained in the variable. The decrement operator (- -) subtract from the value contained in the variable.

There are two ways of representing increment and decrement operators.

a) as a prefix i.e. operator precedes the operand. Eg. ++ i; – -j ;

b) as a postfix i.e. operator follows the operand. Eg. i- -; j ++;

In case of prefix increment operator (Eg. ++i), first the value of the operand will be incremented then incremented value will be used in the expression in which it appears.

In case of postfix increment operator (Eg. I++), first the current value of the operand is used in the expression in which it appears and then its value is incremented by 1.

Java Example to implement Increment Operator. 
class IncrementOperator
{
         public static void main(String args[])
       {
               int X=14, Y=17;
               System.out.println("The Value X is : " +X);
               System.out.println("The Value Y is : " +Y);
               System.out.println("The Value ++X is : " +(++X));
               System.out.println("The Value Y++ is : " +(Y++));
               System.out.println("The Value X is : " +X);
               System.out.println("The Value of  Y is : " +Y);
       }
}

Java Example to implement Increment Operator

Java Example to implement Decrement Operator 
class DecrementOperator
{
         public static void main(String args[])
       {
               int X=10, Y=12;
               System.out.println("The Value X is : " +X);
               System.out.println("The Value Y is : " +Y);
               System.out.println("The Value --X is : " +(--X));
               System.out.println("The Value Y-- is : " +(Y--));
               System.out.println("The Value X is : " +X);
               System.out.println("The Value of  Y is : " +Y);
       }
}

Java Example to implement Decrement Operator

Java Example to perform increment and decrement operations using Scanner Class. 
import java.util.*;
class IncrementDecrementUsingScanner
{
                    public static void main(String args[])
           {
                      int a;
                      Scanner scan=new Scanner(System.in);
                      System.out.print("Enter the Value of a : ");
                      a=scan.nextInt();
                      System.out.println("Before Increment A : "+a);
                      System.out.println("After Increment A : "+(++a));
                      a++;
                      System.out.println("After Two Time Increment A : " +a);
                      System.out.println("Before Decrement A : "+a);
                      --a;
                      a--;
                      System.out.println("After Decrement Two Time A : "+a);
           }
}

Java Example to perform increment and decrement operations using Scanner Class

Assignment Operator in Java Example

By Dinesh Thakur

The assignment operator (=) is the most commonly used binary operator in Java. It evaluates the operand on the tight hand side and then assigns the resulting value to a variable on the left hand side. The right operand can be a variable, constant, function call or expression. The type of right operand must be type compatible with the left operand. The general form of representing assignment operator is

                       Variable = expression/constant/function call

                       a = 3; //constant

                       x = y + 10; //expression

In the first case, a literal value 3 is stored in the memory location allocated to variable a. In the second case, the value of expression y+ 10is evaluated and then stored in memory allocated to

variable x.

Consider a statement x = y = z = 3;

Such type of assignment statement in which a single value is given to a number of variables is called multiple assignment statement i.e. value 3 is assigned to the variables x, y and z. The assignment operator (=) has a right to left associatively, so the above expression is interpreted as

(x = (y = (z = 3)));

Here, first the value 3 is assigned to z, then value stored in z is assigned to y and then finally y is assigned to x. Now let us consider a statement

x = 3 = 5;

This type of statement is invalid assignment statement and it will generate an error.

\

There is another kind of assignment statement which combines a simple assignment operator with five arithmetic binary operators and six bitwise operators. This type of operator is known as compound assignment operator. The general syntax of compound assignment operator IS

                 Variable operator= expression/constant/function call

For example: Suppose i is a variable of type int then the statement,

i += 5;

will add the literal 5 to the variable i and store the result back into the variable i. The various compound assignment operators and their effect are as shown in table

Operator

Usage

Effect

+=

-=

*=

/=

%=

&=

|=

^=

<<=

>>=

>>>=

a+=b;

a-=b;

a*=b;

a/=b;

a%=b;

a&=b;

a|=b;

a^=b;

a<<=b;

a>>=b;

a>>>=b;

a=a+b;

a=a-b;

a=a*b;

a=a/b;

 a=a%b;

a=a&b;

a=a|b;

a=a^b;

 a=a<<b;

 a=a>>b;

    a=a>>>b;

Such operator makes the statement concise so they are also called shorthand assignment operator. The expression a = a+b is almost same as that of a += b but the mainadvantage of shorthand assignment operator is that the operand is that the operand on the left handside of the assignment is evaluated only once. The assignment operators have the lowestprecedence as compared to other operators. Only one variable is allowed on the left hand sideof the expression. Therefore a=x*y is valid and m*n=l is invalid.

It is to be kept in mind that assignment operator (=) and equality operator (= =) are different. The assignment operator is used to assign a value to a variable whereas the equality operator used to compare two operands. These operators cannot be used in place of each other. The assignment operator( =) has lower precedence than arithmetic, relational, bitwise, and logical operators.

Java Example to implement assignment operations
import java.util. *;
class AssignmentOperator
{
                  public static void main(String args[])
         {
                    int X=12, Y=13, Z=16;
                    System.out.println("The Assignment Value is : ");
                    X+=2;
                    Y-=2;
                    Z*=2;
                    System.out.println("The Value of X is : " +X);
                    System.out.println("The Value of Y is : " +Y);
                    System.out.println("The Value of Z is : " +Z);
          }
}

Java Example to implement assignment operations

Java Example to perform assignment operations using Scanner Class.
import java.util. *;
class AssignmentOperator
{
                  public static void main(String args[])
         {
                    int X,Y;
                    Scanner scan=new Scanner(System.in);
                    System.out.print("Enter the Value of X : ");
                    X=scan.nextInt();
                    System.out.print("Enter the Value of b : ");
                    Y=scan.nextInt();
                    System.out.println("X += 6 : "+(X+=6));
                    System.out.println("X -= 4 : "+(X-=4));
                    System. out. println("Y *= 4 : "+(Y*=4));
                    System. out. println("Y /= 6 : " +(Y/=6));
          }
}

Java Example to perform assignment operations using Scanner Class.

Java Arithmetic Operators Example

By Dinesh Thakur

Arithmetic operators are used to perform arithmetic calculations. Java provides basic arithmetic operators. They are +,-, *, /, %. The different Arithmetic operators that were used in java programming.

         

                                                             Arithmetic operators

Operators

Example

Meaning

+

–

*

/

%

a+b

a-b

a*b

a/b

a%b

Addition (or) Unary plus

Subtraction (or) Unary minus

Multip Iication

Division

Modulo division (Remainder)

 

class JavaArithmeticOperators  
{
          public static void main(String args[ ])
      {
                 int  a=15, b=9;
                 System.out.println("The Addition is : " +(a+b));
                 System.out.println("The Subtract is : "+(a-b));
                 System.out.println("The Multiple  is : "+(a*b));
                 System.out.println("The Division  is : " +(a/b));
                 System.out.println("The Modulo  is : "+(a%b));
      }
}

Java Arithmetic Operators Example

Daemon Threads in Java Examples

By Dinesh Thakur

Java has two types of threads : user thread and daemon thread. [Read more…] about Daemon Threads in Java Examples

Thread Priority in Java Example

By Dinesh Thakur

Every thread in Java has a priority that helps the thread scheduler to determine the order in which threads scheduled. The threads with higher priority will usually run before and more frequently than lower priority threads. By default, all the threads had the same priority, i.e., they regarded as being equally distinguished by the scheduler, when a thread created it inherits its priority from the thread that created it. However, you can explicitly set a thread’s priority at any time after its creation by calling its setPriority() method. This method accepts an argument of type int that defines the new priority of the thread. Its syntax is. [Read more…] about Thread Priority in Java Example

Thread Pools in Java Example

By Dinesh Thakur

When a large number of threads are created, degrades the performance of your application. So Java provides a technique of thread pooling to solve this problem.

The thread pooling allows you to reuse a single thread repeatedly instead of creating a new thread for each task and allowing it to be destroyed when the task completes. It avoids the overhead associated with creating a new thread by maintaining a pool of available threads and retrieving one from the pool when necessary. [Read more…] about Thread Pools in Java Example

Explicit Locks in Java Example

By Dinesh Thakur

In order to apply locks explicitly, an instance of the Lock interface needs to be created which is defined in the java.util.concurrent. Locks package. Using the Lock interface is similar to using the synchronized keyword. The Lock interface provides lock () and unlock () methods to acquire and release the lock respectively. [Read more…] about Explicit Locks in Java Example

Method Level Synchronization in Java Example

By Dinesh Thakur

Method level synchronization prevents two threads from executing method on an object at the same time. A method can be synchronized by using the synchronized keyword as a modifier in the method declaration. Its syntax is a follows, [Read more…] about Method Level Synchronization in Java Example

« Previous Page
Next Page »

Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW