Java Operators

Operators are used to manipulate variables. There are following type of operators in java.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations. Following is the list of arithmetic operators in java.

Symbol Operator Example
 + Additive Operator  r =  n + 1;
 – Subtraction Operator  r =  n – 1;
 * Multiplication Operator  r =  n * 1;
 / Division Operator  r = n / 1;
 % Remainder Operator  r = n % 1;

Relational Operators

Relational operators are used to compare two variable and it will return true or false depending on the operator and values are variables being compared.

Symbol Operator Example
 == Equal to  a = = b
 != Not equal to  a ! = b
 > Greater than  a > b
 <  Less than  a < b
 >= Greater than or equal to  a > = b
 <= Less than or equal to  a > = b

Bitwise Operators

The bitwise operators work on bit level. They are used to manipulate the contents of variables at a bit level.

Symbol Operator Example
 ~ Unary bitwise complement ~var1
 & Bitwise AND var1 & var2
 | Bitwise inclusive OR var1 | var2
 ^ Bitwise exclusive OR var1 ^ var2
 << Signed left shift var1 << var2
 >> Signed right sift var1 >> var2
 >>> Unsigned right shift var1 >>> var2

Logical Operators

Logical operators are used to perform logical operations on variables. It return true or false depending on the value of variables and operator used.

Symbol Operator
 & AND
 && Conditional-AND
 | OR
 || Conditional-OR
 ! NOT
 ? : Ternary

Assignment Operators

Assignment operators are used to perform assignment operations on variables.

Symbol Operator Example
 = Simple assignment r = a + b
 += Add and Assignment r += a equivalent r = r + a
 -= Subtract and Assignment r -= a equivalent r = r – a
 *= Multiply and Assignment r *= a equivalent r = r * a
 /= Divide and Assignment r l= a equivalent r = r / a

Java Conditional Statements

Conditional statements are used to evaluate one or more logical conditions along with a block of statements to be executed if the condition return true and optionally another block of statements to be executed if the logical condition return false. There are following conditional statements in java.

If Statement

The if statement is used to execute a block of code only if the applied condition (Boolean expression) return true.

Syntax:

if (condition) {

statements to be executed

}

The default and break statements are optional. Also there can be any number of case blocks in switch statement.

If – Else statement

The if – else statement consist of one if statement with a block of code to be executed if the condition return true and another block of code under else clause which is executed if the condition return false.

Syntax:

if (condition) {

statements to be executed if condition return true

} else {

statements to be executed if condition return false

}

If- Else – If statement

This is a nested if – else statement. It consist of multiple if conditions and an else statement. Each if condition has a block of code which is execute when the condition return true.

Syntax:

if (condition 1) {

statements to be executed if condition 1 return true

} else if(condition 2){

statements to be executed if condition 2 return true

} else {

statements to be executed if all condition return false

}

Switch Statement

The switch statement is used to test a variable for equality against a list of values. The switch statement is enclosed in a switch block and one or more case and/or default labels. The switch statement evaluate each case and execute the appropriate case block.

Syntax:

switch(expression){

case value1 :

statements to be executed

break;

case value2 :

statements to be executed

break;

case value3 :

statements to be executed

break;

default :

statements to be executed

}

The default and break statements are optional also there can be any number of case blocks in switch statement.

Java Loops

Loops are used to repeat the execution of a statement or block of statements while the provided condition returns true. There are following type of java loops.

Java For Loop

for loop executes a bunch of statements continuously to accomplish a particular condition. A for loop is used when you know how many time a block of code to be repeated.

For Loop Syntax

for(initialization; condition; update)

{

//for loop body

}

Initialization: initialize the loop control variable

Condition: a boolean expression

Update: update loop control variable

For Loop Example

public class JavaLoop {

public static void main(String args[]) {

for(int i = 1; x <= 10; i++) {

System.out.print(“i = ” + i );

System.out.print(“\n”);

}

}

}

Output:

i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10

Java While Loop

The while loop is used when you don’t want to repeat the execution of the code for a specific number of time. Instead you want to repeatedly execute code until a specified condition is met. The condition is tested each time before execution of the loop body.

While loop syntax

while(condition)

{

//while loop body

}

While loop example

public class JavaLoop{

public static void main(String args[]) {

int i = 1;

while( i <= 10 ) {

System.out.print(“Repetition number = ” + i );

System.out.print(“\n”);

i++;

}

}

}

Output:

Repetition number = 1
Repetition number = 2
Repetition number = 3
Repetition number = 4
Repetition number = 5
Repetition number = 6
Repetition number = 7
Repetition number = 8
Repetition number = 9
Repetition number = 10

Java do..while loop

The only difference between while and do..while loop is that the body of do..while is executed before testing the condition which mean the body of do..while loop will be executed at least once.

do..while loop syntax

do

{

//do..while loop body

} while(condition);

do..while loop example

public class JavaLoop{

public static void main(String args[]) {

int i = 1;

do {

System.out.print(“Repetition number = ” + i );

System.out.print(“\n”);

i++;

} while( i <= 10 );

}

}

Output:

Repetition number = 1
Repetition number = 2
Repetition number = 3
Repetition number = 4
Repetition number = 5
Repetition number = 6
Repetition number = 7
Repetition number = 8
Repetition number = 9
Repetition number = 10

Java Arrays

The array data structure is a collection of same type of variables. Java arrays are used to store fixed size sequential collection of same type of elements. Items in array are called elements and they can be accessed by their index. This is how to declare, initialize and access arrays in java.

//declaring array of type integer
int[] myArray;

//allocating memory
myArray= new int[10];

//assigning values
myArray[0] = 5;
myArray[1] = 10;
myArray[2] = 15;
myArray[3] = 20;
myArray[4] = 25;
myArray[5] = 30;
myArray[6] = 35;
myArray[7] = 40;
myArray[8] = 45;
myArray[9] = 50;

//retrieving values
System.out.println(“Value at index 0 = “+ myArray[0]);
System.out.println(“Value at index 5 = “+ myArray[5]);

Processing Arrays

Usually loops are used to process arrays. We can use for loop and foreach loop to process array.

Processing Array Example

public class ArrayExample {

public static void main(String[] args) {

int[] myArray= {5,10,15,20,25,30,35,40,45,50};

int total = 0;

// processing array elements

for (int i = 0; i < myArray.length; i++) {

System.out.println(“Value at index ” + i + ” is = ” + myArray[i]);

total = total + myArray[i];

}

System.out.println(“Total is = ” + total);

}

}

Output:

Value at index 0 is = 5
Value at index 1 is = 10
Value at index 2 is = 15
Value at index 3 is = 20
Value at index 4 is = 25
Value at index 5 is = 30
Value at index 6 is = 35
Value at index 7 is = 40
Value at index 8 is = 45
Value at index 9 is = 50
Total is = 275

foreach Loop

The foreach loop makes it more easy to process arrays in java. You don’t need to use the index to access array element.

foreach Example

public class ArrayExample {

public static void main(String[] args) {

int[] myArray= {5,10,15,20,25,30,35,40,45,50};

int total = 0;

// processing array elements

for (int myVal: myArray) {

System.out.println(myVal);

total = total + myVal;

}

System.out.println(“Total is = ” + total);

}

}

Output:

5
10
15
20
25
30
35
40
45
50
Total is = 275

Java Files & I/O

To perform input and output(I/O) operations in java we use java.io package which contains classes for these operations. Most application needs to read input from a source, process it and generate output depending on input.

InputStream: InPutStream is used when you want to read data from a source.

OutPutStream: OutPutStream is used when you want to write data at some destination.

In following example we are reading a text file and displaying its contents on screen using java.io package classes.

import java.io.*;

public class JavaReadTextFile {

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

{

FileInputStream ins = null;

try {

ins = new FileInputStream(“textfile.txt”);

BufferedReader br = new BufferedReader(new InputStreamReader(ins));

String c = null;

while ((c = br.readLine()) != null) {

System.out.println(c);

}

if (br != null) {

br.close();

}

} finally {

if (ins != null) {

ins.close();

}

}

}

}

Output:

The contents of textfile.txt will be displayed on screen line by line.

Java Byte Stream

Byte stream in java is used to perform input and output operations of 8 bit bytes. The following example will copy the contents of a text file to another text file using FileInputStream and FileOutputStream.

import java.io.*;

public class JavaCopyFileContents {

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

{

FileInputStream fin = null;

FileOutputStream fout = null;

int ch;

try {

fin = new FileInputStream(“inputtextfile.txt”);

fout = new FileOutputStream(“outputtextfile.txt”);

while ((ch = fin.read()) != -1) {

fout.write(ch);

}

fin.close();

fout.close();

} catch (IOException e){

System.out.println(“Something went wrong”);

}

}

}

Output:

A new file “outputtextfile.txt” will be created with “inputtextfile.txt” contents.

Standard Streams

All programming languages are required to have standard I/O streams so a program can take input form user’s keyboard and display output on user’s screen after processing the input. Java has following standard I/O streams.

System.in: standard input stream

System.out: standard output stream

System.err: standard error stream

Java Directories

A directory is a type of file which can contain other directories and files. In java File object is used to create new directories and list the files and sub-directories. The mkdir() and mkdirs() methods are used to create directories. If parent directories don’t exists the mkdir() method will return false. mkdirs() methods create both the directory and all parent directories.

Creating Directory

import java.io.File;

public class JavaCreateDirectory {

public static void main(String args[]) {

String dirPath = “C:/javaexamples/files”;

File f = new File(dirPath);

f.mkdirs();

}

}