java basic operators n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Java Basic Operators PowerPoint Presentation
Download Presentation
Java Basic Operators

Loading in 2 Seconds...

play fullscreen
1 / 39

Java Basic Operators - PowerPoint PPT Presentation


  • 159 Views
  • Uploaded on

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

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

PowerPoint Slideshow about 'Java Basic Operators' - andra


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
slide2

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

slide3

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:

slide4

THE RELATIONAL OPERATORS

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

slide5

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

THE LOGICAL OPERATORS

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

slide10

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

slide11

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

slide13

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:

BufferedReaderbr =

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

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

slide14

READING CHARACTERS FROM CONSOLE - EXAMPLE

Enter characters, 'q' to quit.

123abcq

1

2

3

a

b

c

q

slide15

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

slide16

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.

slide17

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.
slide18

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

slide19

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

slide20

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

slide21

STATIC VARIABLE – EXAMPLE 2

public class InstanceCounter {

private static intnumInstances = 0;

protected static intgetCount(){

return numInstances;

}

private static void addInstance(){

numInstances++;

}

InstanceCounter(){

InstanceCounter.addInstance();

}

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

slide22

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.

slide23

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

slide24

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.

slide25

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.

slide26

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

slide27

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.
slide28

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
  • }
slide29

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.
slide30

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();

}

slide31

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();
slide32

THE ABSTRACT MODIFIER

public abstract class SuperClass{

abstract void m(); //abstract method

}

class SubClassextendsSuperClass{

// implements the abstract method

void m(){

.........

}

}

slide33

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

}

slide34

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.
slide35

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.
slide36

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();

}

slide37

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

slide38

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.
slide39

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.