eramarswami.com

amar swami


Leave a comment

how to find square root of decimal number

To find the square root of numbers in the decimal form are explained in the following steps:

Step I: Make the number of decimal places even by affixing a zero on the extreme right of the decimal part (if required).

Step II: In the integral part, mark the periods as done while finding the square root of a perfect square of some natural number.

Step III: In the decimal part, mark the periods on every pair of digits beginning with the first decimal place.

Step IV: Now, find the square root by long division method.

Step V: Put the decimal point in the square root as soon as the integral part is exhausted.

Examples on square root of numbers in decimal form:

1. Evaluate: √42.25

Solution:

Using the division method we may find the square root of the given number;

Therefore, √42.25 = 6.5

2. Evaluate: √1.96

Solution:

Using the division method we may find the square root of the given number;

Therefore, √1.96 = 1.4

3. Evaluate: √6.4009

Solution:

Using the division method we may find the square root of the given number;

Therefore, √6.4009 = 2.53


4. Evaluate: √66.4225

Solution: 

Using the division method we may find the square root of the given number;

Therefore, √66.4225 = 8.15

5. Evaluate: √0.4225

Solution:

Using the division method we may find the square root of the given number;

Therefore, √0.4225 = 0.65


Leave a comment

square of a number easy trick math ssc bank po railway exam

square root

(algorithm)

Definition: This describes a “long hand” or manual method of calculating or extracting square roots. Calculation of a square root by hand is a little like long-hand division.

Suppose you need to find the square root of 66564. Set up a “division” with the number under the radical. Mark off pairs of digits, starting from the decimal point and working left. (Here the decimal point is a period (.) and commas (,) mark pairs of digits.)

               ___________	
             \/  6,65,64.	

Look at the leftmost digit(s) (6 in this case). What is the largest number whose square is less than or equal to it? It is 2, whose square is 4. Write 2 above, write the square below and subtract.

               __2________	
             \/  6,65,64.	
                -4		
               ----		
                 2		

Now bring down the next two digits (65). The next “divisor” is double the number on top (2×2=4) and some other digit in the units position (4_).

               __2________	
             \/  6,65,64.	
                -4		
                -----		
             4_ ) 265		

What is the largest number that we can put in the units and also multiply times the divisor such that the result is still be less than or equal to what we have? (Algebraically, what is d such that d × (40+d) ≤ 265?) It looks like 6 might work (since 6 × 40 = 240), but 6 is too big, since 6 × 46 = 276:

               __2__6_____	
             \/  6,65,64.	
                -4		
                -----		
             46 ) 265		
                 -276   TOO BIG	

So try 5 instead.

               __2__5_____	
             \/  6,65,64.	
                -4		
                -----		
             45 ) 265		
                 -225		
                 -------		
                   40		

Repeat: bring down the next two digits, and double the number on top (2 × 25 = 50) to make a “divisor”, with another unit.

               __2__5_____	
             \/  6,65,64.	
                -4		
                -----		
             45 ) 265		
                 -225		
                 -------		
             50_ ) 4064		

It looks like 8 would work. Let’s see.

               __2__5__8__	
             \/  6,65,64.	
                -4		
                -----		
             45 ) 265		
                 -225		
                 -------		
             508 ) 4064		
                  -4064		
                  ------		
                      0		

So the square root of 66564 is 258. You can continue for as many decimal places as you need: just bring down more pairs of zeros.

Here is an example spanning the decimal point. When a number does not have a rational square root, you can continue calculating (significant) digits as long as you wish.

       __1__6.8_4_0_4_2_7_5_...
     \/  2,83.6		
        -1		
        -----		
     26 ) 183		
         -156		
         ------		
     328 ) 2760		
          -2624		
          -------	
     3364 ) 13600	
           -13456	
           --------	
     33680 )  14400	
                 -0	
            ---------	
     336804 ) 1440000	
             -1347216	
             ----------	
     3368082 )  9278400	
               -6736164	
              -----------	
     33680847 ) 254223600	
               -235765929	
               ------------	
     336808545 ) 1845767100	
                -1684042725	
                -----------	
                  161724375	

Why does this work?

Consider (10A + B)² = 100A² + 2 × 10AB + B² and think about finding the area of a square. Remember that 10A + B is just the numeral with B in the units place and A in the higher position. For 42, A=4 and B=2, so 10 × 4 + 2 = 42.

diagram of a square that is 10A + B on a side showing a 100A squared  rectangle, two 10AB rectangles, and a B squared rectangle

The area of the two skinny rectangles is 2 × 10A × B. The tiny square is B². If we know A and the area of the square, S, what B should we choose?

We previously subtracted A² from S. To scale to 100A², we bring down two more digits (a factor of 100) of the size of S. We write down twice A (2A), but shifted one place to leave room for B (10 × 2A or 2 × 10A). Now we add B to get 2 × 10A + B. Multiplying by B gives us 2 × 10AB + B². When we subtract that from the remainder (remember we already subtracted A²), we have subtracted exactly (10A + B)². That is, we have improved our knowledge of the square root by one digit, B.

We take whatever remains, scale again by 100, by bringing down two more digits, and repeat the process.

See also cube root.

Note: In computers and hand-held calculators, square root, sine, cosine, and other transcendental functions are calculated with sophisticated functions, such as Taylor series, CORDIC, or Newton-Raphson method, sometimes called Newton’s method. This lesson explains, for instance, possible difficulties in convergence.

Author: PEB

Implementation

GAMS Class C2 has many implementations of powers, roots, and reciprocals (C and Fortran). Many variations (C and Assembler) for caching, pipelined processing, etc.

More information

Another geometric justification.


Go to the Dictionary of Algorithms and Data Structures home page.


If you have suggestions, corrections, or comments, please get in touch with Paul Black.

Entry modified 8 September 2014.
HTML page formatted Mon Dec 12 09:26:39 2016.

Cite this as:
Paul E. Black, “square root”, in Dictionary of Algorithms and Data Structures [online], Vreda Pieterse and Paul E. Black, eds. 8 September 2014. (accessed TODAY) Available from: https://www.nist.gov/dads/HTML/squareRoot.html


Leave a comment

How to find square of a number

and should your child learn how to do it

Most people in today’s world feel that since calculators can find square roots, that children don’t need to learn how to find square roots using any pencil-and-paper method. However, learning at least the “guess and check” method for finding the square root will actually help the students UNDERSTAND and remember the square root concept itself!

So even though your math book may totally dismiss the topic of finding square roots without a calculator, consider letting students learn and practice at least the “guess and check” method. Since it actually deals with the CONCEPT of square root, I would consider it as essential for students to learn.

Depending on the situation and the students, the “guess and check” method can either be performed with a simple calculator that doesn’t have a square root button or with paper & pencil calculations.

 

Finding square roots by guess & check method

To find a decimal approximation to, say √2, first make an initial guess, then square the guess, and depending how close you got, improve your guess. Since this method involves squaring the guess (multiplying the number times itself), it uses the actual definition of square root, and so can be very helpful in teaching the concept of square root.

 

Example: what is square root of 20?

You can start out by noting that since √16 = 4 and √25 = 5, then √20 must be between 4 and 5.

Then make a guess for √20; let’s say for example that it is 4.5. Square that, see if the result is over or under 20, and improve your guess based on that. Repeat this process until you have the desired accuracy (amount of decimals). It’s that simple and can be a nice experiment for students!

 

Example: Find √6 to 4 decimal places

Since 22 = 4 and 32 = 9, we know that √6 is between 2 and 3. Let’s guess (or estimate) that it is 2.5. Squaring that we get 2.52 = 6.25. That’s too high, so we reduce our estimate a little. Let’s try 2.4 next. To find the square root of 6 to four decimal places we need to repeat this process until we have five decimals, and then we will round the result.

Estimate Square of estimate High/low
2.4 5.76 Too low
2.45 6.0025 Too high but real close
2.449 5.997601 Too low
2.4495 6.00005025 Too high so the square root of 6 must be between 2.449 and 2.4495.
2.4493 5.99907049 Too low
2.4494 5.99956036 Too low, so the square root of 6 must be between 2.4494 and 2.4495
2.44945 5.9998053025 Too low, so the square root of 6 must be between 2.44945 and 2.4495.

This is enough iterations since we know now that √6 would be rounded to 2.4495 (and not to 2.4494).

 

Finding square roots using an algorithm

There is also an algorithm for square roots that resembles the long division algorithm, and it was taught in schools in days before calculators. See the example below to learn it. While learning this algorithm may not be necessary in today’s world with calculators, working out some examples can be used as an exercise in basic operations for middle school students, and studying the logic behind it can be a good thinking exercise for high school students.

 

Example: Find √645 to one decimal place.

First group the numbers under the root in pairs from right to left, leaving either one or two digits on the left (6 in this case). For each pair of numbers you will get one digit in the square root.

To start, find a number whose square is less than or equal to the first pair or first number, and write it above the square root line (2):

2
6 .45

Then continue this way:

2
6 .45
 – 4
2 45
2
6 .45
 – 4
(4 _) 2 45
2
6 .45
 – 4
(45) 2 45
Square the 2, giving 4, write that underneath the 6, and subtract. Bring down the next pair of digits. Then double the number above the square root symbol line (highlighted), and write it down in parenthesis with an empty line next to it as shown. Next think what single-digit number something could go on the empty line so that forty-something times something would be less than or equal to 245.
45 x 5 = 225
46 x 6 = 276, so 5 works.
2

5

6 .45 .00
 – 4
(45) 2 45
– 2 25
20 00
2

5

6 .45 .00
 – 4
(45) 2 45
– 2 25
(50_) 20 00
2

5

. 3
6 .45 .00
 – 4
(45) 2 45
– 2 25
(503) 20 00
Write 5 on top of line. Calculate 5 x 45, write that below 245, subtract, bring down the next pair of digits (in this case the decimal digits 00). Then double the number above the line (25), and write the doubled number (50) in parenthesis with an empty line next to it as indicated: Think what single digit number something could go on the empty line so that five hundred-something times something would be less than or equal to 2000. 503 x 3 = 1509
504 x 4 = 2016, so 3 works.
2

5

. 3
6 .45 .00 .00
 – 4
(45) 2 45
– 2 25
(503) 20 00
–  15 09

4

91 00
2

5

. 3
6 .45 .00 .00
 – 4
(45) 2 45
– 2 25
(503) 20 00
–  15 09
(506_)

4

91 00
2

5

. 3 9
6 .45 .00 .00
 – 4
(45) 2 45
– 2 25
(503) 20 00
–  15 09
(506_) 4 91 00
Calculate 3 x 503, write that below 2000, subtract, bring down the next digits. Then double the ‘number’ 253 which is above the line (ignoring the decimal point), and write the doubled number 506 in parenthesis with an empty line next to it as indicated: 5068 x 8 = 40544
5069 x 9 = 45621, which is less than 49100, so 9 works.

Thus to one decimal place, 645 = 25.4

 


Leave a comment

Auto-Forward SMS and Missed Calls to your Email [Android]

you may wonder why would anyone want to forward text messages or missed call notifications to their email account when the cell phone is with them all the time? Won’t these messages add more noise to an overflowing email Inbox?
Not so. For instance, some of my friends work in a company where, for security reasons, they aren’t allowed to carry personal mobile phones inside though they do have regular phones at their desk and are allowed email access. They would therefore leave the phone at home but with auto-forwarding enabled, they’ll get an email alert as soon as someone sends them an SMS or calls on their cell during office hours.

Such a feature may also be handy for people who have recently switched to a different phone number and would like to keep track of all incoming calls and messages received on their previous phone but without having to carry it all the time.

The Android Market has dozens of apps that can bring the auto-forwarding feature to your mobile phone but the one that I like most is SMS2Gmail. It says “SMS” but the app can forward both SMS text messages and missed calls to your email address. You will get the complete message text in your email and the sender’s name as well provided that that number already exists in your phonebook.

sms auto forwardIt takes just one step to get it up and running. Launch the app, provide the credentials of your Gmail account and done. It needs the Google credentials in order to send email notifications but if that doesn’t make you too happy, just create another Gmail account and set it to auto-forward messages to your primary email account.

One more thing. You turn on email notifications manually but in a situation where you have have forgotten the phone at home, or have misplaced it somewhere, you can remotely activate auto-forwarding by sending an SMS from any another phone to your phone.

The app lets you assign an Activation Keyword (see screenshot) and as soon as a text arrives with that keyword, the auto-forwards will be enabled automatically.


Leave a comment

play with google

1. Google Gravity

Watch Google shattering itself under the effect of gravity. But the funny part is, you can still make a search by entering your query in the search box and it will display the results in gravity fashion.

LINK-1

gravity

2. Google Mirror

Watch google creating the mirror image every you type with google mirror.

mirroring

To do this :

Open google.com and type in google mirror and select I’m feeling lucky or the first link that comes up.

LINK-2


Leave a comment

file handling

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic functionality related to streams and I/O. We would see most commonly used example one by one:

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are , FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file:

import java.io.*;

public class CopyFile {
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream(“input.txt”);
out = new FileOutputStream(“output.txt”);

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let’s have a file input.txt with the following content:

This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let’s put above code in CopyFile.java file and do the following:

$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are , FileReader and FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write above example which makes use of these two classes to copy an input file (having unicode characters) into an output file:

import java.io.*;

public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader(“input.txt”);
out = new FileWriter(“output.txt”);

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let’s have a file input.txt with the following content:

This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let’s put above code in CopyFile.java file and do the following:

$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user’s program can take input from a keyboard and then produce output on the computer screen. If you are aware if C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similar way Java provides following three standard streams

Standard Input: This is used to feed the data to user’s program and usually a keyboard is used as standard input stream and represented as System.in.

Standard Output: This is used to output the data produced by the user’s program and usually a computer screen is used to standard output stream and represented as System.out.

Standard Error: This is used to output the error data produced by the user’s program and usually a computer screen is used to standard error stream and represented as System.err.

Following is a simple program which creates InputStreamReader to read standard input stream until the user types a “q”:

import java.io.*;

public class ReadConsole {
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;

try {
cin = new InputStreamReader(System.in);
System.out.println(“Enter characters, ‘q’ to quit.”);
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != ‘q’);
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let’s keep above code in ReadConsole.java file and try to compile and execute it as below. This program continues reading and outputting same character until we press ‘q’:

$javac ReadConsole.java
$java ReadConsole
Enter characters, ‘q’ to quit.
1
1
e
e
q
q
Reading and Writing Files:
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams
file handling
The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial:

FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the file.:

InputStream f = new FileInputStream(“C:/java/hello”);
Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows:

File f = new File(“C:/java/hello”);
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

SN Methods with Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it’s end of file.
4 public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If end of file -1 will be returned.
5 public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an int.
There are other important input streams available, for more detail you can refer to the following links:

ByteArrayInputStream

DataInputStream

FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn’t already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file:

OutputStream f = new FileOutputStream(“C:/java/hello”)
Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows:

File f = new File(“C:/java/hello”);
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.

SN Methods with Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.
3 public void write(int w)throws IOException{}
This methods writes the specified byte to the output stream.
4 public void write(byte[] w)
Writes w.length bytes from the mentioned byte array to the OutputStream.
There are other important output streams available, for more detail you can refer to the following links:

ByteArrayOutputStream

DataOutputStream

Example:
Following is the example to demonstrate InputStream and OutputStream:

import java.io.*;

public class fileStreamTest{

public static void main(String args[]){

try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream(“test.txt”);
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream(“test.txt”);
int size = is.available();

for(int i=0; i< size; i++){
System.out.print((char)is.read() + ” “);
}
is.close();
}catch(IOException e){
System.out.print(“Exception”);
}
}
}
The above code would create file test.txt and would write given numbers in binary format. Same would be output on the stdout screen.

File Navigation and I/O:
There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.

File Class

FileReader Class

FileWriter Class

Directories in Java:
A directory is a File which can contains a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail check a list of all the methods which you can call on File object and what are related to directories.

Creating Directories:
There are two useful File utility methods, which can be used to create directories:

The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

The mkdirs() method creates both a directory and all the parents of the directory.

Following example creates “/tmp/user/java/bin” directory:

import java.io.File;

public class CreateDir {
public static void main(String args[]) {
String dirname = “/tmp/user/java/bin”;
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
Compile and execute above code to create “/tmp/user/java/bin”.

Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories available in a directory as follows:

import java.io.File;

public class ReadDir {
public static void main(String[] args) {

File file = null;
String[] paths;

try{
// create new file object
file = new File(“/tmp”);

// array of files and directory
paths = file.list();

// for each name in the path array
for(String path:paths)
{
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
}
This would produce following result based on the directories and files available in your /tmp directory:

test1.txt
test2.txt
ReadDir.java
ReadDir.class

 


Leave a comment

java operator

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

  • Arithmetic Operators
  • Relational Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
  • Misc Operators

The Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:

Assume integer variable A holds 10 and variable B holds 20, then:

 

Operator Description Example
+ Addition – Adds values on either side of the operator A + B will give 30
Subtraction – Subtracts right hand operand from left hand operand A – B will give -10
* Multiplication – Multiplies values on either side of the operator A * B will give 200
/ Division – Divides left hand operand by right hand operand B / A will give 2
% Modulus – Divides left hand operand by right hand operand and returns remainder B % A will give 0
++ Increment – Increases the value of operand by 1 B++ gives 21
Decrement – Decreases the value of operand by 1 B– gives 19

The Relational Operators:

There are following relational operators supported by Java language

Assume variable A holds 10 and variable B holds 20, then:

 

Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

The Bitwise Operators:

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

—————–

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

The following table lists the bitwise operators:

Assume integer variable A holds 60 and variable B holds 13 then:

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits. (~A ) will give -61 which is 1100 0011 in 2’s complement form due to a signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111
>>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >>>2 will give 15 which is 0000 1111

The Logical Operators:

The following table lists the logical operators:

Assume Boolean variables A holds true and variable B holds false, then:

 

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.

The Assignment Operators:

There are following assignment operators supported by Java language:

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C – A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Misc Operators

There are few other operators supported by Java Language.

Conditional Operator ( ? : ):

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:

public class Test {

   public static void main(String args[]){
      int a , b;
      a = 10;
      b = (a == 1) ? 20: 30;
      System.out.println( "Value of b is : " +  b );

      b = (a == 10) ? 20: 30;
      System.out.println( "Value of b is : " + b );
   }
}

This would produce the following result:

Value of b is : 30
Value of b is : 20

instanceof Operator:

This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceof operator is wriiten as:

( Object reference variable ) instanceof  (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example:

public class Test {

   public static void main(String args[]){
      String name = "James";
      // following will return true since name is type of String
      boolean result = name instanceof String;  
      System.out.println( result );
   }
}

This would produce the following result:

true

This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:

class Vehicle {}

public class Car extends Vehicle {
   public static void main(String args[]){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result );
   }
}

This would produce the following result:

true

Precedence of Java Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity
Postfix () [] . (dot operator) Left to
right
Unary ++ – – ! ~ Right to left
Multiplicative * / % Left to right
Additive + – Left to right
Shift >> >>> << Left
to right
Relational > >= < <= Left to right
Equality == != Left
to right
Bitwise AND & Left to right
Bitwise
XOR
^ Left to right
Bitwise OR | Left
to right
Logical AND && Left to right
Logical OR || Left to
right
Conditional ?: Right to left
Assignment = += -= *= /= %=
>>= <<= &= ^= |=
Right to left
Comma , Left to
right