Java Basic Operators

1 / 44

# Java Basic Operators - PowerPoint PPT Presentation

Java Basic Operators. JAVA BASIC OPERATORS. 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

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'Java Basic Operators' - sinead

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### Java Basic Operators

JAVA BASIC OPERATORS

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:

THE RELATIONAL OPERATORS

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

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):

THE LOGICAL OPERATORS

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

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

CONDITIONAL OPERATOR ( ? : ): 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

READING CHARACTERS FROM CONSOLE

To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. Here is most common syntax to obtain BufferedReader:

Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to read a string from the console.

READING CHARACTERS FROM CONSOLE - EXAMPLE

Enter characters, 'q' to quit.

123abcq

1

2

3

a

b

c

q

READING STRINGS FROM CONSOLE - EXAMPLE

Enter lines of text.

Enter 'end' to quit.

This is line one

This is line one

This is line two

This is line two

end

end

MODIFIERS – (KEYWORDS ADDED TO A CLASS/METHOD/VARIABLE)

Visible to the class only (private).

Visible to the package and all subclasses (protected).

Visible to the world (public).

Visible to the package, the default. No modifiers are needed.

THE STATIC MODIFIER

• Static Variables
• The static key word is used to create such variable that will exist independently of any instances (objects) created for the class.
• Only one copy of the static variable exists regardless of the number of instances (objects) of the class.
• Static variables are also known as class variables.
• Local variables (variables of a method) cannot be declared static.
• Static Methods
• A static method belongs to the class rather than object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• Static method can access static data member and can change the value of it.
• Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.

STATIC VARIABLE – EXAMPLE 1

class Student{

introllno;

String name;

static String college =“JAYPEE";

Student(intr,String n){

rollno = r;

name = n;

}

void display(){

System.out.println(rollno+" "+name+“ "+college);

}

public static void main(String args[]){

Student s1 = new Student (111,"Karan");

Student s2 = new Student (222,"Aryan");

s1.display();

s2.display();

}

}

111 Karan JAYPEE

222 Aryan JAYPEE

Static property is shared to all objects.

Advantage: It makes the program memory efficient (i.e it saves memory).

STATIC VARIABLE – EXAMPLE - PROGRAM OF COUNTER WITHOUT STATIC VARIABLE

class Counter{

intcount=0; //will get memory everytime when instance is created

Counter(){

count++;

System.out.println(count);

}

public static void main(String args[]){

Counter c1=new Counter();

Counter c2=new Counter();

Counter c3=new Counter();

}

}

1

1

1

STATIC VARIABLE – EXAMPLE - PROGRAM OF COUNTER USING STATIC VARIABLE

class Counter{

static intcount=0;//will get memory only once and retain its value

Counter(){

count++;

System.out.println(count);

}

public static void main(String args[]){

Counter c1=new Counter();

Counter c2=new Counter();

Counter c3=new Counter();

}

}

1

2

3

STATIC VARIABLE – EXAMPLE 2

public class InstanceCounter {

private static intnumInstances = 0;

protected static intgetCount(){

return numInstances;

}

private static void addInstance(){

numInstances++;

}

InstanceCounter(){

}

public static void main(String[] arguments){

System.out.println("Starting with " +

InstanceCounter.getCount() + " instances");

for (inti = 0; i < 500; ++i){

new InstanceCounter();

}

System.out.println("Created " +

InstanceCounter.getCount() + " instances");

}

}

Started with 0 instances

Created 500 instances

STATIC METHOD– EXAMPLE 1

//Program of changing the common property of all objects(static field).

class Student{

introllno;

String name;

static String college = “JAYPEE";

static void change(){

college = “IIM BANGALORE";

}

Student(int r, String n){

rollno = r;

name = n;

}

void display (){

System.out.println(rollno+" "+name+" "+college);

}

Note: Static method can not access non-static attribute.

STATIC METHOD– EXAMPLE 1

public static void main(String args[]){

Student.change();

Student s1 = new Student (111,"Karan");

Student s2 = new Student (222,"Aryan");

Student s3 = new Student (333,"Sonoo");

s1.display();

s2.display();

s3.display();

}

}

111 Karan IIM BANGALORE

222 Aryan IIM BANGALORE

333 Sonoo IIM BANGALORE

STATIC METHOD– EXAMPLE 2

//Program to get cube of a given number by static method

class Calculate{

staticintcube(int x){

return x*x*x;

}

public static void main(String args[]){

intresult=Calculate.cube(5);

System.out.println(result);

}

}

125

Restrictions for static method

The static method can not use non static data member or call non-static method directly.

"this" and "super" cannot be used in static context.

STATIC METHOD– CAN NOT ACCESS TO NON-STATIC MEMBER

class A{

int a=40; //non static

public static void main(String args[]){

System.out.println(a);

}

}

Compile Time Error

Why main method is static?

Because object is not required to call static method.

If main() method would have been a non-static method, JVM would have to create object first then call main() method; that will lead to the problem of extra memory allocation.

STATIC BLOCK – anything written in {} is called a Block.

Is used to initialize the static data member.

It is executed before main method at the time of classloading.

class A{

static{

System.out.println("static block is invoked");

}

public static void main(String args[]){

System.out.println("Hello main");

}

}

static block is invoked

Hello main

Can we execute a program without main() method?

Yes, one of the way is static block but in previous version of JDK not in JDK 1.7

THE FINAL MODIFIER

• Final Variables
• A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to an different object.
• However the data within the object can be changed. So the state of the object can be changed but not the reference.
• With variables, the final modifier often is used with static to make the constant a class variable.
• Final Methods
• A final method cannot be overridden by any subclasses. As mentioned previously the final modifier prevents a method from being modified in a subclass (incase of inheritance).
• The main intention of making a method final would be that the content of the method should not be changed by any outsider.
• Final Classes
• If a class is marked as final then no class can inherit any feature from the final class.

THE FINAL MODIFIER - EXAMPLE

public class Test{

finalintvalue = 10;

// The following are examples of declaring constants:

public static finalintBOXWIDTH = 6;

static final String TITLE = "Manager";

public void changeValue(){

value = 12; //will give an error

}

}

Test.java:8: error: cannot assign a value to final variable value

value = 12; //will give an error

^

1 error

• public class Test{
• public final void changeName(){
• // body of method
• }
• }
• public final class Test {
• // body of class
• }

THE ABSTRACT MODIFIER

• Abstract Class:
• An abstract class can never be instantiated.
• It can only be extended.
• A class cannot be both abstract and final (since a final class cannot be extended).
• If a class contains abstract methods then the class should be declared abstract.
• An abstract class may contain both abstract methods as well normal methods.

THE ABSTRACT MODIFIER

abstract class Caravan{

private double price;

private String model;

private String year;

public abstract void goFast(); //an abstract method

public abstract void changeColor();

}

THE ABSTRACT MODIFIER

• Abstract Method:
• It is a method declared without any implementation (definition).
• The methods body(implementation) is provided by the subclass.
• Abstract methods can never be final or strict.
• Any class that extends an abstract class must implement all the abstract methods of the super class unless the subclass is also an abstract class.
• If a class contains one or more abstract methods then the class must be declared abstract. An abstract class does not need to contain abstract methods.
• The abstract method ends with a semicolon.
• public abstract void goFast();

THE ABSTRACT MODIFIER

public abstract class SuperClass{

abstract void m(); //abstract method

}

class SubClassextendsSuperClass{

// implements the abstract method

void m(){

.........

}

}

INTERFACES

• An interface is not a class.
• An interface is a collection of abstract methods.
• A class implements an interface, thereby inheriting the abstract methods of the interface.

/* File name : NameOfInterface.java */

import java.lang.*;

//Any number of import statements

public interface NameOfInterface

{

//Any number of final, static fields

//Any number of abstract method declarations

}

INTERFACES

• Properties:
• An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
• Methods in an interface are implicitly public
• An interface is similar to a class in the following ways:
• An interface can contain any number of methods.
• An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
• The bytecode of an interface appears in a .class file.

INTERFACES

• However, an interface is different from a class in several ways, including:
• We cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields.
• The only fields that can appear in an interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.

INTERFACES

• Implementing Interfaces:
• When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviours of the interface.
• If a class does not perform all the behaviours of the interface, the class must declare itself as abstract.
• A class uses the implements keyword to implement an interface.

Example:

/* File name : Animal.java */

interface Animal {

public void eat();

public void travel();

}

INTERFACES

/* File name : MammalInt.java */

public class MammalIntimplements Animal{

public void eat(){

System.out.println("Mammal eats");

}

public void travel(){

System.out.println("Mammal travels");

}

public intnoOfLegs(){

return 0;

}

public static void main(String args[]){

MammalInt m = new MammalInt();

m.eat();

m.travel();

}

}

Mammal eats

Mammal travels

INTERFACES

• Extending Interfaces:
• An interface can extend another interface.
• The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

INTERFACES

//Filename: Sports.java

public interface Sports

{

public void setHomeTeam(String name);

public void setVisitingTeam(String name);

}

//Filename: Football.java

public interface Football extends Sports

{

public void homeTeamScored(int points);

public void visitingTeamScored(int points);

public void endOfQuarter(int quarter);

}

//Filename: Hockey.java

public interface Hockey extends Sports

{

public void homeGoalScored();

public void visitingGoalScored();

public void endOfPeriod(int period);

public void overtimePeriod(intot);

}

Extending Multiple Interfaces:

A Java class can only extend one parent class.

Multiple inheritance is not allowed in case of classes.

Interfaces are not classes, however, and an interface can extend more than one parent interface.

WRAPPER CLASSES - INTRO

• Java is an object-oriented language and can view everything as an object.
• A simple file can be treated as an object (with java.io.File),
• An address of a system can be seen as an object (with java.util.URL),
• An image can be treated as an object (with java.awt.Image)
• A simple data type can be converted into an object (with wrapper classes).
• Wrapper classes are used to convert any data type into an object.
• The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Java has 8 primitive data types (as defined in table in next slide)
• A data type is to be converted into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced wrapper classes.

WHAT ARE WRAPPER CLASSES?

• A wrapper class wraps (encloses) around a data type and gives it an object appearance.
• Wherever, the data type is required as an object, this object can be used.
• Wrapper classes include methods to unwrap the object and give back the data type.
• int k = 100;
• Integer it1 = new Integer(k);
• The int data type k is converted into an object, it1 using Integer class.
• The it1 object can be used in Java programming wherever k is required as an object.
• The following code can be used to unwrap (getting back int from Integer object) the object it1.
• int m = it1.intValue();
• System.out.println(m*m); // prints 10000

intValue() is a method of Integer class that returns an int data type.

HIERARCHY OF WRAPPER CLASSES

• The super class of all numeric wrapper classes is Number.
• The super class for Number, Character and Boolean is Object.
• All the wrapper classes are defined as final and thus designers prevented them from inheritance.

IMPORTANCE OF WRAPPER CLASSES

• There are mainly two uses with wrapper classes.
• To convert simple data types into objects, that is, to give object form to a data type; here constructors are used.
• To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.
• Constructors of wrapper classes are used to convert data types into objects.
• The methods of the form XXXValue() are used to retrieve back the data type from the object.