0% found this document useful (0 votes)
42 views18 pages

Java Control Flow and OOP Concepts

The document provides an extensive overview of Java programming concepts, including control statements, OOP principles, and the use of keywords such as static and final. It covers various control flow statements like if-else and loops, as well as core OOP concepts such as inheritance, polymorphism, encapsulation, and abstraction. Additionally, it explains the use of constructors, the 'this' keyword, and the super keyword, along with examples of method overloading and overriding.

Uploaded by

Swadeep Sachan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views18 pages

Java Control Flow and OOP Concepts

The document provides an extensive overview of Java programming concepts, including control statements, OOP principles, and the use of keywords such as static and final. It covers various control flow statements like if-else and loops, as well as core OOP concepts such as inheritance, polymorphism, encapsulation, and abstraction. Additionally, it explains the use of constructors, the 'this' keyword, and the super keyword, along with examples of method overloading and overriding.

Uploaded by

Swadeep Sachan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Tutorials-Javatpoint

1. Control Statements:
Java provides statements that can be used to control the flow of Java code. Such statements
are called control flow statements.
Java provides three types of control flow statements.
1. Decision Making statements
• if statements
• switch statement
2. Loop statements
• do while loop
• while loop
• for loop
• for-each loop
3. Jump statements
• break statement
• continue statement
a. If-else
--> if statement is used to test the condition. It checks boolean condition: true or false. There
are various types of if statement in Java.
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
b. switch
--> The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement. The switch statement works with byte, short, int, long, enum types,
String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings
in the switch statement.
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums
and string.
• Each case statement can have a break statement which is optional. When control reaches
to the break statement, it jumps the control after the switch expression. If a break
statement is not found, it executes the next case.
• The case value can have a default label which is optional.
--> NOTE: If we doesn't include break statement with the cases then all the below cases will be
executed from the point where condition becomes true.
c. while loop:
The Javawhile loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not fixed,
it is recommended to use the while loop.
d. do-while loop:
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true. If the number of iteration is not fixed and you must have to execute the loop
at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop,
the do-while check the condition at the end of loop body. The Java do-while loop is executed
at least once because condition is checked after loop body.
Note: The do block is executed at least once, even if the condition is false.
e. break statement:
--> We can use Java break statement in all types of loops such as for loop, while loop and
do-while loop.
f. continue statement:
OOPS Concepts:

Object
--> Any entity that has state and behavior is known as an object.
--> It has 3 characteristics:
• State: represents the data (value) of an object.
• Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
• Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.
--> contains an address and holds space in the memory
--> An Object can be defined as an instance of a class.
Class
--> Collection of objects is called class. It is a logical entity.
--> A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
--> A variable which is created inside the class but outside the method is known as an
instance variable.
Inheritance
--> When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
--> If one task is performed in different ways, it is known as polymorphism.
--> we use method overloading and method overriding to achieve polymorphism.
Abstraction
--> Hiding. internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
--> In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
--> Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
--> A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

3 Ways to initialize object


There are 3 ways to initialize object in Java.
1. By reference variable: Initializing an object means storing data into the object.
eg
[Link]=101;
[Link]="Sonoo";
2. Initialization through method:
[Link](111,"Karan");
[Link](222,"Aryan");
3. Initialization through a constructor: to be discussed later

Anonymous object
--> Anonymous simply means nameless. An object which has no reference is known as an
anonymous object. It can be used at the time of object creation only.
--> If you have to use an object only once, an anonymous object is a good approach. For
example:

1. new Calculation();//anonymous object


Calling method through a reference:

1. Calculation c=new Calculation();


2. [Link](5);
Calling method through an anonymous object

1. new Calculation().fact(5);
--> Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

Constructors in Java
--> In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.
--> There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Rule: If there is no constructor in a class, compiler automatically creates a
default constructor.
Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
NOTE:There is no copy constructor in Java. However, we can copy the values from one object
to another like copy constructor in C++.
Q) Does constructor return any value?
Yes, it is the current class instance (You cannot use return type yet it returns a value).
Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling a method, etc. You can perform any
operation in the constructor as you perform in the method.
Is there Constructor class in Java?
Yes.
What is the purpose of Constructor class?
Java provides a Constructor class which can be used to get the internal information of a
constructor in the class. It is found in the [Link] package.

Java static keyword


--> The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.
--> The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


• The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college name
of students, etc.
• The static variable gets memory only once in the class area at the time of class loading.
NOTE:
1. class Counter2{
2. static int count=0;//will get memory only once and retain its value
3.
4. Counter2(){
5. count++;//incrementing the value of static variable
6. [Link](count);
7. }
8.
9. public static void main(String args[]){
10. //creating objects
11. Counter2 c1=new Counter2();
12. Counter2 c2=new Counter2();
13. Counter2 c3=new Counter2();
14. }
15. }
output:
1
2
3

2) Java static method


• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.
NOTE:
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Q) Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem of
extra memory allocation.

3) Java static block


• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.
Q) Can we execute a program without main() method?
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is
not possible to execute a Java class without the main method.

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

Usage of Java this keyword


Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
1) this: to refer current class instance variable
NOTE: If local variables(formal arguments) and instance variables are different, there is no
need to use this keyword.
Suggestion:It is better approach to use meaningful names for variables. So we use same
name for instance variables and parameters in real time, and always use this keyword.
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see
the example

3) this() : to invoke current class constructor


--> The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this keyword.

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. [Link]=rollno;
7. [Link]=name;
8. [Link]=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. [Link]=fee;
13. }

Inheritance in Java:
--> Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
--> By this we can reuse methods and fields of the parent class.
--> Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
Why use inheritance in java
• For Method Overriding(so runtime polymorphism can be achieved).
• For Code Reusability.
--> On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
--> In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.


When one class inherits multiple classes, it is known as multiple inheritance.

Q) Why multiple inheritance is not supported in java?


--> To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.
--> Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object, there
will be ambiguity to call the method of A or B class.
--> Results in compile time error.

Aggregation in Java
--> If a class have an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.
--> Consider a situation, Employee object contains many informations such as id, name,
emailId etc. It contains one more object named address, which contains its own informations
such as city, state, country, zipcode etc. as given below.

1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.

JAVA Polymorphism:
Method Overloading
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
NOTE: In Java, Method Overloading is not possible by changing the return type of the method
only because of ambiguity. - like gives compile time error
--> If you overload a static method in Java, it is the example of compile time polymorphism.
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
1. class TestOverloading4{
2. public static void main(String[] args){[Link]("main with String[]");}
3. public static void main(String args){[Link]("main with String");}
4. public static void main(){[Link]("main without args");}
5. }
--------------------------------------------------------------------------------------------------------

Method Overriding:
--> If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
--> Method overriding is used for runtime polymorphism.
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Can we override static method?
No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we
will learn it later.
Why can we not override static method?
It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.
Can we override java main method?
No, because the main is a static method.

Super Keyword in Java:


The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Note: super() is added in each class constructor automatically by compiler if there is no
super() or this().
Instance initializer block:
example:
1. class A{
2. A(){
3. [Link]("parent class constructor invoked");
4. }
5. }
6. class B2 extends A{
7. B2(){
8. super();
9. [Link]("child class constructor invoked");
10. }
11.
12. {[Link]("instance initializer block is invoked");}
13.
14. public static void main(String args[]){
15. B2 b=new B2();
16. }
17. }
--------------------------------------------------------------------------------------------------------
-

Final Keyword In Java


The final keyword in java is used to restrict the user.
Final can be:
1. variable
2. method
3. class

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

2) Java final method


If you make any method as final, you cannot override it.

3) Java final class


If you make any class as final, you cannot extend it.
NOTE: In all the above 3 cases we get compile time error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it.
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable.
------------------------------------------------------------------------------------------------------
static blank final variable:
--> A static final variable that is not initialized at the time of declaration is known as static
blank final variable. It can be initialized only in static block.
Example of static blank final variable

1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. [Link]([Link]);
6. }
7. }
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.- compile time error
Q) Can we declare a constructor final?
No, because constructor is never inherited.

Static Binding and Dynamic Binding:


--> Connecting a method call to the method body is known as binding.
There are two types of binding
1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).
--> An object is an instance of particular java class,but it is also an instance of its superclass.
static binding:
--> If there is any private, final or static method in a class, there is static binding.

Java instanceof:
--> The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
--> The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.

Abstraction in Java:
--> Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
--> Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class in Java:


A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Also:
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the
method.
Example of abstract class
abstract class A{}
Abstract Method in Java:
--> A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract
--> An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method.
Rule: If there is an abstract method in a class, that class must be abstract.
Rule: If you are extending an abstract class that has an abstract method,
you must either provide the implementation of the method or make this
class abstract.

Interface in Java:
--> An interface in Java is a blueprint of a class. It has static constants and abstract methods.
--> The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance in Java.
--> In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
--> Java Interface also represents the IS-A relationship.
--> It cannot be instantiated just like the abstract class.
--> Since Java 8, we can have default and static methods in an interface.
--> Since Java 9, we can have private methods in an interface.
--> Also It can be used to achieve loose coupling.
--> In interface all the methods are declared with the empty body, and all the fields are
public, static and final by default.
NOTE: The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.

Multiple inheritance in Java by interface:


--> If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

Q) What is marker or tagged interface?


An interface which has no member is known as a marker or tagged interface, for example,
Serializable, Cloneable, Remote, etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.
1. public interface Serializable{
2. }

Difference between abstract class and


interface:
--> Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
--> But there are many differences between abstract class and interface that are given below.
Abstract class

Interface

Interface can have only abstract methods.


1) Abstract class can have abstract and non-
Since Java 8, it can have default and static
abstract methods.
methods also.

2) Abstract class doesn't support multiple


Interface supports multiple inheritance.
inheritance.

3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java
class and implement multiple Java interfaces. interface only.

7) An abstract class can be extended using An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:

public abstract class Shape{ public interface Drawable{

public abstract void draw(); void draw();

} }

--> Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).

You might also like