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

Operators

Uploaded by

guru cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Operators

Uploaded by

guru cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

O Java Supports a rich set of operators. An.

operator is a Symsmi

that tells the computer to perform certain Mathematica] (063;

Logical manipulations. a;

o Operators are used in Programs t0 manipulate data andé

variables. There are various types of operators are there, i

1. Arithmetic Operators. ' lt;

2. Relational Operators (or) Comparission Operators_ g

3. Logical Operators. 1

4. Assignment Operators.

5. Increment and Decrement Operators (or) Unary

Operators. '

6. Conditional Operators.

7. Bit wise Operators.

8- Special Operators.

1' Arithmetic OperatOrS 2 The Arithmetic Operators are +,

-, *, /, 0/0.

Ex : a + b

a-b

a*b

ta/b_

a%b

2. 312,122,111 gaefftors i The Relational Operators are <, <

Ex : a < b
a<=b

a>b

/a>=b

a==b

al=b

3, Logical Operators : The Logical Operators are & &, | | , !.

Ex: (a>b)&&(c<d).

4. Assignment Operators : The Assignment Operators are +

:,-=,*=', | :_

Variable type of Operator = Expression ; '

Ex:X+=(x+y) :> x=x+<x+y)

5. Increment and Decrement Operators : The Increment

and Decrement Operators are + +, - -.

Ex: ++m(or)m++:m+1.

--m(or)m-- :> m-l.

6. Conditional Operators : The Conditional Operators are as

follows.

Exp1?Exp2:Exp3;

Exp 1 is evaluated first, if it is “true”, Exp 2 is evaluated and

if exp 1 is “false”, Exp 3 is evaluated.

Ex:x=a>b?a:b; :> if(a>b)

x=a;

else

x=b;
7. Bit Wise Operators : Bit Wise Operators are used for testing

the bits (or) shifting them to the left (or) right. These Operators

may not be applicable to float (or) double.

The Bit Wise Operators are :

& - Bit wise AND. `

| - Bit wise OR.

" - Bit wise Exclusive OR.

~ - One’s Complement. '

<< - Shift Left. i

>> - Shift Right

<<< _ shift Left with zero fill. '

>>> - Shift Right with zero fill.

8. Special Operators : The Special Operators are Instance of

operator and Member selection operator (or) Dot Operator (.). l

Instance of Operator: This Operator determines whether

the object belongs to a particular class (or) not.

Example .° Person instance of student ;

It is true if the object “person” belongs to the class “student”

; other wise it is false.

Dot Operator : The Dot Operator (.) is used to access the

instance Variables and methods of class objects.

Example : person age // Reference to the variable age.

It is also used to access classes and sub-packages from a package. ;


Separators help define the structure of a program. The table lists the Java separators.

v' V Separator

( ) Encloses arguments in method definitions and calling; adjusts precedence in

_ arithmetic expressions; surrounds cast types and delimits test expressions in

_ flovv control statements

l } defines blocks of code and automatically initializes arrays

l ] declares array types and dereferences array values

_ ; terminates statements

' , Separates successive identifiers in variable declarations; chains statements in

the test, expression of a for loop

g ~ Selects a field or method from an object; Separates package names from sub_

package and class names .

5 Used after loop labelS ,


The Java programming language supports three kinds of comments:

1. Single Line Comment :

Double slashes in front of a single line comment

The compiler ignores everything from // to the end of the line.

Example :

int i=5;

// this is single line comment

2. Multiple Line Comments :

Matching slash-asterisk (/*) and asterisk-slash (*/) to bracket multi-line comments

The compiler ignores everything from /* to */.

Example:

System.out.println (“welcome to java program”);

/* this is multi line I

Comments*/

/* text */ g

` Matching slash-double asterisk (/**) & asterisk-slash("‘/)` for document comments.

, The compiler ignores this kind of comment, .just like it ignores comments that use /**

' and */. _ `

l l Example: '_ 4 v

l s /** this is documentation comment */ I < w


Sometimes one thread needsto know when another thread is ending. ln java, isAlive()

and join() are two different methods to check whether a thread has finished its execution

The isAlive() method return true if the thread upon which it iS Called lS Stlll running

otherwise it return false.

Final boolen isAlive()

The join() method waits until the thread on which it is called terminates.

Final void join() throws lnterruptedException

Using join() method, we tell our thread to wait until the specified thread completes its

execution. There are overloaded version of join method, which allows us to specify

time for which you want to wait for the specified thread to terminate.

Final void join(long millisecond) throws Interrupted Exception

Example program: `

import java.|ang.*;

public class ThreadDemo implements Runnable{

public void run() {

Thread t = Thread.currentThread();

System.out.print(t.getName());

//checks if this thread is alive

System.out.println(“, inside status = “ + t.isA|ive());

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

Thread t = new Thread(new ThreadDemo(),”demothread");

// this will call run() function

t.start();

// waits for this thread to die


Demothread, inside status = true

Demothread, status = false

Suspend() method is used to suspend any thread from critical section on specified

time.

Resume() method is used to revoke suspended thread.

The suspended thread will be in blocked state until resume() method is called on it.

These methods are deprecated, as when not used with precautions, the thread locks, if

' held, are kept in inconsistent state or may lead to deadlocks.

.H i v i \ 1 “UuimiviiquU

ANSWER KEY

PART - A

ANSWER ALL THE QUESTIONS

1. Why is java architectural- neutral ?

Ans: Java compiler generates an architecture-neutral object file format Which makes the

compiled code to be executable on many processors, with the presence of Java runtime

system.

2. Write a java program that uses command -line arguments ?


Ans: A command - line argument is the information that follows the programs name on the

command line. The command line arguments are stored as string array passed to main(). For

example the following program displays all ofthe command line arguments.

public class main

public static void main(string args[]){

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

System.out.println ( “args[“+i+”]:”+args[i]);

}_

Output :

Java main this is suresh p

args [0]: this

agrs [1]: is

agrs [2]: suresh

3. List various types of iteration statements in java ?

Ans: There may be a situation when we need to execute a block of code several number of

times, and is often referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three

loops:

l while Loop

I do...while Loop

I for Loop

while loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:

The syntax ofa while loop is:

While (Boolean_expression)

//Statements -

},

When executing, ifthe boolean_expression result is true, then the actions inside the loop will

be executed. This will continue as long as the expression result is true. _ _

Here, key point ofthe while loop is that the loop might not ever run. When the expression is

tested and the result is false, the loop body will be skipped and the first statement after the

while loop will be executed.

do...while loop:

A do...while loop is similar to a while loop, except that a do...while loop iS guaranteed t0

execute at least one time.

Syntax:

The syntax ofa do...while loop is:

do

//Statements

}while (Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the

loop execute once before the Boolean is tested. If the Boolean expression is true, the flow of

control jumps back up to do, and the statements in the loop execute again. This process

repeats until the Boolean expression is false.

for loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that

needs to execute a specific number oftimes. A for loop is useful When you know how many

times a task is to be repeated.

Syntax:

The syntax of a for loop is:

for(initializationgBoolean_expression; update)

//Statements

4. What is labelled break ?

Ans: The break statement terminates the labelled statement; it does not transfer the flow of

Control to the label. Control flow is transferred to the statement immediately following the

labelled (terminated) statement. `

This means you can only break loops that are currently being executed.

Consider this example:

first:

for( int i = 0; i < 10; i++) {

second:
class MultithreadingDemo implements Runnable{

public void run(){

System.out.println("My thread is in running state.");

public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();

Thread tobj :new Thread(obj);

tobj.start();

Output:

My thread is in running state.

~ ethod 2: Thread creation by extending Thread class

o This is the second way of creating a thread. Here we need to create a new class that

extends the Thread class.

° The class should override the run() method which is the entry point for the new thread.

° Call start() method to start the execution of a thread.

Example :

class MultithreadingDemo extends Thread{

public void run(){

System.out.println("My thread is in running state.");

}
public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();

obj.start();

Output:

My thread is in running state.

14. Explain about interface with syntax and example?

Ans: Interface: An interface is basically a kind of class like classes, interfaces contains

methods and variables but with a major difference. The difference is that interfaces define

only abstract methods and final fields .this means that interfaces do not specify the any code

to implement these methods and data fields contain only constants.

if? _

b. adding variablesgData is encapsulated in a'class by placing data fields inside the body of

the class definition. These variables are called`instance variables. Because they are created

when ever an object ofthe class is instantiate§ We can declare the instance variables exactly

the same way as we declare local variables.

Example: class Rectangle £AQQWZQQ/

{»__, ___! V

int length;

int width;

}
The class Rectangle contains two integer type instance variablesDIt is allowed to declare them

in one line as

int length, width;

Adding methodsQA class with only data fields has no life. The objects created by such a

class cannot respond to any messages) We must there fore add methods that are necessary for

manipulating the data contained in the class. Methods are declared inside the body of the

class but immediately after the declaration of instance variables. The general form of a

method declaration is:

type methodname (parameter list)

method body;

Method declaration has four basic parts:

1. the name of the method (method name)

2. the type of the value the method returns (type)

3. a list of parameters (parameter list)

4. the body ofthe method.

/c. Creating objects:

creating objects is also referred to as instantiating an object. Objects in java are created using

the new operator. The new operator creates an object of the specified class and returns a

reference to that object.

Example:

Rectangle rectl;

Rect1= new Rectangle( );

The first statement declares a variable to hold the object reference and the second one
actually assigns the object reference to the variable. The variable rectl is now an object of the

rectangle class.

7;;[0w to create multiple threads in java? Explain with an example java program.

W!!

yegliod 1: Thread creation by implementing Runnable Interface

° One way of creating a thread is to create a class that implements the Runnable

interface. We must need to give the definition of run() method.

° This run method is the entry point for the thread and thread will be alive till run

method finishes its execution.

° Once the thread is created it will start running when start() method gets called.

Basically start() method calls run() method implicitly.

class MultithreadingDemo implements Runnable{

public void run(){

System.out.println("My thread is in running state.");

public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();

Thread tobj :new Thread(obj);


tobj.start();

Output:

My thread is in running state. `

~ ethod 2: Thread creation/by extending Thread class

o This is the second way of creating a thread. Here we need to create a new class that

extends the Thread class.

° The class should override the run() method which is the entry point for the new thread

as described above.

° Call start() method to start the execution of a thread.

Example :

class MultithreadingDemo extends Thread{

public void run(){

System.out.println("My thread is in running state.");

public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();

obj.start(); v

Output:

My thread is in running state.


14. Explain about interface with syntax and example?

Ans: Interface: An interface is basically a kind of class like classes, interfaces contains

methods and variables but with a major difference. The difference is that interfaces define

only abstract methods and final fields .this means that interfaces do not specify the any code

to implement these methods and data fields contain only constants.

lt is the responsibility ofthe class that implements an interface to define the code for

implementation ofthese methods.

The general form of interface is:

interface lnterfacename

Variable declaration;

Methods declarations;

}i

Here interface is the keyword and interface name is any valid java variable.

Variables are declared as follows:

static final type variable name=value;

Methods are declared as follows:

return_type methodnamel (parameter list);

Example:

interface Area
{

final static float pi=3.l4F;

float compute(float x, float y);

}_

class Rectangle implements Area

Public float compute( float X, float y);

return (x*y);

class Circle implements Area

{t

public float compute (float x, float y)

return (pi*x*X);

class InterfaceTest

public static void main(String args[])

Rectangle rect = new Rectangle();

Circle cir :new Circle ();

Area area;
area = rect;

System.out.println(“Area of the rectangle = “+area. compute(10,20));

area =cir;

System.out.println(“Area ofthe Circle = “+area. Compute (10,0));

Streams are classifieds into two types,~

1. Byte Streams.

2. Character Streams.

In Byte stream data transfer perform in the form of 8 bit bytes Th

' - ist ~ ' -

two types of streams lnputStream and OutputStream VPQ divided into

These two are abstract classes I -

. nputStream class having number of sub classes


Hierarchies forFilelnputStream

I.

l SequencelnputStream

, ByteArrayInputStream

m,

..

ObjectlnputStream ' '

FIG 5.3 :

Hierarchies forFileOutputStream

l FileOutputStream `

ByteArrayOutputStream

l DataOutputStream '

l PipedOutputStream

ObjectOutputStream

l l FilterOutputStream

I BufferedOutputStream

In charac;;trearr_nwriuatatrartsferIanerform in the form characters. It handle input and*

output as characters. There are two types of abstract classes Reader and Writer_

Reader Hierarchy:

,
¥

.o

FIG 5.5 : _ `

Writer Hierarchy: ` y 5 a

0>

*m

*w

'5

You might also like