0% found this document useful (0 votes)
2 views13 pages

Java BufferedReader Input and Operators

The document provides an overview of Java console input using BufferedReader, detailing how to read characters and strings from the console. It also covers various Java operators, categorizing them into arithmetic, bitwise, relational, and logical operators, along with examples of their usage. Additionally, it explains increment/decrement operators, compound assignments, and the ternary operator for conditional expressions.

Uploaded by

Suja Mary
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Java BufferedReader Input and Operators

The document provides an overview of Java console input using BufferedReader, detailing how to read characters and strings from the console. It also covers various Java operators, categorizing them into arithmetic, bitwise, relational, and logical operators, along with examples of their usage. Additionally, it explains increment/decrement operators, compound assignments, and the ternary operator for conditional expressions.

Uploaded by

Suja Mary
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit -1

Java Console input: Buffered Input


 In Java, console input is accomplished by reading from [Link].
 To obtain a characterbased stream that is attached to the console, wrap [Link] in a
BufferedReader object.
 BufferedReader supports a buffered input stream. Its most commonly used constructor is
shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is
being created. Reader is an abstract class. One of its concrete subclasses is
InputStreamReader, which converts bytes to characters.
 To obtain an InputStreamReader object that is linked to [Link], use the following
constructor:
InputStreamReader(InputStream inputStream)
The following line of code creates a BufferedReader that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

After this statement executes, br is a character-based stream that is linked to the console through
[Link].

Reading Characters
 To read a character from a BufferedReader, use read( ).
 The version of read( ) that we will be using is int read( ) throws 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 the stream is encountered.

Example

// Use a BufferedReader to read characters from the console.


import [Link].*;
class BRRead {
public static void main(String args[]) throws IOException {
char c;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter characters, 'q' to quit.");
// read characters do { c = (char) [Link]();
[Link](c);
} while(c != 'q');
}}
Here is a sample run:
Enter characters, 'q' to quit.
12aq
1
2
a
q
This means that no input is actually passed to the program until we press ENTER.

Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class.

Its general form is shown here:

String readLine( ) throws IOException


The following program demonstrates BufferedReader and the readLine( ) method; the program
reads and displays lines of text until you enter the word “stop”

// Read a string from console using a BufferedReader.

import [Link].*;

class BRReadLines {

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

// create a BufferedReader using [Link]

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

String str; [Link]("Enter lines of text.");

[Link]("Enter 'stop' to quit.");

do {

str = [Link]();

[Link](str); } while(![Link]("stop"));

}}
Here is a sample run:

Enter lines of text.

Enter 'stop' to quit.

This is line one.

This is line two.

stop

Here is your file:

This is line one.

This is line two.

Operators
Java operators are special symbols that perform various operations on variables or values.

In Java, operators can be divided into the following four groups:

1. Arithmetic
2. Bitwise
3. Relational and
4. Logical

Arithmetic Operators

 Arithmetic operators are used in mathematical expressions.


 The operands of the arithmetic operators must be of a numeric type.

The following table lists the arithmetic operators:


The Basic Arithmetic Operators

 The basic arithmetic operations—addition, subtraction, multiplication, and


division
 The minus operator also has a unary form that negates its single operand.
 The division operator is applied to an integer type, there will be no fractional
component attached to the result.

Example

int a = 1 + 1; 2

int b = a * 3; 6

int c = b / 4;  1

int d = c - a;  -1

int e = -d; 1

The Modulus Operator

The modulus operator, %, returns the remainder of a division operation.

It can be applied to floating-point types as well as integer types.

Example

int x = 42;
double y = 42.25

x%10; 2

y%10; 2.25

Arithmetic Compound Assignment Operators

Java provides special operators that can be used to combine an arithmetic operation with an
assignment.

compound assignment operator is +=

General form:

var = var op expression;

can be rewritten as

var op= expression;

Example

a = a + 4;

can be written

a+=4;

The %= obtains the remainder of a/2 and puts that result back into a.

Benefits

1. Save a bit of typing


2. Implemented more efficiently by the Java run-time system than are their equivalent long
forms.

Increment and Decrement

The ++ and the – – are Java’s increment and decrement operators.

The increment operator increases its operand by one.

x = x + 1;

can be written
x++;

The decrement operator decreases its operand by one.

Y=y-1;

Can be written

y--;

++ & -- operator has two forms:

 Prefix form
 Postfix form

In the prefix form, the operand is incremented or decremented before the value is obtained for
use in the expression.

In postfix form, the previous value is obtained for use in the expression, and then the operand is
modified.

Example:

x = 42;

y = ++x;

The line y = ++x; is the equivalent to

x = x + 1;

y = x;

In postfix form, the previous value is obtained for use in the expression, and then the operand is
modified.

Example:

x = 42;

y = x++;

The line y = x++; is the equivalent to

Y=x;

x = x + 1;

The Bitwise Operators


 Bitwise operators that can be applied to the integer types, long, int, short, char, and byte.
 These operators act upon the individual bits of their operands.
 The Bitwise operators are:

The bitwise operators manipulate the bits within an integer.


All of the integer types are represented by binary numbers of varying bit widths.
Example
The byte value for 42 in binary is 00101010, where each position represents a power of
two, starting with 20 at the rightmost bit.
Thus, 42 is the sum of 21 + 23 + 25 , which is 2 + 8 + 32.
Assuming a byte value, zero is represented by 00000000. In one’s complement, simply
inverting all of the bits creates 11111111, which creates negative zero.

The Bitwise Logical Operators

The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each
operation.

The Bitwise NOT


Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its
operand.

Example

42=00101010

becomes

11010101

The Bitwise AND

The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all
other cases.

The Bitwise OR

The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the
resultant bit is a 1, as shown here:

Example

int a = 3; // 0 + 2 + 1 or 0011 in binary

int b = 6; // 4 + 2 + 0 or 0110 in binary

int c = a | b;

int d = a & b;

int e = a ^ b;
The Left Shift

The left shift operator, << ,shifts all of the bits in a value to the left a specified number of times.
It has this general form:

value << num

Here, num specifies the number of positions to left-shift the value in value.

The << moves all of the bits in the specified value to the left by the number of bit positions
specified by num. For each shift left, the high-order bit is shifted out (and lost), and a zero is
brought in on the right.

Example

byte a = 64;

int i;

i = a << 2;

output

i=256

Since a is promoted to int for the purposes of evaluation, left-shifting the value 64 (0100 0000)
twice results in i containing the value 256 (1 0000 0000).

The Right Shift

The right shift operator, >>, shifts all of the bits in a value to the right a specified number of
times. Its general form is shown here:

value >> num

Here, num specifies the number of positions to right-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified by
num.

The following code fragment shifts the value 32 to the right by two positions, resulting in a being
set to 8: int a = 32; a = a >> 2; // a now contains 8

The Unsigned Right Shift

The Unsigned Right Shift

The >> operator automatically fills the high-order bit with its previous contents each time a shift
occurs. This preserves the sign of the value.
To shift a zero into the high-order bit no matter what its initial value was. This is known as an
unsigned shift.

shift-right operator, >>>, which always shifts zeros into the high-order bit.

The following code fragment demonstrates the >>>.

Here, a is set to –1, which sets all 32 bits to 1 in binary. This value is then shifted right 24 bits,
filling the top 24 bits with zeros, ignoring normal sign extension. This sets a to 255.

int a = -1;

a = a >>> 24;

Bitwise Operator Compound Assignments

The binary bitwise operator combines the assignment with the bitwise operation

Example

a = a >> 4;

a >>= 4;

The bitwise expression a OR b, are equivalent:

a = a | b;

a |= b;

Relational Operators

The relational operators determine the relationship that one operand has to the other.

The relational operators are shown here:


The relational operators are most frequently used in the expressions that control the if statement
and the various loop statements.

Any type in Java, including integers, floating-point numbers, characters, and Booleans can be
compared using the equality test, ==, and the inequality test, !=.

int a = 4;

int b = 1;

boolean c = a < b;

The result of a<b (which is false) stored in c

Boolean Logical Operators

The Boolean logical operators shown here operate only on boolean operands.

All of the binary logical operators combine two boolean values to form a resultant boolean value
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they
operate on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false
and !false == true.

Short-Circuit Logical Operators

 Secondary versions of the Boolean AND and OR operators, and are known as short-
circuit logical operators.
 The OR operator results in true when A is true, no matter what B is.
 Similarly, the AND operator results in false when A is false, no matter what B is.
 If use the || and && forms, rather than the | and & forms of these operators, Java will not
bother to evaluate the right-hand operand when the outcome of the expression can be
determined by the left operand alone.

For example, consider the following statement:

if(c==1 & e++ < 100) d = 100;

Here, using a single & ensures that the increment operation will be applied to e whether c is equal
to 1 or not.

The Assignment Operator

The assignment operator is the single equal sign, =.

It has this general form:

var = expression;

Here, the type of var must be compatible with the type of expression.

Example

Z=100;

Using a “chain of assignment” is an easy way to set a group of variables to a common value.

x = y = z = 100; // set x, y, and z to 100

The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else statements. This operator is the ?.

The ? has this general form:

expression1 ? expression2 : expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?
operation is that of the expression evaluated. Both expression2 and expression3 are required
to return the same type, which can’t be void.

Example

ratio = denom == 0 ? 0 : num / denom

When Java evaluates this assignment expression, it first looks at the expression to the left of
the question mark. If denom equals zero, then the expression between the question mark and
the colon is evaluated and used as the value of the entire ? expression. If denom does not
equal zero, then the expression after the colon is evaluated and used for the value of the
entire ? expression.

Common questions

Powered by AI

The modulus operator (%) in Java returns the remainder of a division operation. It is unique in that it can be applied to both integer and floating-point numbers, providing flexibility in various calculations. For integers, the modulus operator returns the remainder of dividing two integers. For example, 42 % 10 results in 2. For floating-point numbers, it yields the remainder as a floating-point result, allowing it to handle precision in calculations, such as 42.25 % 10 resulting in 2.25. This ability to work with both number types makes the modulus operator versatile for cases like determining cyclic behavior, time calculations, or handling angles in degrees .

Bit shifts are essential for efficient data manipulation in Java, providing powerful operations to alter binary data. Left shifts ('<<') and right shifts ('>>' or '>>>') differ in how they handle data movement. A left shift ('<<') shifts bits to the left, inserting zero at the least significant bit, thereby increasing the value's magnitude in powers of two. For instance, shifting 64 (binary: 01000000) left by two results in 256 (100000000). Right shifts can be signed ('>>') or unsigned ('>>>'). The signed right shift ('>>') preserves the sign bit by filling it with the same value, maintaining the sign for negative values as it shifts bits right. The unsigned right shift ('>>>'), however, fills the most significant bits with zero, disregarding any sign, which is crucial for manipulating unsigned binary data. These operators are particularly useful for low-level programming tasks such as graphics operations and system-level data management .

Logical boolean operators in Java, including AND (&), OR (|), XOR (^), and NOT (!), are pivotal in control structures, enforcing logical conditions effectively within boolean expressions. The AND operator yields true only if both operands are true, while the OR operator yields true if at least one operand is true. XOR results in true if operands are different, aiding in scenarios where exclusive conditions are beneficial. The NOT operator inverts the boolean value, crucial in toggle logic scenarios. These operators are integral in determining flow control within structures like 'if' conditions, loops, and switches. They harmonize with boolean expressions to form complex conditional logic, enabling developers to manage program execution paths based on dynamic boolean evaluations. Employing these operators smartly can reduce complexity, increase readability, and improve the precision of conditional logic in Java applications .

Bitwise operators in Java operate on the binary representations of integer types, manipulating individual bits. Key bitwise operators include AND (&), OR (|), XOR (^), and NOT (~). The AND operator produces a bit of 1 only if both operands have a bit of 1 at a given position, whereas the OR operator sets a bit to 1 if either operand has a bit of 1. XOR sets the bit to 1 if the corresponding bits of the operands differ. NOT inverts all bits of its operand. For example, the expression 3 & 6 evaluates to 2 since 0011 & 0110 results in 0010 in binary. These operations allow programmers to perform low-level optimizations and are commonly used in settings like graphics programming and hardware interface operations .

Wrapping System.in in a BufferedReader provides a character-based input stream that is buffered, meaning it reads data more efficiently by reducing the number of individual I/O operations required. BufferedReader supports methods like read() and readLine() that enable reading characters and strings from the console, which allows for more intuitive processing of input text. For example, using BufferedReader allows for line-by-line reading with the readLine() method, which waits for the user to press ENTER, batching the input into one line instead of processing each character individually. This approach is beneficial for both performance and usability when interacting with console input .

The ternary operator '?' in Java offers a concise way to perform conditional evaluations, serving as an alternative to simple if-then-else structures. It follows the syntax 'expression1 ? expression2 : expression3'. Here, 'expression1' should evaluate to a boolean value. If true, 'expression2' is executed; otherwise, 'expression3' is executed. The ternary operator is useful for situations where a simple conditional assignment is needed, making the code more compact. However, both 'expression2' and 'expression3' need to evaluate to the same type since the ternary expression results in a single value. This can be particularly efficient for inline assignments or return statements .

Compound assignment operators, such as '+=', '-=', and '*=', allow expressions to combine an arithmetic operation with an assignment, streamlining the code and reducing redundancy. For example, 'x += 3' is a shorthand for 'x = x + 3'. These operators are processed more efficiently by the Java runtime system compared to their longer form equivalents since they can reduce the amount of bytecode generated and executed. This efficiency is achieved because the variable is calculated and assigned in a single operation, minimizing repetitive fetching and computation of the operand, thereby enhancing performance, especially within loops or large codebases .

In Java, the increment (++) and decrement (--) operators can be used in two forms: prefix and postfix. The prefix form (++a or --a) modifies the variable's value before it is used in any expression within which it appears. Conversely, the postfix form (a++ or a--) uses the variable's original value in any expression before modifying it. For example, if we have int x = 5, then the expression int y = ++x results in x being incremented to 6 before it is assigned to y, making y also 6. In contrast, with y = x++, x is assigned to y while still being 5, and only afterwards is x incremented, resulting in x equaling 6 after the operation. These forms provide a way to optimize and control how expressions are evaluated especially within loops and conditions .

Arithmetic operators in Java can operate on numeric types such as int and double. When applying the division operator to integers, it performs integer division, which discards any fractional component and returns only the whole number part of the quotient. This means that dividing two integers will result in an integer result instead of a floating-point one. For instance, with int a = 3 and int b = 2, the expression a/b results in 1, not 1.5. To retain the fractional component, at least one of the operands must be cast to a floating-point type, such as double .

Short-circuit logical operators, such as '&&' and '||', improve efficiency by potentially reducing the number of evaluations necessary. These operators stop evaluating as soon as the overall logical expression’s outcome is determined. For example, in a conditional 'if(a && b)', if 'a' evaluates to false, 'b' is not evaluated, as the entire expression cannot possibly be true. This not only conserves computational resources but also prevents potential side effects from further evaluations, such as calling functions that modify state or involve potentially unsafe operations. Using short-circuit operators over non-short-circuit ('&', '|') ensures robust code execution, particularly when the right-hand side could involve expensive operations, error states, or null pointers .

You might also like