0% found this document useful (0 votes)
6 views

Unit-1 Java Console input

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
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit-1 Java Console input

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
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit -1

Java Console input: Buffered Input


 In Java, console input is accomplished by reading from System.in.
 To obtain a characterbased stream that is attached to the console, wrap System.in 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 System.in, 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(System.in));

After this statement executes, br is a character-based stream that is linked to the console through
System.in.

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 java.io.*;
class BRRead {
public static void main(String args[]) throws IOException {
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters do { c = (char) br.read();
System.out.println(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 java.io.*;

class BRReadLines {

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

// create a BufferedReader using System.in

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

String str; System.out.println("Enter lines of text.");

System.out.println("Enter 'stop' to quit.");

do {

str = br.readLine();

System.out.println(str); } while(!str.equals("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.

You might also like