0% found this document useful (0 votes)
4 views64 pages

UNIT1 JAVA Converted 1

The document provides an overview of object-oriented programming (OOP) concepts through Java, covering topics such as classes, inheritance, polymorphism, encapsulation, and data abstraction. It explains the importance of these concepts using real-world examples and discusses Java's features, including its platform independence and security. Additionally, it details the history of Java's development and its execution process, including static and dynamic loading, and introduces Java's primitive data types.

Uploaded by

Vinay Vinnu
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)
4 views64 pages

UNIT1 JAVA Converted 1

The document provides an overview of object-oriented programming (OOP) concepts through Java, covering topics such as classes, inheritance, polymorphism, encapsulation, and data abstraction. It explains the importance of these concepts using real-world examples and discusses Java's features, including its platform independence and security. Additionally, it details the history of Java's development and its execution process, including static and dynamic loading, and introduces Java's primitive data types.

Uploaded by

Vinay Vinnu
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
You are on page 1/ 64

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

UNIT - I

Object-oriented thinking- A way of viewing world – Agents and


Communities, messages and methods, Responsibilities, Classes and
Instances, Class Hierarchies- Inheritance, Methodbinding, Overriding and
Exceptions, Summary of Object-Oriented concepts. Java buzzwords, An
Overview of Java, Data types, Variables and Arrays, operators,
expressions, control statements, Introducing classes, Methods and
Classes, String handling. Inheritance– Inheritance concept, Inheritance
basics, Member access, Constructors, Creating Multilevel hierarchy, super
uses, using final with inheritance, Polymorphism-ad hoc polymorphism,
pure polymorphism, method overriding, abstract classes, Object class,
forms of inheritance- specialization, specification, construction,
extension, limitation, combination, benefits of inheritance, costs of
inheritance.

A way of viewing world:

The object oriented concepts can be understood with the help of real-world
examples Suppose Mr. A wants to send a music system to a person Mr. B who
lives in another city. Instead of personally delivering the music system to B, the
person A will go to the shopkeeper Mr. X in his city, Mr. X will then in turn
contact another shopkeeper Mr. Y in B’s city by telling him what kind of music
system do Mr. a expects for Mr. B. The shopkeeper Y will contact a
manufacturer Mr. Z and get the desired music system for him. The music
system will then be delivered to Mr. B gets music system from Mr. A.

With the help of above real world Example let us understand the basic
concepts of object oriented programming.

Agents and Communities:

In the above described scenario, the important thing is to find an appropriate


agent and to pass the message to that agent. This message contains the
request. It is the responsibility of Mr. X to satisfy the request. For satisfying the
request Mr. X uses a method or an algorithm. This algorithm is usually hidden
from Mr. A

Objects and Community

An object oriented program consists of a set of agents that communicate with


each other. These agents are called objects. This communication is done by
sending and receiving the messages.

A collection of interacting objects form a community in object oriented


programming.

Messages and Methods:

A message for an object is a request made for execution of method for obtaining
the service.

A method is a set of code which is referred to by name and can be called


(invoked) at any point in a program simply by utilizing the method's name.

Responsibilities:

The behavior of object as response is called responsibility of that object.

Classes and instances:

Each class is a collection of data and the functions that manipulate the data.

The data components of class are called data fields and the function
components are called member functions or methods.

Object is an instance of a class. The objects represent the real world entity. The
objects are used to provide a practical basis for the real world.
Class Hierarchies- Inheritance

In object oriented programming, sometimes new classes can be created from


the old classes. In other words new classes share some properties of old
classes.

A class hierarchy for various material objects.

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

Method Overriding:

The same method name and method signature can be used in super and sub
classes is known as method Overriding

Exceptions:

An Exception is a run-time error which interrupts the normal flow of program


execution
Object-Oriented Programming concepts:

Oriented Programming is a methodology or paradigm to design a program


using classes and objects. It simplifies the software development and
maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
o Dynamic Binding
o Message passing
Object: it is an instance of a class.
Class: A class is a collection of methods and member functions
Inheritance: Acquiring the properties from existing class into new class is
known as Inheritance.
It provides code reusability. It is used to achieve runtime
polymorphism.

Types: Single Inheritance


Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance

Polymorphism: Polymorphism (from Greek, meaning “many forms”) is a feature


that allows one interface to be used for a general class of actions.
Types:

1. Operator Overloading
2. Method Overloading

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 is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
class is the example of encapsulation.

Dynamic Binding: Binding the data at run time is known as Dynamic binding.
Message passing: Sending or Receiving of information by the objects is known
as Message passing
Java buzzwords:

Object Oriented: In Java, everything is an Object. Java can be easily extended


since it is based on the Object model.

Platform independent: Unlike many other programming languages including


C and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by virtual Machine (JVM) on
whichever platform it is being run.

Simple: Java is designed to be easy to learn. If you understand the basic


concept of OOP, Java would be easy to master.

Secure: With Java's secure feature, it enables to develop virus-free, tamper-free


systems. Authentication techniques are based on public-key encryption.

Architectural-neutral: Java compiler generates an architecture-neutral object


file format, which makes the compiled code to be executable on many
processors, with the presence of Java runtime system.

Portable: Being architectural-neutral and having no implementation


dependent aspects of the specification makes Java portable. Compiler in Java
is written in ANSI C with a clean portability boundary which is a POSIX subset.

Robust: Java makes an effort to eliminate error prone situations by


emphasizing mainly on compile time error checking and runtime checking.

Multithreaded: With Java's multithreaded feature, it is possible to write


programs that can do many tasks simultaneously. This design feature allows
developers to construct smoothly running interactive applications.

Interpreted: Java byte code is translated on the fly to native machine


instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and lightweight
process.

High Performance: With the use of Just-In-Time compilers, Java enables high
performance. Distributed: Java is designed for the distributed environment of
the internet.

Dynamic: Java is considered to be more dynamic than C or C++ since it is


designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
An Overview of Java
In 1990, Sun Microsystems inc. (US) has conceived a project to develop
software for consumer electronic devices that could be controlled by a remote.
This project was called Stealth project but later its name was changed to Green
Project.
In Jan 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton and
several others met in Aspen, Colorado to discuss this project. Mike Sheradin
was to focus on business development; Patrick Naughton was to begin work on
the graphic system; and James Gosling was to identify the proper programming
language for the project, Gosling thought C and C++ could be used to develop
the project. But the problem he faced with them is that they were system
dependent languages and hence could not be used on various processors,
which the electronic devices might use. So he started developing a new
language, which was completely system independent. This language was
initially called Oak. Since this was registered by some other company, later it
was changed to Java.

Why the name Java? James Gosling and his team members were consuming a
lot of tea while developing this language. They felt that they were able to
develop a better language because of the good quality tea they had consumed.
So the tea also had its own role in developing this language and hence, they
fixed the name for the language as Java. Thus, the symbol for Java is tea cup
and saucer.

By September of 1994, Naughton and Jonathan Payne started writing Web


Runner- a Java –based Web Browser, which was later renamed as HotJava. By
October 1994, HotJava was stable and was demonstrated to Sun executives.
HotJava was the first browser, having the capabilities of executing applets,
which are programs designed to run dynamically on internet. This time, java’s
potential in the context of the World Wide Web was organized.

Sun Formally announced Java and HotJava at SunWorld conference in 1995.


Soon after, Netscape Inc. announced that it would incorporate Java support in
the browser Netscape Navigator. Later, Microsoft also announced that they
would support Java in their Internet Explorer web browser, further solidifying
java’s role in the World Wide Web. On Jan 23rd 1996, JDK 1.0 version was
released.

Execution of a Java Program


Static Loading:
A block of code would be loaded into the RAM before it is executed (i.e. after
being loaded into the RAM, it may or may not get executed).
Dynamic Loading:
A block of code would be loaded into the RAM only when it is required to be
executed.
Note: Static loading takes place in the execution of structured programming
languages. EX: C-language.
Java follows Dynamic loading.
• JVM would not convert all the statements of the .class file into its executable
code at a time.
• Once the control comes out from the method, then it is deleted from the RAM
and another method of .exe type will be loaded as required.
• Once the control comes out from the main(), the main() method would also be
deleted from the RAM. This is why we are not able to view the .exe contents of a
class file.

Functions of JVM:
✓ It converts the required part of the byte code into its equivalent
executable code.
✓ It loads the executable code into the RAM
✓ Executes this code through local operating system.
✓ Deletes the executable code from the RAM.

JVM converts .class file into its equivalent executable code. Now, if a JVM is in
windows environment it converts the .class file into its environment only.
Similarly, same is the ease with UNIX or other OS.
Thus JVM is platform dependent.
But the platform dependent of the JVM is not considered while saying Java is
platform independent, because JVM is supplied free of cost through the
interest by the Sun Micro System.
Platform Independent:
Complied code of a program should be executed in any OS, irrespective of the
OS in which that code had been generated. This concept is known as platform
independent.
➢ The birth of OOPS concept took place with encapsulation.
➢ Any program contains 2 parts :
Data part and Logic part.
Program

Data

DataLogics
Out of data and logics highest priority is given to data. But in structured
programming languages the data insecurity is high. Thus in a process of
securing data in structured programming language. The concept of
encapsulation came into existence.

In structured programming language programs, the global variables play a


vital role. But, because of these global variables there is data insecurity in the
structured programming lang. program. i.e. functions that are not related to
some variables will have access to those variables and thus data may get
corrupted. In this way data is unsecured.

This is what people say in general about data insecurity. But this is not the
actual reason. The actual concept is as follows:

Let us assume that, we have ‘C’ program with 100 functions. Assume that it is
a project. Now if any upgrading is required, then the client i.e. the user of this
program(S/W) comes to the IT company and asks the programmers to update it
according to his requirement. Now we should note that, it is not generated that
the programmers who developed. Hence this project falls into the hands of new
programmers.

Automatically it takes a lot of time to study the project itself before upgrading
it. It may not be surprising that the time required for writing the code to update
the project may be very less when compared to the time required for studying
the project.

Thus maintenance becomes a problem.

It the new programmer adds a new function to the existing code in the way of
upgrading it, there is no guarantee that it will not affect the existing functions
in the code. This is because of global variables. In this way data insecurity is
created.

To overcome this problem, programmers developed the concept of


Encapsulation.
For example, let us have a program struct.prog program with ten global
variables and twenty functions.
It is sure that all the twenty functions will not use all the global variables.
Three of the global variables may be used only by two functions. But in a
structured programming Language like ‘C’ it is not possible to restrict the
access of variables. Global variables by some limited number of functions.
Every function will have access to all the global variables.

To avoid this problem, Programmers have designed a way such that the
variables and the functions which are associated with or operate on those
variables are enclosed in a block and that block is called a Class and that class
is giver a name, just as a function is given a name.

Now the variables inside the block cannot be called as local variables because
they are not local to only one function and they cannot be called as global
variables because they are confined to a block and not global.

Hence these variables are known as Instance variables.

Ex.
Struct .prog.lang.program
#include<stdio.h>
int I,j,k,l,m,n;
func 1()
{
}
func 2()
{
}
func3()
{
}
.
.
.
func10()
{
}
main()
{
}
Ex.
OOP.lan.program
class abc
{
int i,j,k;
func1()
{
}
func2()
{
}
}
Class xyz
{
int i,m,n;
func3()
{
}
func4()
{
}
}

Therefore a class is nothing but grouping data along with its functionalities.
Note 1: Encapsulation is the concept of binding data along with its
corresponding functionalities.
Encapsulation comes into existence in order to provide security for the data
present inside the program.

Note 2: any OOP language file looks like a group of classes. Everything is
encapsulated. Nothing is outside the class.
➢ Encapsulation is the backbone of OOP languages.
➢ JAVA supports all the OOP concepts (i.e. encapsulation, polymorphism,
inheritance) and hence it is known as object oriented programming language.
➢ C++ breaks the concept of encapsulation, because the main() method in a C++
program is declared outside a class. Hence, it is not a pure OOP language.
Infact, it is poor OOP language.

A simple java program:

Rules and Regulations:


• The class name should start with a capital letter. This is not compulsory but it
is a conventional rule.
• Java is case sensitive.
• All the keywords in java are written in small letters.
import java.lang.*;
class Hello
{
public static void main(String args[])
{
System.out.println(“welcome to VAAGESWARI”);
}
}
In the above program, Hello is the class name. we have the main method which
has only one statement in it.
In the above program public, static, void are keywords. main() is a method,
String is a class, println is a method and System is a class.
Let us save the program in the name Hello.java. Now, we compile the program
with the following command in the DOS prompt.
C:\>javac Hello.java
After execution of this command, the .class file i.e. Hello.class is created.
In other words, it is the dos command given to the Java compiler to convert
contents of the mentioned source into its equivalent byte code.
Now the following command is given to the JVM to execute the .class file
C:\>java Hello

Data types
Data types are used to represent the types of data.
Java defines eight primitive types of data:
byte, short, int, long, char, float, double, and boolean.

These can be put in four groups:


• Integers this group includes byte, short, int, and long, which are for whole-
valued signed numbers.
• Floating-point numbers this group includes float and double, which
represent numbers with fractional precision.
• Characters this group includes char, which represents symbols in a
character set, like letters and numbers.
• Boolean this group includes boolean, which is a special type for
representing true/false values.
Example:

import java.lang.*;
class DataTypesDemo
{
public static void main(String[] args)
{
byte a=20;
short b=40;
int c=123;
long d=245678;
float e=2.1234f;
double d1=5.678923;
char c1='v';
boolean b1=true;
System.out.println(" byte value is"+a);
System.out.println(" short value is"+b);
System.out.println(" int value is"+c);
System.out.println(" long value is"+d);
System.out.println(" float value is"+e);
System.out.println(" double value is"+d1);
System.out.println(" char value is"+c1);
System.out.println(" boolean value is"+b1);

}
}

Output:

byte value is 20
short value is 40
int value is 123
long value is 245678
float value is 2.1234
double value is 5.678923
char value is v
boolean value is true
Variables:
A variable is a data name which can be used to store the data.
There are a few rules and conventions related to the naming of variables.
The rules are:
1. Java variable names must start with a letter, or the $ or underscore
symbol (_).
2. A variable name can consist of letters (a-z, A-Z), digits(0-9) and
underscore symbol(_).
3. Reserved words or keyword are not allowed. For instance, the words int
or for are reserved words in Java. Therefore you cannot name your
variables int or for.
4. White spaces are not allowed.
5. Java variable names are case sensitive. The variable name vaageswari is
not the same as Vaageswari or VAAGESWARI.

Here are a few valid Java variable name examples:


section
roll_number
MIB2
cse2
with_lot_of_under_scores__
_starting_with_under_score_
numberOfStudents
runsCount
i
j
ABC345
PI
$myVar
myVar_1

Invalid variables:
Vaageswari colleges
3abc
7/ARamakrishnaColony
name_with_special_chars@@#
#oo#

Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form
of a variable
declaration is shown here:

type identifier [ = value ][, identifier [= value ] …];

Here, type is one of Java’s atomic types. The identifier is the name of the
variable.
Operators:
Types of Operator in Java

1) Basic Arithmetic Operators


2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator
8) instanceof Operator

1) Basic Arithmetic Operators


Basic arithmetic operators are: +, -, *, /, %
+ is for addition.
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example 11 % 5 would return 1

Example of Arithmetic Operators


public class ArithmeticOperatorDemo
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 20;
System.out.println("addition = " + (num1 + num2) );
System.out.println("subtraction= " + (num1 - num2) );
System.out.println("multiplication= " + (num1 * num2) );
System.out.println("division= " + (num1 / num2) );
System.out.println("modulo = " + (num1 % num2) );
}
}

Output:

addition = 120
subtraction= 80
multiplication= 2000
division= 5
modulo = 0
2) Assignment Operators

Assignments operators in java are: =, +=, -=, *=, /=, %=

num2 = num1 would assign value of variable num1 to the variable.


num2+=num1 is equal to num2 = num2+num1
num2-=num1 is equal to num2 = num2-num1
num2*=num1 is equal to num2 = num2*num1
num2/=num1 is equal to num2 = num2/num1
num2%=num1 is equal to num2 = num2%num1

Example of Assignment Operators


public class AssignmentOperatorDemo
{
public static void main(String args[])
{
int num1 = 10;
int num2 = 20;
num2 = num1;
System.out.println("= Output: "+num2);
num2 += num1;
System.out.println("+= Output: "+num2);
num2 -= num1;
System.out.println("-= Output: "+num2);
num2 *= num1;
System.out.println("*= Output: "+num2);
num2 /= num1;
System.out.println("/= Output: "+num2);
num2 %= num1;
System.out.println("%= Output: "+num2);
}
}

Output:

= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0
3) Auto-increment and Auto-decrement Operators

++ and --
num++ is equivalent to num=num+1;
num–- is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators


public class AutoOperatorDemo
{
public static void main(String args[])
{
int num1=100;
int num2=200;
num1++;
num2--;
System.out.println("num1++ is: "+num1);
System.out.println("num2-- is: "+num2);
}
}
Output:
num1++ is: 101
num2-- is: 199

4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in
conditional statements and loops for evaluating a condition.

Logical operators in java are: &&, ||, !

Let’s say we have two boolean variables b1 and b2.


b1&&b2 will return true if both b1 and b2 are true else it would return false.
b1||b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false
and it would return false if b1 is true.

Example of Logical Operators


public class LogicalOperatorDemo
{
public static void main(String args[])
{
boolean b1 = true;
boolean b2 = false;

System.out.println("b1 && b2: " + (b1&&b2));


System.out.println("b1 || b2: " + (b1||b2));
System.out.println("!(b1 && b2): " + !(b1&&b2));
}
}

Output:
b1 && b2: false
b1 || b2: true
!(b1 && b2): true

5) Comparison(Relational) operators
We have six relational operators in Java: ==, !=, >, <, >=, <=

== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.

Example of Relational operators


public class RelationalOperatorDemo
{
public static void main(String args[])
{
int num1 = 10;
int num2 = 50;
if (num1==num2)
{
System.out.println("num1 and num2 are equal");
}
else
{
System.out.println("num1 and num2 are not equal");
}
if( num1 != num2 )
{
System.out.println("num1 and num2 are not equal");
}
else
{
System.out.println("num1 and num2 are equal");
}
if( num1 > num2 )
{
System.out.println("num1 is greater than num2");
}
else{
System.out.println("num1 is not greater than num2");
}
if( num1 >= num2 )
{
System.out.println("num1 is greater than or equal to num2");
}
else{
System.out.println("num1 is less than num2");
}
if( num1 < num2 )
{
System.out.println("num1 is less than num2");
}
else{
System.out.println("num1 is not less than num2");
}
if( num1 <= num2)
{
System.out.println("num1 is less than or equal to num2");
}
else{
System.out.println("num1 is greater than num2");
}
}
}

Output:
num1 and num2 are not equal
num1 and num2 are not equal
num1 is not greater than num2
num1 is less than num2
num1 is less than num2
num1 is less than or equal to num2

6) Bitwise Operators
There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */
Bitwise operator performs bit by bit processing.
num1 & num2 compares corresponding bits of num1 and num2 and generates
1 if both bits are equal, else it returns 0. In our case it would return: 2 which is
00000010 because in the binary form of num1 and num2 only second last bits
are matching.

num1 | num2 compares corresponding bits of num1 and num2 and generates
1 if either bit is 1, else it returns 0. In our case it would return 31 which is
00011111

num1 ^ num2 compares corresponding bits of num1 and num2 and generates
1 if they are not equal, else it returns 0. In our example it would return 29
which is equivalent to 00011101

~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to
0. In our example it would return -12 which is signed 8 bit equivalent to
11110100

num1 << 2 is left shift operator that moves the bits to the left, discards the far
left bit, and assigns the rightmost bit a value of 0. In our case output is 44
which is equivalent to 00101100

Note: In the example below we are providing 2 at the right side of this shift
operator that is the reason bits are moving two places to the left side. We can
change this number and bits would be moved by the number of bits specified
on the right side of the operator. Same applies to the right side operator.

num1 >> 2 is right shift operator that moves the bits to the right, discards the
far right bit, and assigns the leftmost bit a value of 0. In our case output is 2
which is equivalent to 00000010
Example of Bitwise Operators

public class BitwiseOperatorDemo


{
public static void main(String args[])
{
int num1 = 11; /* 11 = 00001011 */
int num2 = 22; /* 22 = 00010110 */
int result = 0;
result = num1 & num2;
System.out.println("num1 & num2: "+result);
result = num1 | num2;
System.out.println("num1 | num2: "+result);
result = num1 ^ num2;
System.out.println("num1 ^ num2: "+result);
result = ~num1;
System.out.println("~num1: "+result);
result = num1 << 2;
System.out.println("num1 << 2: "+result); result = num1 >> 2;
System.out.println("num1 >> 2: "+result);
}
}

Output:
num1 & num2: 2
num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2

7) Ternary Operator
This operator evaluates a boolean expression and assign the value based on
the result.
Syntax:
variable num1 = (expression) ? value if true : value if false

If the expression results true then the first value before the colon (:) is assigned
to the variable num1 else the second value is assigned to the num1.
Example of Ternary Operator

public class TernaryOperatorDemo


{
public static void main(String args[])
{
int num1, num2;
num1 = 25;
num2 = (num1 == 10) ? 100: 200;
System.out.println( "num2: "+num2);
num2 = (num1 == 25) ? 100: 200;
System.out.println( "num2: "+num2);
}
}

Output:
num2: 200
num2: 100
8. instanceof Operator
The instanceof operator is used to specify object reference variables. It checks if
the object is of a particular type (class type or interface type) or not.

Syntax
( Object reference variable ) instanceof (class/interface type)

If the left side object referred by the variable passes the IS-A check for the
class/interface type on the right side, then the result is displayed as true.
Instanceof Operator Examples
public class Team
{
public static void main(String args[])
{
String name = "vaageswari";
boolean result = name instanceof String;
System.out.println( result );
}
}

Output
true
Control statements

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’s program control statements can be put into the following categories:
selection, iteration, and jump. Selection statements allow your program to
choose different paths of execution based upon the outcome of an expression
or the state of a variable. Iteration statements enable program execution to
repeat one or more statements (that is, iteration statements form loops). Jump
statements allow your program to execute in a nonlinear fashion
Java’s Selection Statements
Java supports two selection statements: if and switch. These statements allow
you to control the flow of your program’s execution based upon conditions
known only during run time.
Forms of if
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if ladder
If statement
If statement consists a condition, followed by statement or a set of statements
as shown below:
if(condition)
{
Statement(s);
}
The statements gets executed only when the given condition is true. If the
condition is false then the statements inside if statement body are completely
ignored.
Example of if statement
public class IfStatementExample
{
public static void main(String args[])
{
int num=70;
if( num < 100 )
{
System.out.println("number is less than 100");
}
}
}
Output:
number is less than 100
Nested if statement in Java
When there is an if statement inside another if statement then it is called the
nested if statement.
The structure of nested if looks like this:
if(condition_1)
{
Statement1(s);
if(condition_2)
{
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only
execute if both the conditions( condition_1 and condition_2) are true.
Example of Nested if statement
public class NestedIfExample
{
public static void main(String args[])
{
int num=70;
if( num < 100 )
{
System.out.println("number is less than 100");
if(num > 50)
{
System.out.println("number is greater than 50");
}
}
}
}
Output:
number is less than 100
number is greater than 50

If else statement in Java


This is how an if-else statement looks:
if(condition)
{
Statement(s);
}
else
{
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the
statements inside “else” would execute if the condition is false.
Example of if-else statement
public class IfElseExample
{
public static void main(String args[])
{
int num=120;
if( num < 50 )
{
System.out.println("num is less than 50");
}
else
{
System.out.println("num is greater than or equal 50");
}
}
}
Output:
num is greater than or equal 50

if-else-if ladder
if-else-if ladder is used when we need to check multiple conditions. In this
statement we have only one “if” and one “else”, however we can have multiple
“else if”. It is also known as if else if ladder. This is how it looks:
if(condition_1)
{
statement(s);
}
else if(condition_2)
{
statement(s);
}
else if(condition_3)
{
statement(s);
}
.
.
.
else {
statement(s);
}
Note: The most important point to note here is that in if-else-if statement, as
soon as the condition is met, the corresponding set of statements get executed,
rest gets ignored. If none of the condition is met then the statements inside
“else” gets executed.
Example of if-else-if
public class IfElseIfExample
{
public static void main(String args[])
{
int num=1234;
if(num <100 && num>=1)
{
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100)
{
System.out.println("Its a three digit number");
}
else if(num <10000 && num>=1000)
{
System.out.println("Its a four digit number");
}
else if(num <100000 && num>=10000)
{
System.out.println("Its a five digit number");
}
else {
System.out.println("number is not between 1 & 99999");
}
}
}
Output:
Its a four digit number
Switch case:
Switch case statement is used when we have number of options (or choices)
and we may need to perform a different task for each choice.
The syntax of Switch case statement looks like this –
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
Switch Case statement is mostly used with break statement even though it
is optional.
Example:
public class SwitchCaseExample2
{
public static void main(String args[])
{
int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
case 2:
System.out.println("Case2 ");
case 3:
System.out.println("Case3 ");
case 4:
System.out.println("Case4 ");
default:
System.out.println("Default ");
}
}
}
Output:
Case2
Case3
Case4
Default
Iteration Statements
Java’s iteration statements are for, while, and do-while. These statements
create what we commonly call loops. As you probably know, a loop repeatedly
executes the same set of instructions until a termination condition is met.
While loop :
Loops are used to execute a set of statements repeatedly until a particular
condition is satisfied.
Syntax of while loop
while(condition)
{
statement(s);
}

How while Loop works?


In while loop, condition is evaluated first and if it returns true then the
statements inside while loop execute. When condition returns false, the control
comes out of loop and jumps to the next statement after while loop.
Example:
class WhileLoopExample
{
public static void main(String args[])
{
int i=10;
while(i>1)
{
System.out.println(i);
i--;
}
}
}
Output:
10
9
8
7
6
5
4
3
2
do-while :
do-while loop is similar to while loop, however there is a difference between
them: In while loop, condition is evaluated before the execution of loop’s body
but in do-while loop condition is evaluated after the execution of loop’s body.
Syntax of do-while loop:
do
{
statement(s);
} while(condition);
How do-while loop works?
First, the statements inside loop execute and then the condition gets evaluated,
if the condition returns true then the control gets transferred to the “do” else it
jumps to the next statement after do-while.
Example:
class DoWhileLoopExample
{
public static void main(String args[])
{
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
Output:
10
9
8
7
6
5
4
3
2
For loop :
Loops are used to execute a set of statements repeatedly until a particular
condition is satisfied. Syntax of for loop:
for(initialization; condition ; increment/decrement)
{
statement(s);
}
Flow of Execution of the for Loop
As a program executes, the interpreter always keeps track of which statement
is about to be executed. We call this the control flow, or the flow of execution of
the program.
First step: In for loop, initialization happens first and only one time, which
means that the initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the
condition is true then the statements inside for loop body gets executed. Once
the condition returns false, the statements in for loop does not execute and the
control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement
part of for loop executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition
is re-evaluated.
Example of Simple For loop
class ForLoopExample
{
public static void main(String args[])
{
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}

The output of this program is:


The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
In the above program:
int i=1 is initialization expression
i>1 is condition(Boolean expression)
i--Decrement operation

Java Break Statement


When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following
the loop.
The Java break is used to break loop or switch statement. It breaks the current
flow of the program at specified condition. In case of inner loop, it breaks only
inner loop.
We can use Java break statement in all types of loops such as for loop, while
loop and do-while loop.
Syntax:
jump-statement;
break;
public class BreakExample
{
public static void main(String[] args)
{
//using for loop
for(int i=1;i<=10;i++)
{
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4

Java Continue Statement

The continue statement is used in loop control structure when you need to
jump to the next iteration of the loop immediately. It can be used with for loop
or while loop.

The Java continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition. In case of an inner loop, it continues the inner loop only.

We can use Java continue statement in all types of loops such as for loop,
while loop and do-while loop.

Syntax:

jump-statement;
continue;

public class ContinueExample


{
public static void main(String[] args)
{
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
6
7
8
9
10
As you can see in the above output, 5 is not printed on the console. It is
because the loop is continued when it reaches to 5.

Arrays

Normally, an array is a collection of similar type of elements that have a


contiguous memory location.

Java array is an object which contains elements of a similar data type. It is a


data structure where we store similar elements. We can store only a fixed set of
elements in a Java array.

Array in java is index-based, the first element of the array is stored at the 0
index.

Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.

Random access: We can get any data located at an index position.

Disadvantages

Size Limit: We can store only the 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 which grows automatically.

Types of Array in java

There are two types of array.

Single Dimensional Array

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 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;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

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.
//Java Program to illustrate the use of multidimensional 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:
123
245
445
Introducing classes, Methods and Classes,
Class: A class is a collection of methods and Varaibles

General form of a class definition is :


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
}
}
In the above syntax class is a keyword used to declare a class and class name
is a name of the class. The body of a class is enclosed within braces.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.

Object: it is an instance of a class.


Syntax:
Classname objectname=new classname();
Here the new operator dynamically allocates memory for an object.

Introducing Methods
This is the general form of a method:
type name(parameter-list)
{
// body of method
}
Here, type specifies the type of data returned by the method. This can be any
valid type, including class types that you create. If the method does not return
a value, its return type must be void. The name of the method is specified by
name. This can be any legal identifier other than those already used by other
items within the current scope. The parameter-list is a sequence of type and
identifier pairs separated by commas. Parameters are essentially variables that
receive the value of the arguments passed to the method when it is called. If
the method has no parameters, then the parameter list will be empty. Methods
that have a return type other than void return a value to the calling routine
using the following form of the return statement:
return value;
Here, value is the value returned.

Example:
import java.lang.*;
class Addition
{
int c;
void add(int a,int b)
{
c=a+b;
}
void display()
{
System.out.println("sum is"+c);
}

}
class AdditionDemo
{
public static void main(String[] args)
{
Addition ob=new Addition();
ob.add(10,20);
ob.display();
}
}
Output:
C:\>javac AdditionDemo.java
C:\>java AdditionDemo
sum is30
Constructors
Constructor is a special member function of class and it is used to initialize the
objects of its class.
Special characteristics of Constructors:
Constructor name and class name should be same
They do not have any return type, not even void
They get automatically invoked when the objects are created
They cannot be inherited

Types of Constructors:
Default constructor
Parameterized constructor

Default constructor: A constructor that accepts no parameters is called the


default constructor
Ex:-
import java.lang.*;
class Student
{
Student()
{
System.out.println("welcome to VAAGESWARI");
}
}
class DCDemo
{
public static void main(String args[])
{
Student s=new Student();
}
}

Output:
C:\>javac DCDemo.java
C:\>java DCDemo
welcome to VAAGESWARI
Parameterized constructor: The constructors that can take arguments are
called parameterized constructors.
Ex:
import java.lang.*;
class Student
{
int id;
String name;
Student(int x,String n)
{
id=x;
name=n;
}
void display()
{
System.out.println("student id is"+id);
System.out.println("student name is"+name);
}
}
class PCDemo
{
public static void main(String args[])
{
Student s=new Student(101,"vaageswari");
s.display();
}
}
Output:
student id is101
student name isvaageswari
Example of Constructor Overloading

class Student
{
int id,age;
String name;

Student(int i,String n)
{
id = i;
name = n;
}

Student(int i,String n,int a)


{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
}
Class CODemo
{
public static void main(String args[])
{
Student s1 = new Student(111,"abc");
Student s2 = new Student(222,"xyz",25);
s1.display();
s2.display();
}
}

Inheritance
Inheritance:
Inheritance is the process of inheriting properties of objects of
one class by objects of another class. The class which inherits the properties of
another class is called Derived or Child or Sub class and the class whose
properties are inherited is called Base or Parent or Super class. It provides code
reusability.

Types:
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance

Single Inheritance: Acquiring the properties from one single existing class into
a new class is called Single Inheritance

import java.lang.*;
class csea
{
void display()
{
System.out.println("welcome to csea");
}
}
class cseb extends csea
{
void show()
{
System.out.println("welcome to cseb");
}
}
class SIDemo
{
public static void main(String args[])
{
cseb c=new cseb();
c.display();
c.show();
}
}
Output:
C:\>javac SIDemo.java
C:\>java SIDemo
welcome to csea
welcome to cseb

Multiple Inheritance: Acquiring the properties from two or more existing


classes into a new class is called Multiple Inheritance

Java doesn’t support multiple inheritance.

Multilevel Inheritance: Acquiring the properties from a subclass into a new


class is called Multilevel Inheritance
import java.lang.*;
class csea
{
void display()
{
System.out.println("welcome to csea");
}
}
class cseb extends csea
{
void show()
{
System.out.println("welcome to cseb");
}
}
class csec extends cseb
{
void print()
{
System.out.println("welcome to cseb");
}
}
class MLDemo
{
public static void main(String args[])
{
csec c=new csec();
c.display();
c.show();
c.print();
}
}Output:

C:\>javac MLDemo.java
C:\>java MLDemo
welcome to csea
welcome to cseb
welcome to cseb

Hierarchical Inheritance
Acquiring the properties from one existing class into two or more new classes is
called Hierarchical Inheritance
Example:
import java.lang.*;
class vaag
{
void display()
{
System.out.println("welcome to csea");
}
}
class csea extends vaag
{

void show()
{
System.out.println("welcome to cseb");
}
}
class csec extends vaag
{
void print()
{
System.out.println("welcome to cseb");
}
}
class HIDemo
{
public static void main(String args[])
{
csea a=new csea();
a.display();
cseb b=new cseb();
b.show();
csec c=new csec();
c.print();
}
}
Output:
C:\>javac HIDemo.java
C:\>java HIDemo
welcome to csea
welcome to cseb
welcome to cseb
Super uses
Whenever a subclass needs to refer to its immediate super class, it can do so
by use of the keyword super.
Super has two general forms.
The first calls the super class constructor.
The second is used to access a member of the super class that has been hidden
by a member of a subclass.
Using super to Call Super class Constructors
A subclass can call a constructor defined by its super class by use of the
following form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the super
class.
Example:
import java.lang.*;
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
Output:
C:\>javac TestSuper1.java
C:\>java TestSuper1
animal is created
dog is created
A Second Use for super
The second form of super acts somewhat like this, except that it always refers
to the superclass of the subclass in which it is used. This usage has the
following general form:
super.member
Here, member can be either a method or an instance variable.

Example:
import java.lang.*;
class A
{
int i;
}
class B extends A
{
int i;
B(int a, int b)
{
super.i = a;
i = b;
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
{
public static void main(String args[])
{
B subOb = new B(1, 2);
subOb.show();
}
}
Output:
i in superclass: 1
i in subclass: 2
Final Keyword
The keyword final has three uses.
1. It is used to create a constant
2. It prevents from method overriding
3. It prevents from inheritance.

It is used to create a constant


import java.lang.*;
class CArea
{
final double pi=3.14;
void area(double r)
{
double a=pi*r*r;
System.out.println("CircleArea is"+a);
}
}
class final1Demo
{
public static void main(String[] args)
{
CArea c=new CArea();
c.area(2.3);
}
}
Output:
C:\>javac final1Demo.java
C:\>java final1Demo
CircleArea is16.610599999999998

It prevents from method overriding


If you make any method as final, you cannot override it.
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()// ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you
attempt to do so, a compile-time error will result.
It prevents from inheritance.
If you make any class as final, you cannot extend it.
example of a final class:
final class A
{
//...
}
// The following class is illegal.
class B extends A
{ // ERROR! Can't subclass A
//...
} As the comments imply, it is illegal for B to inherit A since A is declared as
final.
The Object Class
There is one special class, Object, defined by Java. All other classes are
subclasses of Object. That is, Object is a super class of all other classes. This
means that a reference variable of type Object can refer to an object of any
other class. Also, since arrays are implemented as classes, a variable of type
Object can also refer to any array. Object defines the following methods, which
means that they are available in every object.
Member access
Access Specifier is a key word that specifies how to access the members of a
class. We can use access specifiers before a class and its members. There are
four access specifiers available in java.
Private
Public
Protected
Default
Private: private members of a class are not accessible anywhere outside the
class. They are accessible only within the class by the methods of that class.
Public: public members of a class are accessible everywhere outside the class.
So any other program can read them and use them.
Protected: protected members of a class are accessible outside the class, but
generally within the same directory.
Default: if no access specifier is written by the programmer, then the java
compiler uses a default access specifier. Default members are accessible
outside the class, but within the same directory.

Polymorphism:
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one
interface to be used for a general class of actions.

The ability to exist in different forms is called polymorphism.

In java, polymorphism implemented using method overloading and method


overriding.
Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with
different implementations and different arguments. In a java programming
language, ad hoc polymorphism carried out with a method overloading
concept.
Method overloading: In a class the same method name should be used with
different parameters is called Method overloading.

In ad hoc polymorphism the method binding happens at the time of


compilation. Ad hoc polymorphism is also known as compile-time
polymorphism. Every function call binded with the respective overloaded
method based on the arguments.
The ad hoc polymorphism implemented within the class only.
Let's look at the following example java code.
Example
import java.lang.*;
class MethodOverloading
{
void display(int i)
{
System.out.println("i value is"+i);
}
void display(double j,char c)
{
System.out.println("j value is"+j);
System.out.println("given character is"+c);
}
}
class MODemo
{
public static void main(String[] args)
{
MethodOverloading m=new MethodOverloading();
m.display(10);
m.display(2.45,'v');
}
}

Pure polymorphism
The pure polymorphism is a technique used to define the same method with
the same arguments but different implementations. In a java programming
language, pure polymorphism carried out with a method overriding concept.

Method overriding: The same method name and method prototype can be
used in super and sub classes is called method overriding
In pure polymorphism, the method binding happens at run time. Pure
polymorphism is also known as run-time polymorphism. Every function call
binding with the respective overridden method based on the object reference.
When a child class has a definition for a member function of the parent class,
the parent class function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Let's look at the following example java code.
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
The output from the program is shown here:
Inside A's callme method
Inside B's callme method
Inside C's callme method
String handling

Return
Me Method Description Value

charAt(int) Finds the character at given index char

length() Finds the length of given string int

compareTo(String) Compares two strings int

compareToIgnoreCase(String) Compares two strings, ignoring case int

concat(String) Concatenates the object string with String


argument string.

contains(String) Checks whether a string contains sub- boolean


string

equals(String) Checks whether two strings are same boolean

equalsIgnoreCase(String) Checks whether two strings are same, boolean


ignoring case

starts With(String) Checks whether a string starts with the boolean


specified string

endsWith(String) Checks whether a string ends with the boolean


specified string

getBytes() Converts string value to bytes byte[]


Return
Me Method Description Value

hashCode() Finds the hash code of a string int

indexOf(String) Finds the first index of argument string int


in object string

lastIndexOf(String) Finds the last index of argument string in int


object string

isEmpty() Checks whether a string is empty or not boolean

replace(String, String) Replaces the first string with second String


string

replaceAll(String, String) Replaces the first string with second String


string at all occurrences.

substring(int, int) Extracts a sub-string from specified start String


and end index values

toLowerCase() Converts a string to lower case letters String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends String

toString(int) Converts the value to a String object String

public class JavaStringExample


{
public static void main(String[] args)
{
String title = "Java Tutorials";
String siteName = "www.btechsmartclass.com";
System.out.println("Length of title: " + title.length());
System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Last index of 'a': " + title.lastIndexOf('a'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Endswith'.com':" + siteName.endsWith(".com"));
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}

F:\java>javac JavaStringExample.java
F:\java>java JavaStringExample
Length of title: 19
Char at index 3: G
Index of 'T': 4
Last index of 'A': 7
Empty: false
Endswith'.in':true
Equals: false
Sub-string: ac.in
Upper case: WWW.VGSEK.AC.IN

length(): Finds the length of given string

Ex: String str1 = "Java";


str1.length (); =4

charAt (int): finds the character at given index


String str1 = "Learn Java";
str1.charAt(0); =L

concat(String): Concatenates the object string with argument string.


String str1 = "Learn ";
String str2 = "Java";
str1.concat (str2); = Learn Java
str2.concat (str1); = JavaLearn

contains(String): Checks whether a string contains sub-string


String str1 = "Learn Java";
result = str1.contains("Java");
System.out.println(result); // true

compareTo(String): Compares two strings


returns 0 if the strings are equal
returns a negative integer if the string comes before the str argument in the
dictionary order
returns a positive integer if the string comes after the str argument in the
dictionary order
String str1 = "Learn Java";
String str2 = "Learn Java";
String str3 = "Learn Kolin";
int result;
result = str1.compareTo (str2);
System.out.println (result); // 0
result = str1.compareTo(str3);
System.out.println(result); // -1
result = str3.compareTo (str1);
System.out.println (result); // 1

compareToIgnoreCase(String): compares two strings, ignoring case


String str1 = "Learn Java";
String str2 = "learn java";
String str3 = "Learn Kolin";
int Result;

Result = str1.compareToIgnoreCase (str2);


System.out.println (Result); // 0

Result = str1.compareToIgnoreCase (str3);


System.out.println (Result); // -1

Result = str3.compareToIgnoreCase (str1);


System.out.println (Result); // 1

equals (): Java String equals () method returns true if two strings are
equal. If not, equals () returns false.

String str1 = "Learn Java";


String str2 = "Learn Java";
String str3 = "Learn Kolin";
Boolean result;
result = str1.equals (str2);
System.out.println (result); // true

result = str1.equals(str3);
System.out.println(result); // false

equalsIgnoreCase(String) The Java String equalsIgnoreCase() method


compares two strings, ignoring case differences. If the strings are equal,
equalsIgnoreCase() returns true. If not, it returns false.

String str1 = "Learn Java";


String str2 = "learn java";
String str3 = "Learn Kolin";
Boolean result;

result = str1.equalsIgnoreCase(str2);
System.out.println(result); // true

result = str1.equalsIgnoreCase(str3);
System.out.println(result); // false

result = str3.equalsIgnoreCase(str1);
System.out.println(result); // false

starts With(String) The Java String startsWith() method checks whether


the string begins with the specified string or not.
String str = "Java Programming";

System.out.println(str.startsWith("Java")); // true
System.out.println(str.startsWith("ava")); // false

endsWith(String) The Java String endsWith() method checks whether the


string ends with the specified string or not.

String str = "Java Programming";

System.out.println(str.endsWith("mming")); // true
System.out.println(str.endsWith("Java")); // false

getBytes() The Java String getBytes() method encodes the string into a
sequence of bytes and stores it in a byte array.

String str = "Java";


byte[] byteArray;
byteArray = str.getBytes();
System.out.println(Arrays.toString(byteArray));

hashCode() A hashcode is a number (object's memory address) generated from


any object, not just strings. This number is used to store/retrieve objects
quickly in a hashtable.

String str1 = "Java";


String str2 = "Java Programming";
String str3 = "";

System.out.println(str1.hashCode()); // 2301506
System.out.println(str2.hashCode()); // 1377009627

// hash code of empty string is 0


System.out.println(str3.hashCode()); // 0

indexOf(String) : The String indexOf() method returns the index of the first
occurrence of the specified character/substring within the string.

String str1 = "Learn Java";


int result;

// getting index of character 'J'


result = str1.indexOf('J');
System.out.println(result); // 6

// the first occurrence of 'a' is returned


result = str1.indexOf('a');
System.out.println(result); // 2

lastIndexOf(String): The String lastIndexOf() method returns the index of the


last occurrence of the specified character/substring within the string.

String str1 = "Learn Java";


int result;

// getting index of character 'J'


result = str1.lastIndexOf('J');
System.out.println(result); // 6

// the last occurrence of 'a' is returned


result = str1.lastIndexOf('a');
System.out.println(result); // 9
isEmpty():The Java String isEmpty() method checks whether the string is
empty or not.

String str1 = "Java Programming";


String str2 = "";

System.out.println(str1.isEmpty()); // false
System.out.println(str2.isEmpty()); // true

replace(String, String) The Java String replace() method replaces each


matching occurrences of the old character/text in the string with the new
character/text.

String str1 = "abc cba";

// all occurrences of 'a' is replaced with 'z'


System.out.println(str1.replace('a', 'z')); // zbc cbz

// all occurences of 'L' is replaced with 'J'


System.out.println("Lava".replace('L', 'J')); // Java

// character not in the string


System.out.println("Hello".replace('4', 'J')); // Hello
replaceAll(String, String)The Java String replaceAll() method replaces each
substring that matches the regex of the string with the specified text.

String str1 = "aabbaaac";


String str2 = "Learn223Java55@";

// regex for sequence of digits


String regex = "\\d+";

// all occurrences of "aa" is replaceAll with "zz"


System.out.println(str1.replaceAll("aa", "zz")); // zzbbzzac

// replace a digit or sequence of digits with a whitespace


System.out.println(str2.replaceAll(regex, " ")); // Learn Java @

substring(int, int): The Java String substring() method extracts a substring


from the string and returns it.

String str1 = "program";


// from the first character to the end
System.out.println(str1.substring(0)); // program

// from the 4th character to the end


System.out.println(str1.substring(3)); // gram

toLowerCase() Converts a string to lower case letters

String str1 = "Learn Java";


String str2 = "Java123";

// convert to lower case letters


System.out.println(str1.toLowerCase()); // "learn java"
System.out.println(str2.toLowerCase()); // "java123"

toUpperCase() Converts a string to upper case letters


String str1 = "Learn Java";
String str2 = "Java123";

// convert to upper case letters


System.out.println(str1.toUpperCase()); // "LEARN JAVA"
System.out.println(str2.toUpperCase()); // "JAVA123"

trim() Removes whitespace from both ends


String str1 = " Learn Java Programming ";
String str2 = "Learn\nJava Programming\n\n ";

System.out.println(str1.trim());
System.out.println(str2.trim());

Abstract class
An abstract class is a class that created using abstract keyword. In other
words, a class prefixed with abstract keyword is known as an abstract class.
A class that cannot be instantiated is called abstract class
In java, an abstract class may contain abstract methods (methods without
implementation) and also non-abstract methods (methods with
implementation).
We use the following syntax to create an abstract class.
Syntax
abstract class <ClassName>
{
...
}
Key points for Java abstract class:
An abstract class is a class that contains zero or more abstract methods
An abstract can have abstract and non-abstract methods.
All the abstract methods of the abstract class should be implemented in its
subclasses.
If any abstract method is not implemented, then that subclass should be
declared as abstract.
We cannot create an object to abstract class.
But, we can create a reference of abstract class type.
We cannot declare a class as both abstract and final.

Let's look at the following example java code.


Example
import java.lang.*;
abstract class Figure
{
double dim1;
double dim2;
void initialize(double x, double y)
{
dim1 = x;
dim2 = y;
}
abstract void area();
}
class Rectangle extends Figure
{
void area()
{
System.out.println("area of a Rectangle is"+(dim1*dim2));
}
}
class Triangle extends Figure
{
void area()
{
System.out.println(" Area of a Triangle is" +(dim1*dim2)/2);
}
}
class AbstractAreas
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
r.initialize(3,4);
r.area();
Triangle t = new Triangle();
t.initialize(5,8);
t.area();
}
}
Forms of Inheritance
All objects eventually inherit from Object, which provides useful methods such
as equals and toString.
In general we want to satisfy substitutability: if B is a subclass of A, anywhere
we expect an instance of A we can use an instance of B.
Inheritance gets used for a number of purposes in typical object-oriented
programming:
specialization -- the subclass is a special case of the parent class (e.g. Frame
and CannonWorld)
specification -- the superclass just specifies which methods should be
available but doesn't give code. This is supported in java by interfaces and
abstract methods.
construction -- the superclass is just used to provide behavior, but instances
of the subclass don't really act like the superclass. Violates substitutability.
Exmample: defining Stack as a subclass of Vector. This is not clean -- better to
define Stack as having a field that holds a vector.
extension -- subclass adds new methods, and perhaps redefines inherited
ones as well.
limitation -- the subclass restricts the inherited behavior. Violates
substitutability. Example: defining Queue as a subclass of Dequeue.
combination -- multiple inheritance. Provided in part by implementing
multiple interfaces.
Inheritance is used in a variety of way and for a variety of different
purposes .
Inheritance for Specialization
Inheritance for Specification
Inheritance for Construction
Inheritance for Extension
Inheritance for Limitation
Inheritance for Combination

One or many of these forms may occur in a single case.


Forms of Inheritance (- Inheritance for Specialization -)
Most commonly used inheritance and sub classification is for specialization.
Always creates a subtype, and the principles of substitutability is explicitly
upheld.
It is the most ideal form of inheritance.
An example of subclassification for specialization is;
public class PinBallGame extends Frame {
// body of class
}
Specialization
By far the most common form of inheritance is for specialization.
Child class is a specialized form of parent class
Principle of substitutability holds
A good example is the Java hierarchy of Graphical components in the AWT:
Component
Label
Button
TextComponent
TextArea
TextField
CheckBox
ScrollBar

Forms of Inheritance (- Inheritance for Specification -)


This is another most common use of inheritance. Two different mechanisms
are provided by Java, interface and abstract, to make use of subclassification
for specification. Subtype is formed and substitutability is explicitly upheld.
Mostly, not used for refinement of its parent class, but instead is used for
definitions of the properties provided by its parent.
class FireButtonListener implements ActionListener {
// body of class
}
class B extends A {
// class A is defined as abstract specification class
}
Specification
The next most common form of inheritance involves specification. The parent
class specifies some behavior, but does not implement the behavior
Child class implements the behavior
Similar to Java interface or abstract class
When parent class does not implement actual behavior but merely defines the
behavior that will be implemented in child classes
Example, Java 1.1 Event Listeners:
ActionListener, MouseListener, and so on specify behavior, but must be
subclassed.
Forms of Inheritance (- Inheritance for Construction -)
Child class inherits most of its functionality from parent, but may change the
name or parameters of methods inherited from parent class to form its
interface.
This type of inheritance is also widely used for code reuse purposes. It
simplifies the construction of newly formed abstraction but is not a form of
subtype, and often violates substitutability.
Example is Stack class defined in Java libraries.
Construction
The parent class is used only for its behavior, the child class has no is-a
relationship to the parent.
Child modify the arguments or names of methods
An example might be subclassing the idea of a Set from an existing List class.
Child class is not a more specialized form of parent class; no substitutability

Forms of Inheritance (- Inheritance for Extension -)


Subclassification for extension occurs when a child class only adds new
behavior to the parent class and does not modify or alter any of the inherited
attributes.
Such subclasses are always subtypes, and substitutability can be used.
Example of this type of inheritance is done in the definition of the class
Properties which is an extension of the class HashTable.
Generalization or Extension
The child class generalizes or extends the parent class by providing more
functionality
In some sense, opposite of subclassing for specialization
The child doesn't change anything inherited from the parent, it simply adds
new features
Often used when we cannot modify existing base parent class
Example, ColoredWindow inheriting from Window
Add additional data fields
Override window display methods
Forms of Inheritance (- Inheritance for Limitation -)
Subclassification for limitation occurs when the behavior of the subclass is
smaller or more restrictive that the behavior of its parent class.
Like subclassification for extension, this form of inheritance occurs most
frequently when a programmer is building on a base of existing classes.
Is not a subtype, and substitutability is not proper.
Limitation
The child class limits some of the behavior of the parent class.
Example, you have an existing List data type, and you want a Stack
Inherit from List, but override the methods that allow access to elements other
than top so as to produce errors.

Forms of Inheritance (- Inheritance for Combination -)


This types of inheritance is known as multiple inheritance in Object Oriented
Programming.
Although the Java does not permit a subclass to be formed be inheritance from
more than one parent class, several approximations to the concept are
possible.
Example of this type is Hole class defined as;
class Hole extends Ball implements PinBallTarget{
// body of class
}
Combination
Two or more classes that seem to be related, but its not clear who should be
the parent and who should be the child.
Example: Mouse and TouchPad and JoyStick
Better solution, abstract out common parts to new parent class, and use
subclassing for specialization.

Summary of Forms of Inheritance


Specialization. The child class is a special case of the parent class; in other
words, the child class is a subtype of the parent class.
Specification. The parent class defines behavior that is implemented in the
child class but not in the parent class.
Construction. The child class makes use of the behavior provided by the
parent class, but is not a subtype of the parent class.
Generalization. The child class modifies or overrides some of the methods of
the parent class.
Extension. The child class adds new functionality to the parent class, but does
not change any inherited behavior.
Limitation. The child class restricts the use of some of the behavior inherited
from the parent class.
Variance. The child class and parent class are variants of each other, and the
class-subclass relationship is arbitrary.
Combination. The child class inherits features from more than one parent
class. This is multiple inheritance and will be the subject of a later chapter.

The Benefits of Inheritance


Software Reusability (among projects)
Increased Reliability (resulting from reuse and sharing of well-tested code)
Code Sharing (within a project)
Consistency of Interface (among related objects)
Software Components
Rapid Prototyping (quickly assemble from pre-existing components)
Polymorphism and Frameworks (high-level reusable components)
Information Hiding

The Costs of Inheritance


Execution Speed
Program Size
Message-Passing Overhead
Program Complexity (in overuse of inheritance)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy