You are on page 1of 101

Chapter 1

Basic java programming

Basic java programming By Adugna H 1


What is Java?
• Java is a general-purpose, high-level programming language.
• The features of Java
• Java program is both compiled and interpreted.

• Write once, run anywhere

• Java is a software-only platform running on top of other, hardware-based platforms.


• Java Virtual Machine (Java VM)

• The Java Application Programming Interface


(JAVA API)

Basic java programming By Adugna H 2


Basic java programming By Adugna H 3
Features of Java
• Simple • Portable
• Architecture-neutral • High-Performance
• Object-Oriented • Robust
• Distributed • Secure
• Compiled • Extensible
• Interpreted • Well-Understood
• Statically Typed
• Multi-Threaded
• Garbage Collected
Basic java programming By Adugna H 4
Basic java programming By Adugna H 5
Basic java programming By Adugna H 6
Basic java programming By Adugna H 7
Basic java programming By Adugna H 8
Start Java
• A programming language specifies the words and symbols that we
can use to write a program.
• A programming language employs a set of rules that dictate how
the words and symbols can be put together to form valid program
statements.
• The Java programming language was created by Sun
Microsystems, Inc.
• It was introduced in 1995 and it's popularity has grown quickly.

Basic java programming By Adugna H 1-9


Java Program Structure
• In the Java programming language:
– A program is made up of one or more classes
– A class contains one or more methods
– A method contains program statements

• These terms will be explored in detail throughout the


course
• A Java application always contains a method called
main
Basic java programming By Adugna H 1-10
Lincoln.java
public class Lincoln
{
//-----------------------------------------------------------------
// Prints a presidential quote.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("A quote by Abraham Lincoln:");
System.out.println ("Whatever you are, be a good one.");
}
}

Basic java programming By Adugna H 1-11


Java Program Structure
// comments about the class
public class MyProgram
{
class header

class body

Comments can be placed almost anywhere


}

Basic java programming By Adugna H 1-12


Java Program Structure
//comments about the class
public class MyProgram
{

// comments about the method


public static void main (String[] args)
Class body
{
method header
method body
}

Basic java programming By Adugna H 1-13


Comments
• Comments in a program are called inline
documentation
• They should be included to explain the purpose of
the program and describe processing steps
• They do not affect how a program works
• Java comments can take three forms:
// this comment runs to the end of the line

/* this comment runs to the terminating


symbol, even across line breaks */

/** this is a javadoc comment */

Basic java programming By Adugna H 1-14


Identifiers
• Identifiers are the words a programmer uses in a program
• An identifier can be made up of letters, digits, the underscore
character ( _ ), and the dollar sign
• Identifiers cannot begin with a digit
• Java is case sensitive - Total, total, and TOTAL are different
identifiers
• By convention, programmers use different case styles for different
types of identifiers, such as
– title case for class names - Lincoln
– upper case for constants - MAXIMUM

Basic java programming By Adugna H 1-15


White Space
• Spaces, blank lines, and tabs are called white space
• White space is used to separate words and symbols
in a program
• Extra white space is ignored
• A valid Java program can be formatted many ways
• Programs should be formatted to enhance
readability, using consistent indentation

Basic java programming By Adugna H 1-16


Lincoln2.java

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


System.out.println("A quote by Abraham Lincoln:");
System.out.println("Whatever you are, be a good one.");}}

Basic java programming By Adugna H 1-17


Basic java programming By Adugna H 18
Variables
 The variable is the basic unit of storage in a Java program. A variable is defined by
the combination of an identifier, a type, and an optional initializer.
 In addition, all variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable
 In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
 type identifier [ = value][, identifier [= value] ...] ;
 The type is one of Java’s atomic types, or the name of a class or interface.
 The identifier is the name of the variable. You can initialize the variable by
specifying an equal sign and a value.
Examples

Here are several examples of variable declarations of various types.


Note that some
include an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Names of Variables
• Use only the characters 'a' through 'z', 'A' through 'Z', '0'
through '9', character '_', and character '$'.
• A name cannot contain the space character.
• Do not start with a digit.
• A name can be of any reasonable length.
• Upper and lower case count as different characters. I.e.,
Java is case sensitive. So SUM and Sum are different
names.
• A name cannot be a reserved word (keyword).
• A name must not already be in use in this block of the
program.
A class can contain any of the following variable types.

 Local variables: Variables defined inside methods, constructors or blocks are


called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
 Instance variables: Instance variables are variables within a class but outside
any method. These variables are instantiated when the class is loaded.
Instance variables can be accessed from inside any method, constructor or
blocks of that particular class.
 Class variables: Class variables are variables declared with in a class, outside
any method, with the static keyword.
Classes and Objects
 The class is at the core of Java.
 It is the logical construct upon which the entire Java Language is built because it
defines the shape and nature of an object.
 As such, the class forms the basis for object-oriented programming in Java.
 Any concept you wish to implement in a Java program must be encapsulated
within a class.
 it defines a new data type.
 Once defined, this new type can be used to create objects of that type.
 Thus, a class is a template for an object, and an object is an instance of a class.
 Because an object is an instance of a class, you will often see the two words
object and instance used interchangeably.
The General Form of a Class
 When you define a class, you declare its exact form and nature.
 You do this by specifying the data that it contains and the code
that operates on that data.
 While very simple classes may contain only code or only data,
most real-world classes contain both.
 A class is declared by use of the class keyword.
 The general form of a class definition is shown here:
class ClassName {
type instance-variable1;
type instance-variable2;
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
type methodnameN(parameter-list) {
// body of method
}}
The data, or variables, defined within a class are called instance
variables.
The code is contained within methods.
Collectively, the methods and variables defined within a class
are called members of the class.
In most classes, the instance variables are acted upon and accessed
by the methods defined for that class. Thus, it is the methods that
determine how a class’ data can be used.
E.G of Simple Class: class Box {
double width;
double height;
double depth;
}
A Class is a 3-Compartment Box encapsulating Data and Operations

A class can be visualized as a three-compartment box, as illustrated:


•Name (or identity): identifies the class.
•Variables (or attribute, state, field): contains the static attributes of the
class.
•Methods (or behaviors, function, operation): contains the dynamic
behaviors of the class.
The followings figure shows a few examples of classes:
 Introducing Methods
 Classes usually consist of two things: instance variables and methods.
 The topic of methods is a large one because Java gives them so much power and flexibility.
 This is the general form of a method:
type name(parameter-list) {
// body of method }
 Here, type specifies the type of data returned by the method.
 If the method does not return a value, its return type must be void.
 The name of the method is specified by name.
 The parameter-list is a sequence of type and identifier pairs separated by commas.
 Parameters are essentially variables that receive the value of the arguments passed to the method
when it is called.
 If the method has no parameters, then the parameter list will be empty.
Creating Method:

Considering the following example to explain the syntax of a method:

public static int funcName(int a, int b) {

/ / body }

Here,
public static : modifier. Methods are also known as Procedures

int: return type or Functions:

funcName: function name Procedures: They don't return any


value.
a, b: formal parameters
Functions: They return value.
int a, int b: list of parameters
Example:
Here is the source code of the above defined method called max(). This method takes two
parameters num1 and num2 and returns the maximum between the two:
/ / the snippet returns the minimum between two numbers
public static int maxFunction(int n1, int n2) {
int max;

if (n1 < n2)

max = n2;

else

max = n1;

return max;

}
Method Calling:

For using a method, it should be called. There are two ways in which a method is called

i.e. method returns a value or returning nothing (no return value).

E.g
int min;
public class ExampleMinNumber{
if (n1 > n2)
public static void main(String[] args) {
min = n2;
int a = 11;
else
int b = 6;
min = n1;
int c = minFunction (a, b);
return min;
System.out.println("Minimum Value = " + c);
}}
}
This would produce the following result:
/ ** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) { Minimum value = 6
Main Method
 In the construction of a Java application program there must be one main method
present in one of the classes.
 The main method is a class method with the following signature:
 public static void main(String[] args);
 Static: modifier implies that the main method is not an instance method requiring an
object for its invocation.
 keyword void: implies that the main method does not return a value. The formal
parameter list will allow arguments to be passed to the main method at the time of
giving the command to execute the program.
 Notice that the beginning and ending of the main method are denoted by the use of an
open { and a closed } brace respectively.
The void Keyword:

The void keyword allows us to create methods


else if (points >= 322.4) {
which do not return a value.
Example: System.out.println(" Rank:A2" );

public class ExampleVoid { }


public static void main(String[] args) {
else {
methodRankPoints(255.7);
System.out.println(" Rank:A3" );}}}
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println(" Rank:A1" );
}
Access modifiers

Java provides a number of access modifiers to set access


levels for classes, variables, methods and constructors. The
three access levels are:

 Visible to the class only (private).

 Visible to the world (public).

 Visible to the package and all subclasses (protected)


Private Access Modifier - private:

 Methods, Variables and Constructors that are declared private can only be accessed
within the declared class itself.

 class Private access modifier is the most restrictive access level.

 Class and interfaces cannot be private.

 Variables that are declared private can be accessed outside the class if public getter
methods are present in the class.

 Using the private modifier is the main way that an object encapsulates itself and
hide data from the outside world.
Example: The following class uses private access control:

public class Logger {

private String format;

public String getFormat(){

return this.format;

public void setFormat(String format) {

this.format = format;

}}
 Here, the format variable of the Logger class is private, so there's
no way for other classes to retrieve or set its value directly.

 So to make this variable available to the outside world, we


defined two public methods:

 getFormat(), which returns the value of format, and

 setFormat(String), which sets its value


Public Access Modifier - public:

 A class, method, constructor, interface etc declared public can be accessed from
any other class.

 Therefore fields, methods, blocks declared inside a public class can be accessed
from any class belonging to the Java Universe.

 However if the public class we are trying to access is in a different package,


then the public class still need to be imported.

 Because of class inheritance, all public methods and variables of a class are
inherited by its subclasses.
Example:

The following function uses public access control:

public static void main(String[] arguments)

{ // ...

The main() method of an application has to be public. Otherwise, it


could not be called by a Java interpreter (such as java) to run the class
Protected Access Modifier - protected:

 Variables, methods and constructors which are declared protected in a


superclass can be accessed only by the subclasses in other package or any class
within the package of the protected members' class.

 The protected access modifier cannot be applied to class and interfaces.

 Methods, fields can be declared protected, however methods and fields in a


interface cannot be declared protected.

 Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.
Working with objects

 An object is an instance of a class created using a new operator.

 The process of creating objects from a class is called instantiation.

 An object encapsulates state and behavior.

 Creating variables of your class type is similar to creating variables of primitive data
types, such as integer or float.

 Each time you create an object, a new set of instance variables comes into existence
which defines the characteristics of that object.

 If you want to create an object of the class and have the reference variable associated
with this object, you must also allocate memory for the object by using the new
operator.

 This process is called instantiating an object or creating an object instance.


Constructors

It can be tedious to initialize all of the variables in a class each


time an instance is created.
A constructor initializes an object immediately upon creation. It has the
same name as the class in which it resides and is syntactically similar to
a method.
// Here, Box uses a constructor to initialize the dimensions of a box.
class Box { class BoxDemo6 {
double width; public static void main(String args[]) {
double height; // declare, allocate, and initialize Box objects
double depth; Box mybox1 = new Box();
// This is the constructor for Box. Box mybox2 = new Box();
Box() { double vol;
System.out.println("Constructing Box"); // get volume of first box
width = 10; vol = mybox1.volume();
height = 10; System.out.println("Volume is " + vol);
depth = 10; // get volume of second box
} vol = mybox2.volume();
// compute and return volume System.out.println("Volume is " + vol);
double volume() { }
return width * height * depth; }
}}
Types of constructor
Generally there are three types of constructors
1)Default constructor
Constructor with no argument is called default
constructor.
Example:
Class hello{
Hello(){
System.out.println(“I am hello constructor”);
}
}
2) Parameterized constructor
Constructor which takes parameter during the time of invocation is called
parameterized constructor.
Example
Class Unit{
Private int n;
unit(int var) //Parameterized constructor.
{
n=var;
}}
3)Copy constructor
Takes object as a argument. It copies one object
into another object.
Example:
Class Unit{
Int n;
Unit(unit a) //Copy constructor.
{
this.n=this.a;
}
}
Features of constructor:-
1) Constructor need not call, it calls automatically when object creates.
2) Constructor name and class name must be same.
3) Generally constructor is declared as public mode.
4) Constructor is used to initialize object.
5) Constructor can be overloaded.
6) Constructor may be virtual.
7) constructor of one class can call constructor of other class using super
keyword.
Features of OOPS

•Inheritance.
•Encapsulation.
•Abstraction.
•Polymorphism.
•Modularity
•Reusability

Basic java programming By Adugna H 49


Inheritance

Basic java programming By Adugna H 50


• Inheritance is one of the cornerstones of object-oriented programming
because it allows the creation of hierarchical classifications.
• Using inheritance, you can create a general class that defines traits
common to a set of related items.
• Inheritance is the concept of a child class (sub class) automatically
inheriting the variables and methods defined in its parent class (super
class).

03/15/2024 51
• A primary feature of object-oriented
programming along with encapsulation and
polymorphism

• To inherit a class, you simply incorporate the


definition of one class into another by using the
extends keyword.

03/15/2024 52
• OOP languages provide specific mechanisms for defining
inheritance relationships between classes.
• Derived (Child) Class - a class that inherits
characteristics of another class.
• Base (Parent) Class - a class from which characteristics
are inherited by one or more other classes.
• A derived class inherits data and function members from
03/15/2024
ALL of its base classes. 53
class B extends A { ….. } A <<class>>

A super class
B sub class B <<class>>

03/15/2024 54
• Extends keyword signifies that properties of the
super class are extended to sub class
• Sub class will not inherit private members of super
class

03/15/2024 55
Types of inheritance.
1. Single Inheritance
When a class extends another one class only then
we call it a single inheritance.

03/15/2024 56
• Single Inheritance example program in Java
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
03/15/2024 obj.methodB(); //calling local method 57
}}
2) Multiple Inheritance

When one class is derived from two or more classes, it is called


multiple inheritance.
This inheritance is not supported by java.

03/15/2024 58
3) Hierarchical Inheritance
In such kind of inheritance one class is inherited
by many sub classes.

03/15/2024 59
Example of hierarchical inheritance
Class D extends A
Class A {
{ public void methodD()
public void methodA() {
System.out.println("method of Class D");
{
}
System.out.println("method of Class A");
}
} Class MyClass
} {
class B extends A public void methodB()
{ public void methodB() {
{ System.out.println("method of Class B");
}
System.out.println("method of Class B");
public static void main(String args[])
}
{
} B obj1 = new B();
Class C extends A C obj2 = new C();
{ D obj3 = new D();
public void methodC() obj1.methodA();
{ obj2.methodA();
obj3.methodA(); } }
System.out.println("method of Class C");
}
}
03/15/2024 } 60
• The above would run perfectly fine with no
errors and the output would be –
method of Class A
method of Class A
method of Class A

03/15/2024 61
• 4) Multilevel Inheritance
• Multilevel inheritance refers to a mechanism in
OO technology where one can inherit from a
derived class, thereby making this derived class
the base class for the new class.

03/15/2024 62
Multilevel Inheritance example program in Java
Class X Class Z extends Y
{ {
public void methodX() public void methodZ()
{
{
System.out.println("class Z method");
System.out.println("Class X
}
method");
public static void main(String args[])
}
{
}
Z obj = new Z();
Class Y extends X obj.methodX(); //calling grand parent
{ class method
public void methodY() obj.methodY(); //calling parentclass
{ method
System.out.println("class Y obj.methodZ(); //calling localmethod
method"); }
} }
03/15/2024 } 63
5) Hybrid Inheritance
• In simple terms you can say that Hybrid inheritance
is a combination of Single and Multiple inheritance.

• Since java doesn’t support multiple inheritance,


hybrid inheritance is unsupportive.

03/15/2024 64
• Member Access and Inheritance

Although a subclass includes all of the members of its super class, it cannot
access those members of the super class that have been declared as private.
For example, consider the following simple class hierarchy:

/* In a class hierarchy, private members remain

private to their class.

The following program contains an error and will not compile.

03/15/2024 65
• // Create a superclass.
class A {
int i; // public by default class Access {
private int j; // private to A public static void
void setij(int x, int y) { main(String args[]) {
i = x;
j = y;
B subOb = new B();
} subOb.setij(10, 12);
} subOb.sum();
// A's j is not accessible here.
System.out.println("Total is
class B extends A {
int total;
" + subOb.total);
void sum() { }
total = i + j; // ERROR, j is not }
accessible here
}
03/15/2024 } 66
Using super
• Whenever a subclass needs to refer to its immediate
super class, it can do so by use of the keyword super.
super has two general forms.
The first calls the super class’ constructor.
super();
super(<parameter-list>);
The second is used to access a member of the super
class that has been hidden by a member of a subclass.
super.<super class instance variable/Method>

03/15/2024 67
class A class B extends A
{ {
private int a; private int b;
A( int a) private double c;
{ B(int a,int b,double c)
this.a =a; {
System.out.println("This is constructor of super(a);
class A"); this.b=b;
} this.c=c;
void print() System.out.println("This is constructor of
{ class B");
System.out.println("a="+a); }
} void show()
void display() {
{ print();
System.out.println("hello This is Display in System.out.println("b="+b);
A"); System.out.println("c="+c);
} }
} // End of class A } // End of class B

03/15/2024 68
•Inheritance.
•Encapsulation.
•Abstraction.
•Polymorphism.
•Modularity
•Reusability

Basic java programming By Adugna H 69


Encapsulation

 Encapsulation means that an object contains both a state and an


operation that can be performed on that state. That is procedure and
data bundled together.
 Actions on an object’s state are called methods and are initiated by
messages that are sent to the object.
 Encapsulation separates the interface (which captures the outside
view of a class) of an abstraction and its implementation

Basic java programming By Adugna H 70


•Inheritance.
•Encapsulation.
•Abstraction.
•Polymorphism.
•Modularity
•Reusability

Basic java programming By Adugna H 71


Abstraction

 A simplified description or specification, of a system that


emphasizes some of the systems details or properties while
suppressing others.

Basic java programming By Adugna H 72


•Inheritance.
•Encapsulation.
•Abstraction.
•Polymorphism.
•Modularity
•Reusability

Basic java programming By Adugna H 73


• Polymorphism is an important concept of

Object Oriented Programming.


 (Poly means ―many‖ and morph means ―form‖). Polymorphism means
the ability to take more than one form. Polymorphism plays a main role
in allocate objects having different internal structures to share the same
external interface.

03/15/2024 74
• Polymorphism allows us to write generic, reusable code more
easily

03/15/2024 75
Method overloading
• Defining two or more methods within the same class that
share the same name, as long as their parameter
declarations are different is called method overloading.
• When an overloaded method is called, the Java compiler
selects the appropriate method by examining the number,
types and order of the arguments in the call.
03/15/2024 76
Ex
public class Overloading
{
int square(int intVal)
{
System.out.println("Called square with argument: "+intVal);
return intVal*intVal;
}
double square(double doubleVal)
{
System.out.println("Called square with argument: "+doubleVal);
return doubleVal*doubleVal;
}
}
class OverloadingTest
{
public static void main(String[] args)
{
Overloading first=new Overloading();
System.out.println("Square of integer 8 equals to "+first.square(8));
System.out.println("Square of double 8.5 equals to "+first.square(8.5));
}
}

03/15/2024 77
 Overloaded method declarations with identical
signatures cause compilation errors, even if the return
types are different.

03/15/2024 78
Constructor overloading
• Constructors are methods that can be overloaded,
just like any other method in a class.
• Constructors having the same name with different
parameter list is called constructor overloading.

03/15/2024 79
• class Box {
double width; Ex class OverloadCons {
double height;
double depth; public static void main(String args[]) {
Box(double w, double h, double d) { // create boxes using the various constructors
width = w; Box mybox1 = new Box(10.0, 20.0, 15.0);
height = h; Box mybox2 = new Box();
depth = d; Box mycube = new Box(7.0);
}
double vol;
// constructor used when no dimensions specified
// get volume of first box
Box() {
width = -1; // use -1 to indicate vol = mybox1.volume();
height = -1; // an uninitialized System.out.println("Volume of mybox1 is " +
depth = -1; // box vol);
} // get volume of second box
// constructor used when cube is created vol = mybox2.volume();
Box(double len) { System.out.println("Volume of mybox2 is " +
width = height = depth = len; vol);
} // get volume of cube
// compute and return volume
vol = mycube.volume();
double volume() {
return width * height * depth;
System.out.println("Volume of mycube is " +
}
vol);
} }
03/15/2024 } 80
• Method Overriding

• In a class hierarchy, when a method in a subclass has


the same name and type signature as a method in its
super class, then the method in the subclass is said to
override the method in the super class.

03/15/2024 81
// display k – this overrides show() in
// Method overriding.
A
class A {
void show() {
int i, j;
A(int a, int b) { System.out.println("k: " + k);
i = a; }
j = b; }
} class Override {
// display i and j public static void main(String args[]) {
void show() { B subOb = new B(1, 2, 3);
System.out.println("i and j: " + i + " " + subOb.show(); // this calls show() in B
j);
}
}
}
}
The output produced by this program
class B extends A {
is shown here:
int k;
k: 3
B(int a, int b, int c) {
super(a, b);
03/15/2024 k = c; 82
}
•Inheritance.
•Encapsulation.
•Abstraction.
•Polymorphism.
•Modularity
•Reusability

Basic java programming By Adugna H 83


Modularity

 It is the property of a system that has been decomposed into a set of


cohesive and loosely coupled modules.
 In traditional structured design, modularization is primarily concerned
with the meaningful grouping of subprograms, using the criteria of
coupling and cohesion.
 In O-O design, the task of modularization is to decide where to physically
package the classes and objects from the design’s logical structure.
03/15/2024 By Mr. Adugna .H 84
•Inheritance.
•Encapsulation.
•Abstraction.
•Polymorphism.
•Modularity
•Reusability

Basic java programming By Adugna H 85


Reusability

Reusability Once a class has been written, created, and


debugged, it can be distributed to other programmers for use in
their own programs. This is called reusability.

03/15/2024 By Mr. Adugna .H 86


Operators
 An operator is symbols that specify operation to be performed may
be certain mathematical and logical operation.
 Operators are used in programs to operate data and variables. They
frequently form a part of mathematical or logical expressions.

03/15/2024 87
• Categories of operators are as follows:

1. Arithmetic operators

2. Logical operators

3. Relational operators

4. Assignment operators

5. Conditional operators

6. Increment and decrement operators

7. Bit wise operators


03/15/2024 88
1. Arithmetic operators:
Arithmetic operators are used to make
mathematical expressions and the working out
as same in algebra.

03/15/2024 89
• Operator Result

+ Addition

– Subtraction (also unary minus)

* Multiplication

/ Division

% Modulus

++ Increment

+= Addition assignment

–= Subtraction assignment

*= Multiplication assignment

/= Division assignment

%= Modulus assignment
03/15/2024 90
–– Decrement
• Example
// Demonstrate the basic arithmetic
// arithmetic using doubles
operators.
class BasicMath { System.out.println("\nFloating Point
public static void main(String args[]) Arithmetic");
{ double da = 1 + 1;
// arithmetic using integers double db = da * 3;
System.out.println("Integer Arithmetic");
double dc = db / 4;
int a = 1 + 1;
int b = a * 3;
double dd = dc - a;
int c = b / 4; double de = -dd;
int d = c - a; System.out.println("da = " + da);
int e = -d; System.out.println("db = " + db);
System.out.println("a = " + a);
System.out.println("dc = " + dc);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("dd = " + dd);
System.out.println("d = " + d); System.out.println("de = " + de);
System.out.println("e = " + e); }
}
03/15/2024 91
2. Increment and Decrement Operators:
/ Demonstrate ++ and --.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
03/15/2024 92
}
3. Relational operators
• The relational operators determine the relationship
that one operand has to the other.
• Operator Result
• == Equal to
• != Not equal to
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to

03/15/2024 93
4. Boolean logical operators
• The Boolean logical operators operate only on
boolean operands.
• All of the binary logical operators combine
two boolean values to form a resultant
boolean value.

03/15/2024 94
• Operator Result
& Logical AND
| Logical OR
== Equal to
!= Not equal to

03/15/2024 95
5. The Assignment operator
• The assignment operator is the single
equal sign, =.
int x, y, z;
x = y = z = 100; // set x, y, and z to
100
03/15/2024 96
6. The Bite Wise Operator

• Java defines several bitwise operators which can be applied to the integer types,

long,int, short, char, and byte.

• These operators act upon the individual bits of their operands.

• Operator Result

• ~ Bitwise unary NOT

• & Bitwise AND

• | Bitwise OR

• ^ Bitwise exclusive OR

• >> Shift right

• >>> Shift right zero fill


03/15/2024 97
• << Shift left
class OpBitEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a |= 4;
b >>= 1;
c <<= 1;
a ^= c;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
03/15/2024 98
}
The output of the above program is shown here:
a=3
b=1
c=6

03/15/2024 99
7. The ? Operator(conditional operator)
• General form:
expression1 ? expression2 : expression3 ;
Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is
evaluated.
// Demonstrate ?.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
03/15/2024 100
}
End of Chap 4.

10 Q!!!!!

If Any ??????? ?
03/15/2024 101

You might also like