UNIT1 JAVA Converted 1
UNIT1 JAVA Converted 1
UNIT - I
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.
A message for an object is a request made for execution of method for obtaining
the service.
Responsibilities:
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
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:
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:
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.
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.
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.
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.
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 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.
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.
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.
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.
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:
Here, type is one of Java’s atomic types. The identifier is the name of the
variable.
Operators:
Types of Operator in Java
Output:
addition = 120
subtraction= 80
multiplication= 2000
division= 5
modulo = 0
2) Assignment Operators
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;
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in
conditional statements and loops for evaluating a condition.
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.
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 | 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
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
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
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);
}
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;
Arrays
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.
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.
Multidimensional Array
dataType arr[];
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]);
}
}
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
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;
}
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
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.
Polymorphism:
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one
interface to be used for a general class of actions.
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
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
equals (): Java String equals () method returns true if two strings are
equal. If not, equals () returns false.
result = str1.equals(str3);
System.out.println(result); // false
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
System.out.println(str.startsWith("Java")); // true
System.out.println(str.startsWith("ava")); // false
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.
System.out.println(str1.hashCode()); // 2301506
System.out.println(str2.hashCode()); // 1377009627
indexOf(String) : The String indexOf() method returns the index of the first
occurrence of the specified character/substring within the string.
System.out.println(str1.isEmpty()); // false
System.out.println(str2.isEmpty()); // true
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.