W3resource Concepts
W3resource Concepts
This tutorial will help you to understand about Java OOPS concepts
with examples. Lets discuss about what are the features of Object
Oriented Programming. Writing object-oriented programs involves
creating classes, creating objects from those classes, and creating
applications, which are stand-alone executable programs that use
those objects.
A class is a template, blueprint,or contract that defines what an
objects data fields and methods will be. An object is an instance of a
class. You can create many instances of a class. A Java class uses
variables to define data fields and methods to define actions.
Additionally,a class provides methods of a special type, known as
constructors, which are invoked to create a new object. A constructor
can perform any action, but constructors are designed to perform
initializing actions, such as initializing the data fields of objects.
Encapsulation
Encapsulation means putting together all the variables (instance
variables) and the methods into a single unit called Class. It also
means hiding data and methods within an Object. Encapsulation
provides the security that keeps data and methods safe from
inadvertent changes. Programmers sometimes refer to encapsulation
as using a black box, or a device that you can use without regard to
the internal mechanisms. A programmer can access and use the
methods and data contained in the black box but cannot change them.
Below example shows Mobile class with properties, which can be set
once while creating object using constructor arguments. Properties
can be accessed using getXXX() methods which are having public
access modifiers.
view plaincopy to clipboardprint?
1. package oopsconcept;
2. public class Mobile {
3.
4.
5.
6.
7.
8.
9.
this.manufacturer = man;
10.
this.operating_system=o;
11.
this.model=m;
12.
this.cost=c;
13.
14.
15.
16.
return this.model;
17.
18.
19.
Inheritance
An important feature of object-oriented programs is inheritancethe
ability to create classes that share the attributes and methods of
existing classes, but with more specific features. Inheritance is mainly
used for code reusability. So you are making use of already written
class and further extending on that. That why we discussed about the
code reusability the concept. In general one line definition we can tell
that deriving a new class from existing class, its called as Inheritance.
You can look into the following example for inheritance concept. Here
we have Mobile class extended by other specific class like Android
and Blackberry.
view plaincopy to clipboardprint?
1. package oopsconcept;
2. public class Android extends Mobile{
3.
4.
5.
super(man, o, m, c);
6.
7.
8.
9.
10.
11.
1. package oopsconcept;
2. public class Blackberry extends Mobile{
3.
4.
5.
super(man, o, m, c);
6.
7.
}
public String getModel(){
8.
9.
10.
Polymorphism
In Core Java Polymorphism is one of easy concept to understand.
Polymorphism definition is that Poly means many and morphos means
forms. It describes the feature of languages that allows the same word
or symbol to be interpreted correctly in different situations based on
the context. There are two types of Polymorphism available in Java.
For example, in English the verb run means different things if you
use it with a footrace, a business, or a computer. You understand
the meaning of run based on the other words used with it. Objectoriented programs are written so that the methods having same name
works differently in different context. Java provides two ways to
implement polymorphism.
1. package oopsconcept;
2. class Overloadsample {
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
obj.print(10);
17.
obj.print("Amit");
18.
obj.print("Hello", 100);
19.
20.
}
}
Output :
1. package oopsconcept;
2. public class OverridingDemo {
3.
4.
5.
6.
System.out.println(m.getModel());
7.
8.
9.
System.out.println(a.getModel());
10.
11.
000);
12.
System.out.println(b.getModel());
13.
14.
}
}
Abstraction
All programming languages provide abstractions. It can be argued that
the complexity of the problems youre able to solve is directly related
to the kind and quality of abstraction. An essential element of objectoriented programming is abstraction. Humans manage complexity
through abstraction. When you drive your car you do not have to be
concerned with the exact internal working of your car(unless you are a
mechanic). What you are concerned with is interacting with your car
via its interfaces like steering wheel, brake pedal, accelerator pedal
etc. Various manufacturers of car has different implementation of car
working but its basic interface has not changed (i.e. you still use
steering wheel, brake pedal, accelerator pedal etc to interact with your
car). Hence the knowledge you have of your car is abstract.
A powerful way to manage abstraction is through the use of
hierarchical classifications. This allows you to layer the semantics of
complex systems, breaking them into more manageable pieces. From
the outside, the car is a single object. Once inside, you see that the
car consists of several subsystems: steering, brakes, sound system,
seat belts, heating, cellular phone, and so on. In turn, each of these
subsystems is made up of more specialized units. For instance, the
sound system consists of a radio, a CD player, and/or a tape player.
The point is that you manage the complexity of the car (or any other
complex system)through the use of hierarchical abstractions.
An abstract class is something which is incomplete and you can not
create instance of abstract class. If you want to use it you need to
make it complete or concrete by extending it. A class is called
concrete if it does not contain any abstract method and implements all
abstract method inherited from abstract class or interface it has
implemented or extended. By the way Java has concept of abstract
classes, abstract method but a variable can not be abstract in Java.
Lets take an example of Java Abstract Class called Vehicle. When I
am creating a class called Vehicle, I know there should be methods
like start() and Stop() but don't know start and stop mechanism of
every vehicle since they could have different start and stop
mechanism e.g some can be started by kick or some can be by
pressing buttons.
Advantage of Abstraction is if there is new type of vehicle introduced
we might just need to add one class which extends Vehicle Abstract
class and implement specific methods. Interface of start and stop
method would be same.
view plaincopy to clipboardprint?
1. package oopsconcept;
2. public abstract class VehicleAbstract {
3.
4.
5.
6.
7. }
8. class TwoWheeler extends VehicleAbstract{
9.
10.
11.
@Override
public void start() {
System.out.println("Starting Two Wheeler");
12.
13.
14.
15.
@Override
16.
17.
18.
19.
}
}
1. package oopsconcept;
2. public class VehicleTesting {
3.
4.
5.
6.
my2Wheeler.start();
7.
my2Wheeler.stop();
8.
my4Wheeler.start();
9.
my4Wheeler.stop();
10.
11.
}
}
Output :
Summary
Encapsulation provides the security that keeps data and methods safe from
inadvertent changes.
Polymorphism definition is that Poly means many and morphos means forms.
IS-A Relationship:
In object oriented programming, the concept of IS-A is a totally based
on Inheritance, which can be of two types Class Inheritance or
Interface Inheritance. It is just like saying "A is a B type of thing". For
example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is unidirectional. For example House is a Building. But Building is not a
House.
It is key point to note that you can easily identify the IS-A relationship.
Wherever you see an extends keyword or implements keyword in a
class declaration, then this class is said to have IS-A relationship.
HAS-A Relationship:
Composition(HAS-A) simply mean use of instance variables that are
references to other objects. For example: Maruti has Engine, or House
has Bathroom.
Lets understand these concepts with example of Car class.
1. package relationships;
2.
3.
4.
5. class Car {
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
System.out.println("Car Color= "+color + " Max Speed= " +
maxSpeed);
18.
19.
20.
21.
22.
23.
24.
25.
this.color = color;
26.
27.
28.
29.
30.
31.
32.
33.
this.maxSpeed = maxSpeed;
34.
35.
36.
37.
38.
39.
As shown above Car class has couple of instance variable and few
methods. Maruti is specific type of Car which extends Car class
means Maruti IS-A Car.
view plaincopy to clipboardprint?
//Maruti extends Car and thus inherits all methods from Car (except
final and static)
4.
5.
6.
7.
8.
9.
10.
11.
MarutiEngine.start();
12.
13.
14.
15.
1. package relationships;
2.
3.
4.
5. public class Engine {
6.
7.
8.
9.
10.
11.
System.out.println("Engine Started:");
12.
13.
14.
15.
16.
17.
18.
19.
System.out.println("Engine Stopped:");
20.
21.
22.
23.
1. package relationships;
2.
3.
4.
5. public class RelationsDemo {
6.
7.
8.
9.
10.
11.
12.
13.
myMaruti.setColor("RED");
14.
15.
myMaruti.setMaxSpeed(180);
16.
17.
myMaruti.carInfo();
18.
19.
20.
21.
myMaruti.MarutiStartDemo();
22.
23.
24.
25.
26.
27.
It is easier to change the class implementing composition than inheritance. The change of
a method inherited from a superclass. Composition, on the other hand, allows you to change
the interface of a front-end class without affecting back-end classes.
Composition is dynamic binding (run time binding) while Inheritance is static binding
(composition), because inheritance comes with polymorphism. If you have a bit of code that
relies only on a superclass interface, that code can work with a new subclass without change.
This is not true of composition, unless you use composition with interfaces. Used together,
composition and interfaces make a very powerful design tool.
With both composition and inheritance, changing the implementation (not the interface)
of any class is easy. The ripple effect of implementation changes remain inside the same
class.
Don't use inheritance just to get code reuse If all you really want is to reuse
polymorphism, but there is no natural is-a relationship, use composition with interfaces.
Summary
Description
An array is a group of similar typed variables that are referred to by a
common name. Arrays of any type can be created and may have one
or more dimensions. A specific element in an array is accessed by its
index. Array is simple type of data structure which can store primitive
variable or objects. For example, imagine if you had to store the result
Here, type specifies the type of variables (int, boolean, char, float etc)
being stored, size specifies the number of elements in the array, and
array-name is the variable name that is reference to the array. Array
size must be specified while creating an array. If you are creating a
int[], for example, you must specify how many int values you want it to
hold (in above statement resultArray[] is having size 6 int values).
Once an array is created, it can never grow or shrink.
Initializing array: You can initialize specific element in the array by
specifying its index within square brackets. All array indexes start at
zero.
resultArray[0]=69;
This will initialize first element (index zero) of resultArray[] with integer
value 69. Array elements can be initialized/accessed in any order. In
memory it will create structure similar to below figure.
Array Literals
The null literal used to represent the absence of an object can also be
used to represent the absence of an array. For example:
String [] name = null;
In addition to the null literal, Java also defines special syntax that
allows you to specify array values literally in your programs. This
syntax can be used only when declaring a variable of array type. It
combines the creation of the array object with the initialization of the
array elements:
1. package arrayDemo;
2.
3.
4.
5. import java.util.Arrays;
6.
7.
8.
9. public class ResultListDemo {
10.
11.
12.
13.
14.
15.
16.
17.
//Array Declaration
18.
19.
20.
21.
//Array Initialization
22.
23.
resultArray[0]=69;
24.
25.
resultArray[1]=75;
26.
27.
resultArray[2]=43;
28.
29.
resultArray[3]=55;
30.
31.
resultArray[4]=35;
32.
33.
resultArray[5]=87;
34.
35.
36.
37.
);
38.
39.
[1]);
40.
41.
]);
42.
43.
3]);
44.
45.
);
46.
47.
]);
48.
49.
50.
51.
52.
53.
Output
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These,
as you might expect, look and act like regular multidimensional arrays.
However, as you will see, there are a couple of subtle differences. To
1. package arrayDemo;
2.
3.
4.
5. public class twoDimArrayDemo {
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
twoDim[0][0]=1;
16.
17.
twoDim[0][1]=2;
18.
19.
twoDim[0][2]=3;
20.
21.
twoDim[1][0]=4;
22.
23.
twoDim[1][1]=5;
24.
25.
twoDim[1][2]=6;
26.
27.
28.
29.
System.out.println(twoDim[0][0] + " " + twoDim[0][1] + " "
+ twoDim[0][2]);
30.
31.
System.out.println(twoDim[1][0] + " " + twoDim[1][1] + " "
+ twoDim[1][2]);
32.
33.
34.
35.
Output
1. package arrayDemo;
2.
3.
4.
5. import java.util.Arrays;
6.
7.
8.
9. public class ArraySortingDemo {
10.
11.
12.
13.
14.
15.
16.
17.
2f};
18.
19.
System.out.println("Array Before Sorting- " + Arrays.toString
(resultArray));
20.
21.
22.
23.
Arrays.sort(resultArray);
24.
25.
System.out.println("Array After Sorting- " + Arrays.toString(r
esultArray));
26.
27.
28.
29.
Output
The two Object arguments specify the array to copy from and the
array to copy to. The three int arguments specify the starting position
in the source array, the starting position in the destination array, and
the number of array elements to copy.
Important points:
Arrays are widely used with loops (for loops, while loops). There will be more sample
program of arrays with loops tutorial.
Summary
An array is a group of similar typed variables that are referred to by a common name.
Array can be declared using indexes or literals.
Single dimensional array is widely used but we can have multi-dimensional.
Description
Each of Java's eight primitive data types has a class dedicated to it.
These are known as wrapper classes, because they "wrap" the
primitive data type into an object of that class. The wrapper classes
are part of the java.lang package, which is imported by default into all
Java programs.
The wrapper classes in java servers two primary purposes.
int
x = 25;
Integer
y = new Integer(33);
Wrapper Class
Constructor Argument
boolean
Boolean
boolean or String
byte
Byte
byte or String
char
Character
char
int
Integer
int or String
float
Float
double
Double
double or String
long
Long
long or String
short
Short
short or String
Here in we can provide any number as string argument but not the
words etc. Below statement will throw run time exception
(NumberFormatException)
Purpose
parseInt(s)
toString(i)
byteValue()
doubleValue()
floatValue()
intValue()
shortValue()
longValue()
int compareTo(int i)
static int
compare(int num1,
int num2)
Compares the values of num1 and num2. Returns 0 if the values are e
negative value if num1 is less than num2. Returns a positive value if
than num2.
boolean
equals(Object
intObj)
Lets see java program which explain few wrapper classes methods.
view plaincopy to clipboardprint?
1. package WrapperIntro;
2.
3.
4.
5. public class WrapperDemo {
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
//compareTo demo
18.
19.
System.out.println("Comparing using compareTo Obj1 and O
bj2: " + intObj1.compareTo(intObj2));
20.
21.
System.out.println("Comparing using compareTo Obj1 and O
bj3: " + intObj1.compareTo(intObj3));
22.
23.
24.
25.
//Equals demo
26.
27.
System.out.println("Comparing using equals Obj1 and Obj2:
" + intObj1.equals(intObj2));
28.
29.
System.out.println("Comparing using equals Obj1 and Obj3:
" + intObj1.equals(intObj3));
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
System.out.println("Comparing using compare f1 and f2: " +
Float.compare(f1,f2));
40.
41.
System.out.println("Comparing using compare f1 and f3: " +
Float.compare(f1,f3));
42.
43.
44.
45.
46.
47.
48.
49.
System.out.println("Addition of intObj1 and f1: "+ intObj1 +
"+" +f1+"=" +f );
50.
51.
52.
53.
54.
55.
Output
1. package WrapperIntro;
2.
3.
4.
5. public class ValueOfDemo {
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
er);
24.
25.
per2);
26.
27.
per3);
28.
29.
System.out.println("Hex value of intWrapper: " + Integer.toH
exString(intWrapper));
30.
31.
System.out.println("Binary Value of intWrapper2: "+ Integer.
toBinaryString(intWrapper2));
32.
33.
34.
35.
Output
Summary
Wrapper class provides many methods while using collections like sorting,
searching etc.
Description
Assigning a value to a variable seems straightforward enough; you
simply assign the stuff on the right side of the '= 'to the variable on the
left. Below statement 1 assigning value 10 to variable x and statement
2 is creating String object called name and assigning value "Amit" to it.
Statement 1:
Statement 2:
x =10;
ads
Primitive Assignment :
The equal (=) sign is used for assigning a value to a variable. We can
assign a primitive variable using a literal or the result of an expression.
Primitive Casting
Casting lets you convert primitive values from one type to another. We
need to provide casting when we are trying to assign higher precision
primitive to lower precision primitive for example If we try to assign int
variable (which is in range of byte variable) to byte variable then
compiler will throw exception called "possible loss of precision".
Eclipse IDE will suggest the solution as well as shown below. To avoid
such problem we should use type casting which will instruct compiler
for type conversion.
byte v = (byte) a;
to assign 129 literal value to byte primitive type which is out of range
for byte so compiler converted it to -127 using twos compliment
method. Refer link for twos complement calculation
(http://en.wikipedia.org/wiki/Two's_complement)
Java Code
view plaincopy to clipboardprint?
1. package operatorsdemo;
2.
3.
4.
5. public class ExplicitCastingDemo {
6.
7.
8.
9.
10.
11.
byte b = (byte)129;
12.
13.
14.
15.
16.
17.
Output
You can also assign null to an object reference variable, which simply
means the variable is not referring to any object. The below statement
creates space for the Employee reference variable (the bit holder for a
reference value), but doesn't create an actual Employee object.
Employee a = null;
Name
Example
Equiv
+=
Addition assignment
i+=5;
i=i+5
-=
Subtraction assignment
j-=10;
j=j-10
*=
Multiplication assignment
k*=2;
k=k*2
/=
Division assignment
x/=10;
x=x/1
%=
Remainder assignment
a%=4;
a=a%
Java Code
view plaincopy to clipboardprint?
1. package operatorsdemo;
2.
3.
4.
5. public class AssignmentOperatorDemo {
6.
7.
8.
9.
10.
11.
12.
13.
byte b = 25;
14.
15.
16.
17.
18.
19.
byte c =b;
20.
21.
System.out.println("Primitive byte Assignment from another
byte variable- "+ c);
22.
23.
24.
25.
int a = 23+b;
26.
27.
System.out.println("Primitive int Assignment from arithmetic
operation- "+ a);
28.
29.
30.
31.
short s = 45;
32.
33.
int x = b;
34.
35.
36.
int y = s;
37.
38.
39.
40.
41.
42.
43.
44.
45.
int i = 10;
46.
47.
i+=10;
48.
49.
50.
51.
i-=10;
52.
53.
54.
55.
i*=10;
56.
57.
58.
59.
i/=10;
60.
61.
62.
63.
64.
i%=3;
65.
66.
67.
68.
69.
Output
Summary
Description
We can use arithmetic operators to perform calculations with values in
programs. Arithmetic operators are used in mathematical expressions
in the same way that they are used in algebra. A value used on either
side of an operator is called an operand. For example, in below
int a = 47+3;
Operator
Use
Description
Example
x+y
Adds x and y
x-y
Subtracts y from x
Arithmetically negates x
-x
*
x*y
Multiplies x by y
x/y
Divides x by y
x%y
int rm = 20/3; // rm = 2
If the operand is of type byte, short, or char then the result is a value of type int.
Java Code
view plaincopy to clipboardprint?
1. package operatorsdemo;
2.
3.
4.
5. public class ArithmeticOperatorDemo {
6.
7.
8.
9.
10.
11.
12.
13.
System.out.println("Integer Arithmetic");
14.
15.
int i = 1 + 1;
16.
17.
int n = i * 3;
18.
19.
int m = n / 4;
20.
21.
int p = m - i;
22.
23.
int q = -p;
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
double a = 1 + 1;
40.
41.
double b = a * 3;
42.
43.
double c = b / 4;
44.
45.
double d = c - a;
46.
47.
double e = -d;
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
Output
Java Code
view plaincopy to clipboardprint?
1. package operatorsdemo;
2.
3.
4.
5. public class RemainderDemo {
6.
7.
8.
9.
int x = 15;
10.
11.
12.
13.
14.
15.
+ "remainder of 15 divided by 10. The remainder is " +
int_remainder);
16.
17.
double d = 15.25;
18.
19.
20.
21.
22.
23.
24.
25.
+ "remainder of 15.25 divided by 10. The remainder is
" + double_remainder);
26.
27.
28.
29.
30.
31.
Output
results isNaN.
A non-zero integer value divided by integer 0 will result in ArithmeticException at
runtime
x++;
Same way decrement operator
x = x - 1;
is equivalent to
x--;
These operators are unique in that they can appear both in postfix
form, where they follow the operand as just shown, and prefix form,
where they precede the operand. In the foregoing examples, there is
no difference between the prefix and postfix forms. However, when the
increment and/or decrement operators are part of a larger expression,
then a subtle, yet powerful, difference between these two forms
appears. In the prefix form, the operand is incremented or
decremented before the value is obtained for use in the expression. In
postfix form, the previous value is obtained for use in the expression,
and then the operand is modified.Lets understand this concept with
help of example below,
Java Code
view plaincopy to clipboardprint?
1. package operatorsdemo;
2.
3.
4.
5. public class ShortcutArithmeticOpdemo {
6.
7.
8.
9.
int a,b,c,d;
10.
11.
a=b=c=d=100;
12.
13.
14.
15.
int p = a++;
16.
17.
int r = c--;
18.
19.
int q = ++b;
20.
21.
int s = --d;
22.
23.
System.out.println("prefix increment operator result= "+ p
+ " & Value of a= "+ a);
24.
25.
System.out.println("prefix decrement operator result= "+ r
+ " & Value of c= "+c);
26.
27.
System.out.println("postfix increment operator result= "+ q
+ " & Value of b= "+ b);
28.
29.
System.out.println("postfix decrement operator result= "+ s
+ " & Value of d= "+d);
30.
31.
32.
33.
Output
Summary
Description
If you need to change the execution of the program based on a certain
condition you can use if statements. The relational operators
determine the relationship that one operand has to the other.
Specifically, they determine equality condition. Java provides six
relational operators, which are listed in below table.
Operator
Description
==
Equality operator
a==b
!=
a!=b
>
Greater than
a>b
<
Less than
a<b
>=
a>=b
<=
a<=b
if(condition) statement;
or
if (condition) statement1;
else statement2;
1. if (someVariable ==10){
2.
3. System.out.println("The Value is 10);
4.
5. }
Nested if blocks:
A nested if is an if statement that is the target of another if or else. In
other terms we can consider one or multiple if statement within one if
block to check various condition. For example we have two variables
and want to check particular condition for both we can use nested if
blocks.
Java Code
view plaincopy to clipboardprint?
1. package logicaloperator;
2.
3.
4.
5. public class NestedIfDemo {
6.
7.
8.
9.
10.
11.
int a =10;
12.
13.
int b =5;
14.
15.
if(a==10){
16.
17.
if(b==5){
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
if else if ladder:
We might get situation where we need to check value multiple times to
find exact matching condition. Below program explain the same thing.
Lets see we have requirement to check if variable value is less than
100, equal to 100 or more than 100. Below code explain the same
logic using if-else if ladder.
Java Code
view plaincopy to clipboardprint?
1. package logicaloperator;
2.
3.
4.
5. public class IfelseLadderDemo {
6.
7.
8.
9.
10.
11.
int a =120;
12.
13.
if(a<100){
14.
15.
16.
17.
}else if(a==100){
18.
19.
20.
21.
}else if (a>100){
22.
23.
24.
25.
26.
27.
28.
29.
Output
Java Code
view plaincopy to clipboardprint?
1. package logicaloperator;
2.
3. import java.util.Scanner;
4.
5. public class GradeCalculation {
6.
7.
8.
9.
int marks=0 ;
10.
11.
try{
12.
13.
14.
15.
16.
17.
0) >> ");
18.
19.
marks = inputDevice.nextInt();
20.
21.
22.
23.
24.
if(marks<0){
25.
System.out.println("Marks can not be negative: Your entr
y= "+ marks );
26.
27.
}else if(marks==0){
28.
29.
30.
31.
}else if (marks>100){
32.
33.
System.out.println("Marks can not be more than 100: You
r entry= "+ marks );
34.
35.
36.
37.
System.out.println("You need to work hard: You failed this
time with marks ="+ marks);
38.
39.
40.
41.
System.out.println("Your score is not bad, but you need i
mprovement, you got C Grade");
42.
43.
44.
45.
System.out.println("You can improve performance, you go
t C+ grade");
46.
47.
48.
49.
50.
51.
52.
53.
System.out.println("You can get better grade with little m
ore efforts, your grade is B+");
54.
55.
56.
57.
A ");
58.
59.
}else if (marks>=90){
60.
61.
System.out.println("One of the best performance, Your gr
ade is A+");
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
&&
||
short-circuit AND
short-circuit OR
They are used to link little boolean expressions together to form bigger
boolean expressions. The && and || operators evaluate only boolean
values. For an AND (&&) expression to be true, both operands must
be true. For example, The below statement evaluates to true because
both operand one (2 < 3) and operand two (3 < 4) evaluate to true.
Java Code
view plaincopy to clipboardprint?
1. package logicaloperator;
2.
3.
4.
5. public class ShortCircuitOpDemo {
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
Output
below example, we are deciding the status based on user input if pass
or failed.
Java Code
view plaincopy to clipboardprint?
1. package logicaloperator;
2.
3.
4.
5. import java.util.Scanner;
6.
7.
8.
9. public class TernaryOpDemo {
10.
11.
12.
13.
14.
15.
String status;
16.
17.
int marks;
18.
19.
20.
21.
0) >> ");
22.
23.
marks = inputDevice.nextInt();
24.
25.
26.
27.
28.
29.
30.
31.
Summary
Java provides six conditional operators == (equality), > (greater than), < (less
The relational operators are most frequently used to control the flow of program.
Ternary operator is one which is similar to if else block but which is used to
assign value based on condition.
Description
Sometimes, whether a statement is executed is determined by a
combination of several conditions.You can use logical operators to
combine these conditions. Logical operators are known as Boolean
operators or bitwise logical operators. Boolean operator operates on
boolean values to create a new boolean value.The bitwise logical
operators are &, |, ^, and ~ or !. The following table shows the
outcome ofeach operation.
a
a&b
a|b
a^b
~a o
true(1)
true(1)
true
true
false
false
true(1)
false(0)
false
true
true
false
false(0)
true(1)
false
true
true
true
false(0)
false(0)
false
false
false
true
int b = ~a; // this will reverts the bits 01000 which is 8 in decimal
boolean x = true;
boolean y = !x;
boolean b1 = true;
boolean b2=false;
The OR Operator
The OR operator | produces a 0 bit if both operands are 0 otherwise
1 bit. Similarly for boolean operands it will result in false if both
operands are false else result will be true.
boolean b1 = true;
boolean b2=false;
operands it will result in false if both operands are same (either both
are false or both true) else result will be true.
boolean b1 = true;
boolean b2=false;
Java Code
view plaincopy to clipboardprint?
1. package operatorsdemo;
2.
3.
4.
5.
6.
7.
8.
9. public class BitwiseLogicalOpDemo {
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
Output
System.out.println(a>>>1);
Java Code
view plaincopy to clipboardprint?
1. package operatorsdemo;
2.
3.
4.
5.
6.
7.
8.
9. public class ShiftOperatorDemo {
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
int a = 34; //binary representation 00000000 00000000 00
000000 00100010
26.
27.
28.
29.
int b = -20; //binary representation 10000000 00000000 00
000000 00010100
30.
31.
32.
33.
34.
35.
36.
37.
a>>1) );
38.
39.
40.
41.
System.out.println("Signed Right Shift -20 devide by 2= " +
(b>>1) );
42.
43.
44.
45.
46.
47.
48.
49.
a<<1) );
50.
51.
52.
53.
System.out.println("Signed Letf Shift -20 multiply by 2= " +
(b<<1) );
54.
55.
56.
57.
58.
59.
60.
61.
1) );
62.
63.
64.
65.
>1) );
66.
67.
68.
69.
70.
71.
72.
73.
Output
Summary
Binary Shift operators are >> (right shift), << (left shift), >>> (unsigned right shift).
Description
A programming language uses control statements to cause the flow of
execution to advance and branch based on changes to the state of a
program. Java supports two flow control statements: if and switch.
These statements allow you to control the flow of your programs
execution based upon conditions known only during run time. We
have discussed if statement in logical operator tutorial.
Switch Statement
The switch statement is Javas multiway branch statement. It provides
an easy way to dispatch execution to different parts of your code
based on the value of an expression. Here is the general form of a
switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
case valueN:
// statement sequence
break;
default:
The expression must be of type byte, short, int, or char; each of the
values specified in the case statements must be of a type compatible
with the expression. An enumeration value can also be used to control
a switch statement. From Java 7 onward String is also allowed as
case expression. Each case value must be a unique literal (that is, it
must be a constant, not a variable). Duplicate case values are not
allowed.
Java Code
view plaincopy to clipboardprint?
1. package loops;
2.
3.
4.
5. public class SwitchCaseDemo {
6.
7.
8.
9.
10.
11.
12.
13.
switch (Grade){
14.
15.
case 'A':
16.
17.
+ 2000);
18.
19.
break;
20.
21.
case 'B':
22.
23.
+ 1000);
24.
25.
break;
26.
27.
case 'C':
28.
29.
+ 500);
30.
31.
break;
32.
33.
default:
34.
35.
+ 100);
36.
37.
break;
38.
39.
40.
41.
42.
43.
Output
The switch can only check for equality. This means that the other relational
operators such as greater than are rendered unusable in a case.
Case constants are evaluated from the top down, and the first case constant that
matches the switch's expression is the execution entry point. If no break statement
used, all the case after entry point will be executed.
No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in
common.
The default case can be located at the end, middle, or top. Generally default
appears at end of all cases.
Break Statements
The break statement included with each case section determines
when to stop executing statements in response to a matching case.
Without a break statement in a case section, after a match is made,
the statements for that match and all the statements further down the
switch are executed until a break or the end of the switch is found. In
some situations, this might be exactly what you want to do. Otherwise,
you should include break statements to ensure that only the right code
is executed. It is sometimes desirable to have multiple cases without
break statements between them. For example here program prints
same value until some condition reaches.
Java Code
view plaincopy to clipboardprint?
1. package loops;
2.
3.
4.
5. import java.util.Scanner;
6.
7.
8.
9. public class SwitchBreakDemo {
10.
11.
12.
13.
14.
15.
16.
17.
int age;
18.
19.
20.
21.
22.
23.
age = inputDevice.nextInt();
24.
25.
switch (age){
26.
27.
case 10:
28.
29.
case 15:
30.
31.
case 17:
32.
33.
34.
35.
break;
36.
37.
case 18:
38.
39.
40.
41.
42.
43.
44.
45.
Output
Summary
The switch can only check for equality. This means that the other relational
operators such as greater than are rendered unusable in a case.
Break statement is used to stop current iteration of loop or end Switch-case block.
Description
In computer programming, a loop is a sequence of instruction s that is
continually repeated until a certain condition is reached. Imagine you
have to write a program which performs a repetitive task such as
printing 1 to 100. Writing 100 print statements would not be wise thing
to do. Loops are specifically designed to perform repetitive tasks with
one set of code. Loops save a lot of time. A loop is a structure that
allows repeated execution of a block of statements. Within a looping
structure, a Boolean expression is evaluated. If it is true, a block of
statements called the loop body executes and the Boolean expression
is evaluated again. As long as the expression is true, the statements in
the loop body continue to execute. When the Boolean evaluation is
false, the loop ends.
A for loop, which is usually used as a concise format in which to execute loops
While Loops
The while loop is good for scenarios where you don't know how many
times a block or statement should repeat, but you want to continue
looping as long as some condition is true. A while statement looks like
below. In Java, a while loop consists of the keyword while followed by
a Boolean expression within parentheses, followed by the body of the
loop, which can be a single statement or a block of statements
surrounded by curly braces.
while (expression) {// do stuff}
You can use a while loop when you need to perform a task a
predetermined number of times. A loop that executes a specific
Java Code
view plaincopy to clipboardprint?
Output
The key point to remember about a while loop is that it might not ever
run. If the test expression is false the first time the while expression is
checked, the loop body will be skipped and the program will begin
executing at the first statement after the while loop.Lets take an
example to understand this. In below program user enters the value of
loop counter variable, If counter variable is less than 5, then loop will
execute and increment counter variable by one till counter value is
Java Code
view plaincopy to clipboardprint?
Output
Loop condition/expression can be true always, which makes our loop infinite. This
is bad programming practice as it might result in memory exception. Below
statement is valid but not good to have in our program.
It is very common to alter the value of a loop control variable by adding 1 to it, or
incrementing the variable. However, not all loops are controlled by adding 1
do while Loops
The do loop is similar to the while loop, except that the expression is
not evaluated until after the do loop's code is executed. Therefore the
code in a do loop is guaranteed to execute at least once. The following
shows a do loop syntax:
do {//Loop Body} while(Condition);
If so, you want to write a loop that checks at the bottom of the loop
after the first iteration. The
do...while loop checks the value of the loop control variable at the
bottom of the loop after one repetition has occurred. Below sample
code explain do while loop.
Java Code
view plaincopy to clipboardprint?
Output
Summary
The while loop is used for scenarios where you don't know how many times a
block of code should be executed.
The do loop is similar to the while loop, except that the expression is not
evaluated until after the do loop's code is executed.
Description
A for loop is a special loop that is used when a definite number of loop
iterations is required. Although a while loop can also be used to meet
this requirement, the for loop provides you with a shorthand notation
for this type of loop. When you use a for loop, you can indicate the
starting value for the loop control variable, the test condition that
controls loop entry, and the expression that alters the loop control
variableall in one convenient place. Below is syntax of conventional
for loop.
For loop will begin with the keyword for followed by a set of
parentheses. Within the parentheses are three sections separated by
exactly two semicolons. The three sections are usually used for the
following:
For loop is very useful in java programming and widely used in java
programs. Lets see few more samples for loop declaration.
You can leave one or more portions of a for loop empty, although the
two semicolons are still required as placeholders. For example, if x has
been initialized in a previous program statement, you might write the
following:
Lets see below example which prints all the values divisible by 7 in
the range of 1 to 100 in reverse order.
Java Code
view plaincopy to clipboardprint?
Output
Here, type specifies the type and itr-var specifies the name of an
iteration variable that will receive the elements from a collection, one
at a time, from beginning to end. Because the iteration variable
receives values from the collection, type must be the same as (or
compatible with) the elements stored in the collection. Thus, when
iterating over arrays,type must be compatible with the base type of the
array.
Below example shows use of enhanced for loop.
Java Code
view plaincopy to clipboardprint?
nt elements of array
for(int loopVal: myArray){
ntln(loopVal);
} }}
System.out.pri
Output
As this output shows, the enhanced for loop style automatically cycles
through an array in sequence from the lowest index to the highest.
Summary
A for loop is a special loop that is used when a definite number of loop
iterations is required.
For loop have 3 sections, loop variable initialization, testing loop control
variable, updating loop control variable.