Unit I Introduction To Java: Overview of Object Oriented Programming Principles

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

Unit I

Introduction to Java
Overview of Object Oriented Programming principles
 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing
Object: Any entity that has state and behaviour is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.
Example: A dog is an object because it has states i.e. color, name, breed etc. as well as
behaviours i.e. wagging the tail, barking, eating etc.
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.
Data abstraction and encapsulation: The wrapping up of data and methods into a single
unit (called class) is known as encapsulation. Data encapsulation is the most striking feature
of a class. Abstraction refers to the act of representing essential features without including the
background details or explanations.
Inheritance: Inheritance is the process by which objects of one class acquire the properties
of objects of another class. It supports the concept of hierarchical classification. For example,
the bird ‘robin’ is a part of the class ‘flying bird’ which is again a part of the class ‘bird’. The
concept of inheritance provides the idea of reusability. This means that we can add additional
features to an existing class without modifying it.
Polymorphism: Polymorphism is another important OOP concept. Polymorphism, a Greek
term means ability to take more than one form. An operation may exhibit different
behaviours in different instances. The behaviour depends upon the types of data used in the
operation. For example, consider the operation of addition. For two numbers the operation
will generate a sum. If the operands are strings, then the operation would produce a third
string by concatenation. The process of making an operator to exhibit different behaviours in
different instances is known an operator overloading.
Dynamic binding: Association of method call to the method body is known as binding.
There are two types of binding: Static Binding that happens at compile time and Dynamic
Binding that happens at runtime.
Static Binding or Early Binding: The binding which can be resolved at compile time by
compiler is known as static or early binding. The binding of static, private and final methods
is compile-time.
Dynamic Binding or Late Binding: When compiler is not able to resolve the call/binding at
compile time, such binding is known as Dynamic or late binding. Method Overriding is a
perfect example of dynamic binding
Message passing: A single object by itself may not be very useful. An application contains
many objects. One object interacts with another object by invoking methods on that object. It
is also referred to as Method Invocation.
Importance of Java to the Internet
 The Internet helped catapult Java to the forefront of programming, and Java, in turn,
has had a profound effect on the Internet. The reason for this is quite simple: Java
expands the universe of objects that can move about freely in cyberspace. In a
network, two very broad categories of objects are transmitted between the server and
your Personal computer: passive information and dynamic, active programs.
 When you read your e-mail, you are viewing passive data. Even when you download
a program, the program’s code is still only passive data until you execute it.
 However, a second type of object can be transmitted to your computer: a dynamic,
self-executing program. Such a program is an active agent on the client computer, yet
is initiated by the server. For example, a program might be provided by the server to
display properly the data that the server is sending.
 As desirable as dynamic, networked programs are, they also present serious problems
in the areas of security and portability. Prior to Java, cyberspace was effectively
closed to half the entities that now live there.
 As you will see, Java addresses those concerns and, by doing so, has opened the door
to an exciting new form of program: the applet.
 In a network, two very broad categories of objects are transmitted between the server
and your personal computer: passive information and dynamic, active programs. For
example, when you read your e-mail, you are viewing passive data. Even when you
download a program, the program's code is still only passive data until you execute it.
However, a second type of object can be transmitted to your computer: a dynamic,
self-executing program
 In a network, two very broad categories of objects are transmitted between the server
and your personal computer: passive information and dynamic, active programs. For
example, when you read your e-mail, you are viewing passive data. Even when you
download a program, the program's code is still only passive data until you execute it.
However, a second type of object can be transmitted to your computer: a dynamic,
self-executing program
 Java Applets and Applications: An application is a program that runs on your
computer. It is Java's ability to create applets that makes it important. An applet is an
application designed to be transmitted over the Internet and executed by
 a Java-compatible Web browser
 Security: Prior to Java, most users did not download executable programs frequently,
and those who did scanned them for viruses prior to execution. When you use a Java-
compatible Web browser, you can safely download Java applets without fear of viral
infection or malicious intent. Java achieves this protection by Confining a Java
program to the Java execution environment and not allowing it access to other parts of
the computer.
 Portability: many types of computers and operating systems are connected to the
Internet. For programs to be dynamically downloaded to all the various types of
platforms connected to the Internet, some means of generating portable executable
code is needed.
 Byte Code java’s magic for solve above to problems(security and portability): The
output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a
highly optimized set of instructions designed to be executed by the Java run-time
system, which is called the Java Virtual Machine (JVM). That is, in its standard form,
the JVM is an interpreter for bytecode only the JVM needs to be implemented for
each platform. Once the run-time package exists for a given system, any Java program
can run on it. Remember, although the details of the JVM will differ from platform to
platform, all interpret the same Java bytecode.
 The Java words Although the fundamental forces that necessitated the invention of
Java are portability and security, other factors also played an important role
 Simple: Java was designed to be easy for the professional programmer to learn and
use effectively
 Object-oriented
 Robust: memory management mistakes and mishandled exceptional conditions
 Multithreaded: Java supports multithreaded programming, which allows you to write
programs that do many things simultaneously
 Architecture-neutral: there was no guarantee today program run and tomorrow also
run in same manner. Java achieved.
 Interpreted & High performance: Java enables the creation of cross-platform
programs by compiling into an intermediate representation called Java bytecode. This
code can be interpreted on any system that provides a Java Virtual Machine java was
designed to perform well on very low-power CPUs.
 Distributed: Java is designed for the distributed environment of the Internet, because
it handles TCP/IP protocols.
 Dynamic: Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time.
 process-oriented model: a program can be conceptually organized around its code
then code is acting on data,
 Object-oriented programming: a program can be conceptually organized around its
data.
Byte code
Java bytecode is the instruction set for the Java Virtual Machine. Byte code is a highly
optimized set of instructions designed to be executed by the Java run-time system, which is
called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is
an interpreter for byte code. Java bytecode is the result of the compilation of a Java program,
an intermediate representation of that program which is machine independent.
How does it works: When we write a program in Java, firstly, the compiler compiles that
program and a bytecode is generated for that piece of code. When we wish to run this .class
file on any other platform, we can do so. After the first compilation, the bytecode generated is
now run by the Java Virtual Machine and not the processor in consideration. This essentially
means that we only need to have basic java installation on any platforms that we want to run
our code on. Resources required to run the bytecode are made available by theJava Virtual
Machine, which calls the processor to allocate the required resources. JVM's are stack-based
so they stack implementation to read the codes.
JAVA Program Structure:
Documentation Section: It includes the comments to tell the program's purpose. It improves
the readability of the program.
Package Statement: It includes statement that provides a package declaration.
Import statements: It includes statements used for referring classes and interfaces that are
declared in other packages.
Interface Section: It is similar to a class but only includes constants, method declaration.
Class Section: It describes information about user defines classes present in the program.
Every Java program consists of at least one class definition. This class definition declares the
main method. It is from where the execution of program actually starts.
DOCUMENTATION Section: It includes the comments that improve the readability of the
program. A comment is a non-executable statement that helps to read and understand a
program especially when your programs get more complex. It is simply a message that exists
only for the programmer and is ignored by the compiler. A good program should include
comments that describe the purpose of the program, author name, date and time of program
creation. This section is optional and comments may appear anywhere in the program.
Java programming language supports three types of comments.
Single line (or end-of line) comment: It starts with a double slash symbol (//) and terminates
at the end of the current line. The compiler ignores everything from // to the end of the line.
For example:
// Calculate sum of two numbers
Multiline Comment: Java programmer can use C/C++ comment style that begins with
delimiter /* and ends with */. All the text written between the delimiter is ignored by the
compiler. This style of comments can be used on part of a line, a whole line or more
commonly to define multi-line comment. For example.
/*calculate sum of two numbers */
Comments cannot be nested. In other words, you cannot comment a line that already includes
traditional comment. For example,
/* x = y /* initial value */ + z; */ is wrong.
Documentation comments: This comment style is new in Java. Such comments begin with
delimiter /** and end with */. The compiler also ignores this type of comments just like it
ignores comments that use / * and */. The main purpose of this type of comment is to
automatically generate program documentation. The java doc tool reads these comments and
uses them to prepare your program's documentation in HTML format. For example.
/**The text enclosed here will be part of program documentation */
PACKAGE STATEMENT: Java allows you to group classes in a collection known as
package. A package statement includes a statement that provides a package declaration. It
must appear as the first statement in the source code file before any class or interface
declaration. This statement is optional. For example: Suppose you write the following
package declaration as the first statement in the source code file.
package employee;
This statement declares that all classes and interfaces defined in this source file are part of the
employee package. Only one package declaration can appear in the source file.
IMPORT STATEMENT: Java contains many predefined classes that are stored into
packages. In order to refer these standard predefined classes in your program, you need to use
fully qualified name (i.e. Packagename.className). But this is a very tedious task as one
need to retype the package path name along with the classname. So a better alternative is to
use an import statement.
An import statement is used for referring classes that are declared in other packages. The
import statement is written after a package statement but before any class definition. You can
import a specific class or all the classes of the package. For example : If you want to import
Date class of java.util package using import statement then write
import java.util.Date;
This statement allows the programmer to use the simple classname Date rather than fully
qualified classname java.util.Date in the code.
Unlike package statement, you can specify more than one import statement in your program.
For example:
Import java.util.Date; /* imports only the Date class in java.util package */
import java.applet.*; // imports all the classes in java applet
// package
INTERFACE SECTION: In the interface section, we specify the interfaces. An interface is
similar to a class but contains only constants and method declarations. Interfaces cannot be
instantiated. They can only be implemented by classes or extended by other interfaces. It is
an optional section and is used when we wish to implement multiple inheritance feature in the
program.
interface stack
{
void push(int item); // Insert item into stack
int pop(); // Delete an item from stack
}
CLASS SECTION: The Class section describes the information about user-defined classes
present in the program. A class is a collection of fields (data variables) and methods that
operate on the fields. Every program in Java consists of at least one class, the one that
contains the main method. The main () method which is from where the execution of program
actually starts and follow the statements in the order specified.
The main method can create objects, evaluate expressions, and invoke other methods and
much more. On reaching the end of main, the program terminates and control passes back to
the operating system.
The class section is mandatory.
After discussing the structure of programs in Java, we shall now discuss a program that
displays a string Hello Java on the screen.
// Program to display message on the screen
class HelloJava
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Classes and instances and Objects
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical. A class is declared
using class keyword. A class contain both data and code that operate on that data. The data or
variables defined within a class are called instance variables and the code that operates on
this data is known as methods. Thus, the instance variables and methods are known as class
members. class is also known as a user defined datatype.

class ClassName
{
// variables
// methods
}
Instance variable: A variable which is created inside the class but outside the method, is
known as instance variable. Instance variable doesn't get memory at compile time. It gets
memory at run time when object(instance) is created. That is why, it is known as instance
variable.
cass Rectangle
{
Int a;
Float b;
}
Methods
Type methodname(parameter_list)
{
Method_body;
}
Syntax for class:
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, as a general rule, it is the methods that
determine how a class’ data can be used.
Variables defined within a class are called instance variables because each instance of the
class (that is, each object of the class) contains its own copy of these variables. Thus, the data
for one object is separate and unique from the data for another.
All methods have the same general form as main( ), which we have been using thus far.
However, most methods will not be specified as static or public.
Notice that the general form of a class does not specify a main( )method. Java classes do not
need to have a main( ) method. You only specify one if that class is the starting point for your
program. Further, applets don’t require a main( ) method at all.
NOTE: C++ programmers will notice that the class declaration and the implementation of the
methods are stored in the same place and not defined separately. This sometimes makes for
very large .java files, since any class must be entirely defined in a single source file. This
design feature was built into Java because it was felt that in the long run, having
specification, declaration, and implementation all in one place makes for code that is easier to
maintain.
Declaring Member Variables
There are several kinds of variables:
 Member variables in a class—these are called fields.
 Variables in a method or block of code—these are called local variables.
 Variables in method declarations—these are called parameters.
The Bicycle class uses the following lines of code to define its fields:
public int cadence;
public int gear;
public int speed;
Field declarations are composed of three components, in order:
1. Zero or more modifiers, such as public or private.
2. The field's type.
3. The field's name.
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int).
The public keyword identifies these fields as public members, accessible by any object that
can access the class.
A Simple Class:
Let’s begin our study of the class with a simple example. Here is a class called Box that
defines three instance variables: width, height, and depth.
// This program declares two Box objects.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
The output produced by this program is shown here:
Volume is 3000.0
Volume is 162.0
 As you can see, mybox1’s data is completely separate from the data contained in
mybox2.
 As stated, a class defines a new type of data. In this case, the new data type is called
Box.
 You will use this name to declare objects of type Box. It is important to remember
that a class declaration only creates a template; it does not create an actual object.
Thus, the preceding code does not cause any objects of type Box to come into
existence.
To actually create a Box object, you will use a statement like the following:
Box mybox = new Box(); // create a Box object called mybox
 After this statement executes, mybox will be an instance of Box. Thus, it will have
“physical” reality. For the moment, don’t worry about the details of this statement.
 As mentioned earlier, each time you create an instance of a class, you are creating an
object that contains its own copy of each instance variable defined by the class.
 Thus, every Box object will contain its own copies of the instance variables width,
height, and depth.
 To access these variables, you will use the dot (.) operator. The dot operator links the
name of the object with the name of an instance variable.
For example, to assign the width variable of mybox the value 100, you would use the
following statement:
mybox.width = 100;
This statement tells the compiler to assign the copy of width that is contained within the
mybox object the value of 100.
 In general, you use the dot operator to access both the instance variables and the
methods within an object.
 You should call the file that contains this program BoxDemo2.java, because the
main() method is in the class called BoxDemo2, not the class called Box.
 When you compile this program, you will find that two .class files have been created,
one for Box and one for BoxDemo2.
 The Java compiler automatically puts each class into its own .class file. It is not
necessary for both the Box and the BoxDemo2 class to actually be in the same source
file. You could put each class in its own file, called Box.java and BoxDemo2.java,
respectively.
To run this program, you must execute BoxDemo2.class. When you do, you will see the
following output:
Volume is 3000.0
Volume is 162.0
 As stated earlier, each object has its own copies of the instance variables.
This means that if you have two Box objects, each has its own copy of depth, width, and
height. It is important to understand that changes to the instance variables of one object have
no effect on the instance variables of another.
Declaring Objects
An object is an instance of a class. An object is known by a name and every object contains a
state. The state is determined by the values of attributes (variables). The state of an object can
be changed by calling methods on it. The sequence of state changes represents the behavior
of the object.
An object is a software entity (unit) that combines a set of data with a set of operations to
manipulate that data.
As just explained, when you create a class, you are creating a new data type. You can use
this type to declare objects of that type.
However, obtaining objects of a class is a two-step process.
 First, you must declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
 Second, you must acquire an actual, physical copy of the object and assign it to that
variable. You can do this using the new operator.
 Declaration: The code set in variable declarations that associate a variable name with
an object type.
 Instantiation: The new keyword is a Java operator that creates the object.
 Initialization: The new operator is followed by a call to a constructor, which
initializes the new object.
The new operator dynamically allocates (that is, allocates at run time) memory for an object
and returns a reference to it. This reference is, more or less, the address in memory of the
object allocated by new. This reference is then stored in the variable. Thus, in Java, all class
objects must be dynamically allocated. Let’s look at the details of this procedure.
In the preceding sample programs, a line similar to the following is used to declare an object
of type Box:
Box mybox = new Box();
This statement combines the two steps just described. It can be rewritten like this to show
each step more clearly:
mybox = new Box(); // allocate a Box object
The first line declares mybox as a reference to an object of type Box. After this line executes,
mybox contains the value null, which indicates that it does not yet point to an actual object.
Any attempt to use mybox at this point will result in a compile-time error. The next line
allocates an actual object and assigns a reference to it to mybox. After the second line
executes, you can use mybox as if it were a Box object. But in reality, mybox simply holds
the memory address of the actual Box object. The effect of these two lines of code is depicted
in Figure.

NOTE: Those readers familiar with C/C++ have probably noticed that object references
appear to be similar to pointers. This suspicion is, essentially, correct. An object reference is
similar to a memory pointer. The main difference—and the key to Java’s safety—is that you
cannot manipulate references as you can actual pointers. Thus, you cannot cause an object
reference to point to an arbitrary memory location or manipulate it like an integer.
Assigning Object Reference Variables:
Object reference variables act differently than you might expect when an assignment takes
place. For example, what do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the object referred to by
b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However,
this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the
same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the
original object. It simply makes b2 refer to the same object as does b1. Thus, any changes
made to the object through b2 will affect the object to which b1 is referring, since they are the
same object.
This situation is depicted here:

Although b1 and b2 both refer to the same object, they are not linked in any other way.
For example, a subsequent assignment to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2. For example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
REMEMBER: When you assign one object reference variable to another object reference
variable, you are not creating a copy of the object, you are only making a copy of the
reference.
Data types
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
1. Primitive data types: The primitive data types include Integer, Character, Boolean,
and Floating Point.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.

Data Type Default Value Default size


Boolean false 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

Arrays
Normally, array is a collection of similar type of elements that have contiguous memory
location. Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of elements in a java
array. Array in java is index based, first element of the array is stored at 0 index.
Advantage of Java Array
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
o Random access: We can get any data located at any index position.
Disadvantage of Java Array
o Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.
Types of Array in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
Single Dimensional Array in java
Syntax to Declare an Array in java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in java
arrayRefVar=new datatype[size];
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare instantiate,
initialize and traverse an array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output: 10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:33
3
4
5

Passing Array to method in java


We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}}
Output: 3
Multidimensional array in java
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:1 2 3
245
445
What is the class name of java array?
In java, array is an object. For array object, an proxy class is created whose name can be
obtained by getClass().getName() method on the object.
Control statements
The control statement are used to controll the flow of execution of the program . This
execution order depends on the supplied data values and the conditional logic. Java contains
the following types of control statements:
 Selection Statements
 Repetition Statements
 Branching Statements
Selection statements:
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}

Example:
public class IfExample {
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}

Example:
public class IfElseExample {
public static void main(String[] args) {
int number=13;
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Output:
odd number
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-
if ladder statement.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

Example:
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
Repetition Statements
In programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true. There are three types of loops in java.
o for loop
o while loop
o do-while loop

while loop statements:


This is a looping or repeating statement. It executes a block of code or statements till the
given condition is true. The expression must be evaluated to a boolean value. It continues
testing the condition and executes the block of code. When the expression results to false
control comes out of loop.
Syntax:
while(expression){
<statement>;
...;
...;
}
Example:
Here expression i<=10 is the condition which is checked before entering into the loop
statements. When i is greater than value 10 control comes out of loop and next statement is
executed. So here i contains value "1" which is less than number "10" so control goes inside
of the loop and prints current value of i and increments value of i. Now again control comes
back to the loop and condition is checked. This procedure continues until i becomes greater
than value "10". So this loop prints values 1 to 10 on the screen.
int i = 1;
//print 1 to 10
while (i <= 10){
System.out.println("Num " + i);
i++;
}
do-while loop statements:
This is another looping statement that tests the given condition past so you can say that the
do-while looping statement is a past-test loop statement. First the do block statements are
executed then the condition given in while statement is checked. So in this case, even the
condition is false in the first attempt, do block of code is executed at least once.
Syntax:
do{
<statement>;
...;
...;
}while (expression);

Example:
Here first do block of code is executed and current value "1" is printed then the condition
i<=10 is checked. Here "1" is less than number "10" so the control comes back to do block.
This process continues till value of i becomes greater than 10.
int i = 1;
do{
System.out.println("Num: " + i);
i++;
}while(i <= 10);

for loop statements:


This is also a loop statement that provides a compact way to iterate over a range of values.
From a user point of view, this is reliable because it executes the statements within this block
repeatedly till the specified conditions is true .
Syntax:
for (initialization; condition; increment or decrement){
<statement>;
...;
...;
}
initialization: The loop is started with the value specified.
condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.
increment or decrement: After each iteration, value increments or decrements.
Example:
Here num is initialized to value "1", condition is checked whether num<=10. If it is so then
control goes into the loop and current value of num is printed. Now num is incremented and
checked again whether num<=10.If it is so then again it enters into the loop. This process
continues till num>10. It prints values 1 to10 on the screen.
for (int num = 1; num <= 10; num++){
System.out.println("Num: " + num);
}

Branching Statements:
Break statements:
The break statement is a branching statement that contains two forms: labeled and unlabeled.
The break statement is used for breaking the execution of a loop (while, do-while and for) . It
also terminates the switch statements.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
Continue statements:
This is a branching statement that are used in the looping statements (while, do-while and for)
to skip the current iteration of the loop and resume the next iteration .
Syntax:
continue;
Return statements:
It is a special branching statement that transfers the control to the caller of the method.
This statement is used to return a value to the caller method and terminates execution of
method. This has two forms: one that returns a value and the other that can not return. the
returned value type must match the return type of method.
Syntax:
return;
return values;
return; //This returns nothing. So this can be used when method is declared with void
return type.
return expression; //It returns the value evaluated from the expression.
Constructors
In Java, constructor is a block of codes similar to method. It is called when an instance of
object is created and memory is allocated for the object. It is a special type of method which
is used to initialize the object.
When is a constructor called: Every time an object is created using new() keyword, at least
one constructor is called. It is called a default constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors in java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Java parameterized constructor
A constructor which has a specific number of parameters is called parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the list
and their types.
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour of an
object.

Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler in any
don't have any constructor. case.

Constructor name must be same as the class name. Method name may or may not be same as
class name.

Access control
There are two types of modifiers in java: access modifiers and non-access modifiers. The
access modifier in java specifies accessibility (scope) of a data member, method, constructor
or class.
There are 4 types of java access modifiers:
 private
 default
 protected
 public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
private access modifier
The private access modifier is accessible only within class.
example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
default access modifier
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
protected access modifier
The protected access modifier is accessible within package and outside the package but
through inheritance only. The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output: Hello
public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

This keyword
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.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.

1) this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Example
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000
112 sumit 6000

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
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello n
hello m
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.
Calling default constructor from parameterized constructor:
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello a
10
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling
Application of this that can be passed as an argument: In event handling (or) in a situation
where we have to provide reference of a class to another one. It is used to reuse one object in
many methods.
5) this: to pass as argument in the constructor call
We can pass the this keyword in the constructor also. It is useful if we have to use one object
in multiple classes.
6) this keyword can be used to return current class instance
We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
Overloading methods
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program. Suppose you have to perform addition of
the given numbers but there can be any number of arguments, if you write the method such as
a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for
you as well as other programmers to understand the behavior of the method because its name
differs. So, we perform method overloading to figure out the program quickly.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
In java, Method Overloading is not possible by changing the return type of the method only.
Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers. In this example, we are
creating static methods so that we don't need to create instance for calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
Garbage collection
In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the
runtime unused memory automatically. In other words, it is a way to destroy the unused
objects. To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
 It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
How can an object be unreferenced?
There are many ways:
 By nulling the reference
 By assigning a reference to another
 By annonymous object etc.
By nulling a reference:
Employee e=new Employee();
e=null;
By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
By annonymous object:
new Employee();
finalize() method: The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This method is defined in
Object class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).
gc() method: The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC).
This thread calls the finalize() method before object is garbage collected.
Simple Example of garbage collection in java
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Test it Now
object is garbage collected
object is garbage collected

Self Study Course:


Features of object-oriented programming–Java History–Computer Programming Hierarchy–
Role of Java Programmer in Industry

You might also like