Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, 8 February 2022

Difference between C and C++ | C and C++ difference - The Program Blog

Hello readers in this post you guys will be going to see the difference between C and C++, and what are the similarity is there in C and C++. So guys let's see both differences and similarities available between C and C++.

difference between c and c++

Some differences between C and C++ is as follows:

-C is a procedure/function-oriented language and C++ language is driven by a procedure/object.

-Data is not protected in C, whereas data is secured in C++. The data hiding concept is absent in C.

-C uses a top-down approach while C++uses a bottom-up approach. The program is prepared step by step in c, and in C++ base, elements are prepared first.

-In C we cannot give the same name to two functions in a program, whereas due to the function overloading feature, the above concept is possible in C++. One can initialize a number of functions with the same name, but with different arguments. The polymorphism feature is built in C++, which supports this concept.

-C uses printf() and scanf() functions to write and read the data respectively, while C++ uses cout and cin objects for output and input operations, respectively. Further,the cout uses <<(insertion operator) and cin uses >> (extraction operator).

-C uses stdio.h file for input and output functions, whereas C++ uses iostream.h for these functions.

-Constructor and destructor are absent in C and the same are provided in C++.

-Inline functions are supported by C++, and the same is absent in C. Inline functions can be used as micros. They are stated by the word 'inline'.

I hope you guys get cleared what is the difference between C and C++. If you have any queries or any doubts regarding this then please do comment in the comment section below.


Recommended post:

Monday, 9 March 2020

Java String | String class in java | java string methods - Online Help

In this post, we are discussing what is java string? that is what is a string class in java.let's see the string constructors and methods available in java. The topic which we will be going to cover in this post is

Java String | String class in java - Online Help

String class in Java:

A combination of characters is a string. Strings are instances of the class string. They are real objects and enable combination, testing, and modification. When a string literal is used in the program, Java automatically creates an instance of the String class. 

The string is a sequence of characters enclosed within double quotes “ “. This class is used to represent the constant string.it is fixed size. These classes are contained in the package java.lang that represents a string in Java that provides two fundamental classes that represent a string in Java. They are:


String declaration in Java:

Before we use a string in our program we have to declare it. so the java string Syntax is,

String stringname;

Where,

  • String is the java literal
  • Stringname is the name of the string

Example:
String s;

String initialization in Java:

The string can be initialized at the time of the string declaration. The value which we assign to the string should be enclosed with the double quotes " ''. so the initialization of the string is,

String strname=” variables”;

Example:

String s=” Sania”;

We can use an array in the declaration and initialization of string. let’s pass the array of values to the string,

String name[]={“Rohit”,” Rahul”,” Rohan”,” pooja”,” Sneha”};

Accessing the string:

In order to access the string, we have to create an instance for the string class. With the help of instance, we can access the string.

In the next section, let's see how to create Constructors and what are the different ways available in constructors so that we can understand the topics on how to create and access the instance.

Drawbacks of string class:


  • String class objects are immutable because once it is created the content of the string cannot be modified.
  • Because it is immutable it needs more memory space.

String program in Java:

Declaration and access of strings
Class strings
{
int i;
String name[]={“aaaa”,”bbbb”,”cccc”,”dddd”};
Void show()
{
System.out.println(“my favourite names are”);
for(i=0;i<5;i++)
System.out.println(name[i]);
}
}
Public static void main(String args[])
{
Strings s=new strings();
s.show();
}
}

The output is:

aaaa
bbbb
cccc
dddd

String constructors in Java:

Different types of String constructors are available in Java so that you can use the string in different ways as per your requirement. With these constructors, you will go through with different types of string declaration and initialization. The different types of the constructor are:

Empty string:

Let's see how empty string is created using the class string. It is the default constructor with no parameter.

The general form is,

String stringname;
Stringname=new String();

In the above statement is equivalent to the following statement:

String stringname=new string();

Example:

String str1;
str1=new String();

Is equivalent to

String str1=new String();

Or

String str=” ”; // empty string

The example will create an instance of a string with no characters in it.

String with character:

In order to create a string initialized with the character, we need to pass an array of characters to the constructor. let's see how the string is created with the character.

The general format is,

String strname=new String(character);

where the string and new are keywords. Strname is the name of the string. The String(character) is the constructor character in which the character is to assign.

Example:
Char chars[]={‘z’,’u’,’h’,’a’};
String s=new String(name);
System.out.println(s);

The above example creates a string instance with the four characters from the char as the initial value of the string s.

String with another string:

let's see how a string is created with another string. The general format to create a string with another string is,

String strname1=new String(strname2);

Where,

  • The string and new are keywords
  • The strname1,2 is the name of the string. 
  • In the string(), strname1 is assigned to the strname2

Example:
String str1=”sneha”;
String str2=new String(str1);
System.out.println(str2);

String with substring:

A string is created using the substring that allowed the specification of the starting index and the number of characters that have to be used. The general format is,

String strname=new String(char chars[],int startIndex, int numberofchar);

Where,

  • The String and new are keywords
  • char chars[] is the original string of character
  • startIndex is the starting index of the substring
  • Numberofchar is the ending number of substring.

Example:
char name[]={‘s’,’n’,’e’,’h’,’a’}
String str=new String(name,1,4);
System.out.println(str);

The example given above will print neha because when ‘n’ was at the index at 1 and we specified the count of 4 characters to be used to construct the string.

String with an array of ASCII:

let's see how a string is created with the array of ASCII parameters. The general format is,

String strname=new String(ASCIInum);

Where,

  • String and new are keywords. 
  • strname is the name of the string 
  • ASCII num is the ASCII value.

Example:

int value[]={77,65,78};
String str1=new String(value);
System.out.println(str1);

it will return the output as MAN.

string methods in Java:

The string class contains a number of methods that allow you to perform string manipulation. Most commonly used string methods are as follow:

Methods
Description
General format
length()
Number of character in string
Stringobject.length()
charAt()
The char at a location in the string
Stringobject.charAt(int indexvalue);
getChars(),getBytes()
Copy chars or bytes into a external array
Stringobject.getChars();
toCharArray()
Produces a char[]contains the character in the string
Stringobject.toCharArray()
equals(),equalsIgnoreCase()
An equality check on the content of the two strings
Stringobject.equals(string);
compareTo()
Results is negative,0 or + depending on the lexicographical ordering of the string and the argument. Uppercase and the lower case are not equal.
Stringobject.compareTo(string1);
regionMatches()
Boolean result indicates whether the region matches
 boolean regionMatches()
startWith()
Boolean result indicating whether the region matches
 boolean startWith()
endsWith()
The boolean result indicates if the argument is a suffix
boolean endsWith()
indexOf(),lastIndexOf()
Return -1 if the argument is not found within the string,otherwise returns the index where the arguments start. lastIndexOf() searches backward from the end.
Stringobject.indexOf(char);
Stringobject.lastIndexOf(char);
Substring()
Return a new string object contains the specified character set.
1.   Stringobject.substring(int beginindex);
2.   Stringobject.substring(int indexbegin,int endindex);
Concat()
Return a new string object contain the original strings character followed by the characters in the argument.
Stringobject.concat(string);
Replace()
Return a new string object with the replacements made.uses the old string if no matches found.
Stringobject.replace(oldstring,newstring);
toLowerCase(),toUpperCase()
Return a new string object with the case of all letter changed.uses the old string if no changes need to be made.
Stringobject.toLowerCase();
Stringobject.toUpperCase();
Trim()
Return the new string object with the whitespace removed from each end.uses the old string if no changes need to be made.
Stringobject.trim();
valueOf()
It returns a string containing a character representation of the argument.
String valueOf();
Intern()
Produces one and only string handle for each unique character sequence.
 String intern()


It is seen that every string method returns a new string object when it is necessary to change the contents. Also noticed that if the content does not require any change, the method will just return a handle to the original string. This saves storage and overhead.

Java String method example:

equal():

Class equaldemo
{
Public static void main(String args[])
{
String s1=”welcome”;
String s2=”welcome”;
String s3=”good morning”;
String s4=”welcome”
System.out.println(s1+”equals”+s2+”is”+s1.equals(s2));
System.out.println(s1+”equals”+s3+”is”+s1.equals(s3));
System.out.println(s1+”equals”+s4+”is”+s1.equals(s4));
}
}

The output is:

Welcome equals welcome is true
Welcome equals good morning is false
Welcome equals welcome is false

Sample program for :
length(),toLowerCase(),toUpperCase(),charAt(),concat(),indexOf(),lastIndexOf(),substring(),replace(),and trim()


Class st
{
Public static void main(String args[])
{
String s=”johny johny yes papa”+”eating sugar no papa”+”telling lies no papa”;
String s1=”hello world”;
String s2=”hello”;
String s3=”HELLO”;
String s4=”monkey”;
String s5=”don”
System.out.println(“index of e=”+s.indexOf(‘e’));
System.out.println(“last index of e=”+s.lastIndexOf(‘e’));
System.out.println(s1.substring(6));
System.out.println(s1.length());
System.out.println(s1.substring(3,8));
System.out.println(s2.concat(“world”));
System.out.println(s2.replace(‘l’,’w’));
System.out.println(s2.toUpperCase());
System.out.println(s3.toLowerCase());
System.out.println(s3.charAt(3));
System.out.println(s1.trim());
System.out.println(s4.compareTo(s5);
}
}

The output will be

johny johny yes papa eating sugar no papa telling lies no papa
index of e:14
11
last index of e: 62
world
lo wo
helloworld
hewwo
HELLO
Hello
l
hello world
6

String arithmetic:

The ‘+’ sign doesn't mean “addition” when it is used with the string object. The Java string class has something called operator overloading”, in another word the ‘+’ sign, when used with the string object, behave differently that does with everything else.

For string, it means: “concatenate these two strings”. when it is used with the strings and other objects creates a single string that contains the concatenation of all its operands.

When a numerical value is added to a string, the compiler calls the method that turns the numerical value( int, float, etc) into a string which can then be added with the Plus sign.

Any object or type you can convert to the string if the method to string() is implemented. To create a string, add all the parts together and output them. The +=operator will also work for the strings.

Example:
class sample
{
String fname=”rohit”;
String lname=”sharma”;
void show()
{
System.out.println(“The full name is+” “+fname+” “+lname);
}
Public static void main(String args[])
{
sample s1=new sample();
s1.show();
}
}

The output is;

The full name is rohit sharma

I hope you find this article useful. if you have any queries regarding this or something went wrong. Then please do comment.

Recommended post(you may like):




Wednesday, 26 February 2020

Java applet | How to create applet in java | life cyle of applet - 0nline help

We are going to discuss java applet. It’s advantages and disadvantages, the life cycle of an applet and sample program, etc.

java applet

What is Java applet:

The applet is small applications that are accessed on an internet server, transported over the internet, automatically installed and run as part of a web document.

An applet is developed for internet applications. Applets are embedded in HTML documents. Applets program can be run using a web browser or applet viewer.

The applet viewer tool is one of the tools included in the JDK(Java development kit) applet viewer. For example, when you use Java to enhance a web page the Java code is embedded within HTML code. It is called an applet.

Advantages and disadvantages of the applet:

Advantages of the applet:

Following are the advantages of an applet:

  • The most important feature of an applet is, it is truly platform-independent so there is no need of making any changes in the code for the different platform i.e. it is simple to make it works on Linux, Windows and Mac OS to make it cross-platform.
  • The same applet can work on all installed versions of Java at the same time, rather than just the latest plugin version only.
  •  It can move the work from the server to the client, making a web solution more scalable with users/clients.
  • The applet naturally supports the changing user state like figure position on the chessboard.
  • An applet improves with use: after the first applet is run the JVM is already running and starts quickly.
  • It can be used to provide dynamic user interfaces and a variety of graphical effects for web pages.

 Disadvantages of applets:

 The following are the disadvantages of an applet:

  • Applets cannot run any local executable programs.
  •  It can't talk with any host other than the originating server.
  •  Applets cannot read or write to the local computer file system.
  •  It cannot find any information about the local computer.
  •  All Java created a popup window carrying a warning message.
  •  Stability depends on the stability of clients with the server.
  •  Performance directly depends on the client's machine.

Also read: Multithreading in java

How to create java applet:

The creation of an applet is present here because the applet is not structured in the same way as the Java program has been used. As you will see, applet differs from application in several key areas:

Example:
import java.awt.*;
import java.applet.*;
Public class simpleapplet extends Applet
{
Public void paint(Graphics g)
{
g.drawString(“a simple applet”,20,20);
}
}

This applet begins with two import statements. The first import the Abstract window toolkit(AWT) classes. The applet interacts with the user through the AWT. The AWT supports Windows-based, graphical interface.

 The AWT is quite large and sophisticated. So, the applet makes very limited use of the AWT.

The second statement imports the applet package which contains the class applet. Every applet that you create must be a subclass of the applet.

The next line in the program declared the class simpleapplet. This class must be declared as public because it will be accessed outside the program.

Also read: Static and fixed method in java

Inside simplapplet, paint() is declared. This method is defined by the AWT and must be overridden by the applet.

paint() is called each time that is the applet must be redisplayed its output.

For example, the window in which are the applet is running can be minimized and restored. paint() is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint() is called.

The paint() method has one parameter of type Graphics. This parameter contains the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever the output of the applet is required.

Inside paint() is called to the drawString() which is a member of the Graphics class. This method outputs a string beginning at the specified X, Y location. It has the following general form:

Void drawString(string message,int x,int y);

Here the message is the string to be output beginning at the X, Y. In a java window, the upper-left corner is the location 0,0. The call to drawString() in the applet causes the message “a simple applet” to be displayed beginning at the location 20,20.

Notice:
The applet doesn't have a main() method. It does not begin execution at the main().In fact the most applets don't ever have main() method. An applet begins execution when the name of its class is passed to an applet viewer or to a net Browser.

After you enter the source code for simpleapplet, compile in the same way that you have been compiling a Java program.

However, running a simpleapplet involves a different process. There are two ways in which the applet run. They are:

-  We can execute the applet within a java compatible web browser such as Netscape navigator.

-  Using the applet viewer, such as the standard JDK tool, applet viewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet.

Also read: Java Synchronization

To execute an applet in a web browser, you need to write a short HTML text file that contains the appropriate applet tag. Here is the  HTML file that executes a simpleapplet.

<applet code=”simpleapplet” width=200 height=60>

</applet>

Save the file(as may be simpleapplet with .html extension). To execute a simpleapplet with an applet viewer, you may also execute the HTML file. Type the following command at the DOS prompt:

C:\>appletviewer simpleapplet.html

However, a more convenient method that you can use to speed up testing simply includes the HTML code at the head of your Java source code file that contains the Applet tag.

By doing this, your code is documented with a prototype of the necessary HTML statement and you can test your compiled applet merely by starting the applet viewer with your Java source code file. If you use this method the simple applet source file look like this:

Example:

Import java.awt.*;
Import java.applet.*;
/*
<applet code=”simpleapplet” width=200 height=60>
</applet>
*/
Public class simpleapplet extends Applet
{
Public void paint(Graphics g)
{
g.drawString(“a simle applet”,20,20);
}
}

Java applet life cycle:

The class applet has four methods that constitute the applet life cycle. They are: init(0,start(),stop(), and destroy(). These are defined by the applet class java.applet.*;
1.Public void init(0
2.Public void start()
3.Public void stop()
4.Public void destroy()

Graphical representation of the life cycle of a java applet:


java applet


Another method paint() is inherited by the applet class from the component class.

1.init()- The init() method is called only when the applet begins execution.

2.start()- The start() is executed after the init() method completes execution. This method is called by the applet viewer of the web browser to resume the execution of the applet.

3.stop()- The method stop() is called by the applet viewer or the web browser to suspend the execution of an applet.

4.destroy()- The method destroy() is called before the applet is terminated by the applet viewer or the web browser.

Sample program to demonstrate the applet life cycle:

import java.awt.*;
import java.applet.*;
/*<applet code=”applettest” width=200 height=100>
</applet>
*/
public class applettest extends Applet
{
public void init()
{
System.out.println(“applet initialized…”);
setBackground(Color.cyan);
}
public void start()
{
System.out.println(“applet is started…”);
}
public void stop()
{
System.out.println(“applet is stopped…”);
}
public void destroy()
{
System.out.println(“applet is destroyed…”);
}
Public void paint(Graphics g)
{
g.drawString(“applet text”,200,400);
showStatus(“this is shown in the status”);
}
}

Applet tags in HTML:

The applet tag is used to start an applet from both HTML documents and the applet viewer. An applet viewer will execute each applet tag that is fine in a separate window, while web browsers like Netscape Navigator, Internet Explorer and hot java will allow many applets on a single page.

The <applet> tag included in the body section of the HTML file supplies the name of the applet to be loaded and tells the browser how much space the applet requires.

The <applet> tag is used to incorporate an applet into a web page. The syntax of the <applet> is

<applet code=”filename.class” width=250 height=200>

</applet>

General structure of <applet> tag is:

<applet 
code=appletname.class
alt=alternate message
width=pixels
height=pixels
align=value
vspace=value
hspace=value>
</applet>

Also read: Thread in java

Here the attributes of an <applet> are

code: Name of the applet class file
Alt: alternate message
width: width of the applet window
height: height of the applet window
align: it aligns the applet window. Commonly used values are left,right,top,bottom,middle.
vspace: specifies the vertical blank space
hspace: specifies the horizontal blank space

Passing arguments to the applet:

Java allows users to pass user-defined parameters to applets with the help of <param> tags. Every applet has a built-in way of reading parameters from the <applet> tag.

The <param> tag is used within the <applet> tag pair t pass input as a parameter to an applet.

The <param> tag has a name attribute which defines the name of the parameter and a value attribute which specifies the value of the parameter.


The syntax of the <param> tag is:

<applet>
<param name=parameter1_name value=parameter1_value>
<param name=parameter2_name value=parameter2_value>
.
.
.
<param name=parametern_name value=parametern_value>
</applet>

For example, consider the following statement to set the text attribute to the applet:

<applet>
<param name=text value=This is an example of parameter>
</applet>

Accessing parameter:

Note that the <param> tags must be included between the <applet> and </applet> tags. The init() method in the applet retrieves user-defined value of the parameters defined in the <param> tag by using the getParameter() method.

This method accepts one string argument that holds the name of the parameter and returns a string that contains the value of that parameter.

The following program demonstrates the <param> tag i.e. passing parameters to an applet:

import.java.awt.*;
Import java.applet.*;
/*
<applet code=” passing.class” width=200 height=200>
<param name=”college” value=”neha”>
</applet>
*/
Public class passing extends applet
{
String str=” hi”;
public void init()
{
str+=getParameter(“college”);
}
public void paint(Graphics g)
{
g.drawString(str,50,50);
}
}

Also read: DeadLock in java

I hope you guys understand what is java applet? how can we create it and also get to know the life cycle of an applet? If you have any doubt or information regarding this, then please do comment.

Saturday, 22 February 2020

Java I/O tutorial | I/O stream class | Java file handling - Online Help

Java I/O tutorial:

In this post, we are going to discuss Java I/O tutorial. It is also known as Java file handling. Java I/O means input and output file which we can be used to read or write in a program. So to use the I/O file then we have to import the java.io package which is used for all the file handling tasks in Java.

The main concept of the Java I/O tutorial is' 'Stream''. It is a sequence of data composed in bytes. Java defines two types of the stream:

  • byte stream 
  • character stream

The topic that we will discuss in this post is:


Java I/O tutorial - Online Help

What is Byte stream:

Byte stream handles input and output of bytes. It is defined by 2 hierarchy classes. They are the InputStream and OutputStream classes.

Each of these classes is having its own several subclasses. The most commonly used method of InputStream and OutputStream is read() and write() method, which is used to read and write bytes of data.

The InputStream and OutputStream classes are the most commonly used classes of byte stream class.


 Byte stream classes in Java:

 The important classes defined by InputStream and OutputStream are as follow:


Classes
Meaning



Input stream class
1.BufferedInputStream
Buffers input from a byte stream.
2.ByteArrayInputStream
An input stream that reads from a byte array.
3.DataInputStream
Reads the standard java datatype from a byte input stream.
4.FileInputStream
Reads binary data from a file.
5.FilterInputStream
Filters an input stream.
6.PipedInputStream
Inputs pipe.
7.SequenceInputStream
Reads sequentially one after the other.
8.PushBackInputStream
Return a byte to the input stream.




Output stream class
1.BufferedOutputStream
Buffers output to a byte stream.
2.ByteArrayOutputStream
Output streams that write a byte array
3.DataOutputStream
Writes the standard java  datatype from a byte output stream.
4.FileOutputStream
Writes binary data to a file
5.FilterOutputStream
Filters an output stream
6.PipedOutputStream
Outputs pipe
7.PrintStream
Output stream that contains print() and println()
8.PushBackOutputStream
Returns bytes to the output stream.

Methods for byte stream classes:

The important method defined by the InputStream and OutputStream classes are as follow:


Methods
Meaning



Input stream method
1.int available()
Returns the number of bytes currently  available for reading
2.int read()
Reads one byte from the input stream
3.int read(byte buf[])
Reads an array of bytes into the buffer
4.int read( byte buf[],int n,int numbytes)
Reads the number of bytes into the buffer starting from an nth byte.
5.void close()
Close the input stream.
6.void mark(int numbytes)
Places the mark at the current point in the input stream.
7.void reset()
Resets the input pointer to the previously set mark.
8.void skip()
Returns the number of bytes actually skipped.

Output stream method
1.void write(int b)
Writes the single bytes to the output stream
2.void write(byte buf[])
Writes the complete bytes in the array buffer to the output stream.
3.void close()
Closes the output stream.
4.void flush()
Clears the output buffer.

What is Character stream:

Character stream handles input and output of character. It is used to define the hierarchy of classes. They are Reader and Writer class. These classes handle the Unicode characters stream.

The two important methods of Reader and Writer class is read() and write(), which reads and writes the character data respectively

 Character stream classes in Java:

The most commonly used  subclasses of reader and writer class are listed below:


Classes
Meaning




Reader class
1.BufferedReader
Buffered input character stream.
2.CharArrayReader
Reads from a character array.
3.FileReader
An input stream that reads from a file.
4.FilterReader
Filtered reader.
5.PipedReader
Inputs pipe.
6.PushbackReader
Allows character to be refused to the input stream.
7.StringReader
Reads from a string.
8.InputStreamReader
Translates bytes to a character stream.
9.LineNumberReader
An input stream that counts lines.




Writer class
1.BufferedWriter
Buffered output character stream.
2.CharArrayWriter
Writes to a character array.
3.FileWriter
Output stream that writes to a file.
4.FilterWriter
Filtered writer.
5.PipedWriter
Output pipes.
6.StringWriter
Writes to a string.
7.OutputStreamWriter
Translates character to a byte stream.
8.PrintWriter
Output stream that contains print() and println().

Character stream methods:

The various important methods defined by The Reader and writer class is as follow:


Method
Meaning



Reader class
1.void close()
Closes the input stream.
2.int read()
Reads a character from the stream.
3.int read(char buf[])
Reads an array of character into buffer.
4.int read(char buf[],int n, int numchars)
Read the number of character into the buffer starting from the nth number.
5.void mark(int numchars[])
Places the mark at the current point in the input stream.
6.void reset()
Resets the input pointer to previously set mark.
7.void skip(long numchar)
Returns the number of character actually skipped.

Writer class
1.void write(int c)
Writes the lower 2 bytes of c to the stream.
2.void write(char buff[])
Writes the characters in the buffer to the stream.
3.void close()
Closes the output stream.

4.void flush()
Writes any buffered data that is represented by the stream.

Predefined streams in java:

All Java programs automatically import the java.lang package. This package defines a class called system which encapsulates several aspects of the Runtime environment. There are basically three types of stream consoles present in Java. They are:

  • System.in
  • System.out
  • System.err


System.out: Refers to standard output stream by default this is the console.

System.in: Refers to the standard input which is the keyboard by default.

System.err: Refers to standard error stream which also is the console by default. However, these streams may be redirected to any compatible I/O device.

System.in is an object of type InputStream. System.out and System.in is an object of type PrintSystem.

These are byte stream even though they can be used to read and write characters from one console to the other console.

Reading console input

In Java, the input console is accomplished by reading from System.in. To obtain a character-based Stream that is attached to the console, we have to wrap system.in in a BufferReader object, to create a character stream. BufferedReader supports your buffered input stream. The most commonly used constructor is:

BufferedReader(Reader inputReader)

here inputReader is the stream that is linked to the instance of BufferedReader that is being created. The reader is an abstract class. its subclass is InputStreamReader, which converts bytes to the character. To obtain an InputStreamReader object that is linked to System.in, uses the following constructor:

InputStreamReader(InputStream inputStream)

because of System.in refers to an object of the type Input system, it can be used for InputStream. Putting it all together to create a BufferedReader that is connected to the keyboard is,

BufferedReader br= new BufferedReader(new InputStreamReader(System.in))

after this stream executes, br is a character-based stream that is linked to the console through system.in

-Reading characters:

To read a character from BufferedReader, use read(). The syntax will be

int read()throw IOException

each time that read() is called, it reads a character from the input stream and returns it as an integer value. It returns -1 when the end of Stream is encountered. It can throw an IOException.

Example:
class brread
{
public static void main(String args[]) throws IOException
{
char c,
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter character,q to quit");
do{
c=(char)br.read();
System.out.println(c);
}while(c!='q');
}
}

-Reading string:

To read a string from BufferedReader, use readLine(). The general format is,

String readLine() throws IOException

each time that readLine() is called, it reads a line of text from, store each line in the array. It reads until you enter stop. It can throw an IOException.

Example:
import java.io.*;
class brread{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("enter lines of text");
System.out.println("enter stop to exit");
do
{
str=br.readLine();
System.out.println(str);
}
while(!str.Equals("stop");
}
}

Writing console output:

These methods are defined by the class PrintStream(which is the type of object reference by even though system.out). Even though System.out is a byte stream, using it for simple program output is still acceptable. For a character-based program, the method is described below.

Printstream is an output stream derived from OutpuStream. it also implements the low-level method to write(). Thus write() can be used to write to the console. The simplest form of write() defined by PrintStream is shown here,

void write(int byteval) throws IOException

This method writes to the file the bytes specified by the byteval. although the byteval is declared as an integer, only the lower level eight bits are written. Here is an example that uses write() to output the character "A" followed by the new line to the screen:

class writedemo
{
public static void main(String args[])
{
int b;
b='A';
System.out.write(b);
System.out.write('\n');
}
}

PrintWriter Class:

PrintWriter is one of the character-based classes. It displays the string equivalents of standard types(int, char, float). It has four constructors are as follows:

  • PrintWriter(Writer w)
  • PrintWriter(Writer w, boolean flushonNewline)
  • PrintWriter(OutputStream os)
  • PrintWriter(OutputStream os, boolean flushonNewline)


Here, flushOnNewline controls whether java flushes the output stream. If flushonNewLine is true, flushing automatically takes place, otherwise, flushing is not automatic.

PrintWriter supports the print() and println() method for all types including the object. To create a PrintWriter that is connected to the console output as follow:

PrintWriter pw=new PrintWriter(System.out);

The following program illustrates using a PrintWriter to handle console output:

import java.io.*;
class printwriterdemo
{
public static void main(String args[])
{
PrintWriter pw=new PrintWriter(System.out);
pw.println('x');
pw.println(400);
int i=10;
pw.println(i);
double d=4329.683596;
pw.println(d);
float f= 3.14f;
pw.println(f);
pw.println("java");
}
}


FileInputStream and FileOutputStream in java (File streams):

Java provides the number of class and method that allows you to read and write files. In Java all files are byte-oriented and Java provides methods to read and write bytes from a file to a file.

Two of the most often used stream classes are FileInputStream and FileOutputStream, which create a byte stream link to a file.

To open your file you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor.

While both FileInputStream and FileOutputStream classes support constructor. The format is,

-FileInputStream(String filename) throws FileNotFoundException

-FileOutputStream(String filename)throws FileNotFoundException

here, filename specified the name of the file that you want to open. when you create an input stream if the file doesn't exist then FileNotFoundException is thrown. For output stream, if the file cannot be created then FileNotFoundException has thrown. When an output file is open any pre-existing file by the same name is destroyed.

When you are done with the file you should close it by calling close() method it is defined by both as FileInputStream and FileOutputStream as shown here:

void close() throws IOException

To read a file, you can use the read() method that is defined within FileInputStream. The general form is,

int read() throws IOException

Each time the read() is called it reads a single byte from the file and returns the byte as an integer value, read() returns -1 when the end of file is encountered. It can throw an IOException.

The following program uses read() to input and displays the content of the text file. The name of which is specified as a command-line argument.

Note the try-catch block that handles the two errors that might occur when this program is used- the specified file not being found or the user forgetting to include the name of the file.

You can use this same approach whenever you use common line arguments.

import java.io.*;
class showfile
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
try
{
fin=new FileInputStream(args[0])'
}
catch(FileNotFoundException e)
{
System.out.println("file not found");
return;
}
catch(ArrayIndexOutOfBoundException e)
{
System.out.println("usage: showfile file");
return;
}
do
{
}
while(i!=-1)'
}
}