Oop Thr Java-unit 1 (1)
Oop Thr Java-unit 1 (1)
Course Objectives:
Course Outcomes:
Demonstrate the behavior of programs involving the basic programming constructs like
control structures, constructors, string handling and garbage collection.
Demonstrate the implementation of inheritance (multilevel, hierarchical and multiple) by
using extend and implement keywords
Use multithreading concepts to develop inter process communication.
Understand the process of graphical user interface design and implementation using AWT
or swings.
Develop applets that interact abundantly with the client environment and deploy on the
server
UNIT-I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts,
coping with complexity, abstraction mechanisms. A way of viewing world – Agents,
responsibility, messages, methods, History of Java, Java buzzwords, data types, variables, scope
and lifetime of variables, arrays, operators, expressions, control statements, type conversion and
casting, simple java program, concepts of classes, objects, constructors, methods, access control,
this keyword, garbage collection, overloading methods and constructors, method binding,
inheritance, overriding and exceptions, parameter passing, recursion, nested and inner classes,
exploring string class.
Object oriented thinking and Java Basics: OOP stands for Object-Oriented
Programming. Procedural programming is about writing procedures or methods that perform
operations on the data, while object-oriented programming is about creating objects that
contain both data and methods.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
Java Standard Editions (JSE): It is used to create programs for a desktop computer.
Java Enterprise Edition (JEE): It is used to create large programs that run on the server
and manages heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices such as set-
top boxes, phone, and appliances.
Need for OOP Paradigm: Traditionally, the structured programming techniques were used
earlier. There were many problems because of the use of structured programming technique.
The structured programming made use of a top-down approach. To overcome these problems
the object-oriented programming concept was created.
The object-oriented programming makes use of bottom-up approach. It also manages the
increasing complexity. The description of an object-oriented program can be given as, a data that
controls access to code. The object-oriented programming technique builds a program using the
objects along with a set of well-defined interfaces to that object.
Whereas in OOP paradigm, the data and methods are tightly coupled to form objects. These
objects help to build structure models of the problem domain and enables to get effective
solutions. OOP uses various principles (or) concepts such as abstraction, inheritance,
encapsulation and polymorphism. With the help of abstraction, the implementation is hidden
and the functionality is exposed. Use of inheritance can eliminate redundant code in a program.
Encapsulation enables the data and methods to wrap into a single entity. Polymorphism enables
the reuse of both code and design.
Object-oriented programming paradigm methods enable us to create a set of objects that work
together to produce software that is better understandable and models their problem domains
than produced using traditional techniques.
Object orientation techniques work more efficiently than traditional techniques due to the
following reasons.
The higher level of abstraction: Top-down approach support abstraction at the
Functional level while object-oriented approach support abstraction at the object level.
The seamless transition among different software development phases: It uses the
same language for all phases, which reduces the level of complexity and redundancy
makes software development clear and robust.
Good programming practice: The subroutine and attributes of a class are held together
tightly.
Improves reusability: it supports inheritance due to which classes can be built from
each other. So only difference and enhancement between classes need to be designed and
coded. All the previous functionality remains as it is and can be used without change.
Object: Any entity that has state and behavior is known as an object. For
example:chair, pen, table, keyboard, bike etc. It can be physical and logical.
know about the internal functionality like how wheel system works, how brake
system works and how music system works etc.
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. A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
Benefits of Inheritance:
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent
code exists in two related classes, the hierarchy can usually be re-factored to move
the common code up to a mutual super class. This also tends to result in a better
organization of code and smaller, simpler compilation units.
Inheritance can also make application code more flexible to change because classes
that inherit from a common super class can be used interchangeably. If the return
Reusability: facility to use public methods of base class without rewriting the
same.
Extensibility: extending the base class logic as per business logic of the
derivedclass.
Data hiding: base class can decide to keep some data private so that it
cannot bealtered by the derived class
Abstraction mechanisms.
In object-oriented programming, abstraction is one of three central principles (along with
encapsulation and inheritance). Through the process of abstraction, a programmer hides all but
the relevant data about an object in order to reduce complexity and increase efficiency.
Suppose I wish to send flowers to a friend who lives in a city many miles away. Let
me call my friend Sally. Because of the distance, there is no possibility of my picking the
flowers and carrying them to her door myself. Nevertheless, sending her the flowers is
an easy enough task; I merely go down to my local Florist (who happens to be named
Flora), tell her the variety and quantity of flowers I wish to send and give her Sally's
address, and I can be assured the flowers will be delivered expediently and
automatically.
To solve the problem, let me call zomato (an agent in food delivery community), tell
them the variety and quantity of food and the hotel name from which I wish to
deliver the foodto my family members. Look at the following image.
Responsibilities:
In object-oriented programming, behaviors of an object described in terms of
responsibilities. In our example, my request for action indicates only the desired
outcome (food deliveredto my family). The agent (zomato) is free to use any technique
that solves my problem. By discussing a problem in terms of responsibilities increases
the level of abstraction. This enables more independence between the objects in
solving complex problems.
An Overview of Java:
Java is a computer programming language. Java was created based on C and C++.
Java uses C syntax and many of the object-oriented features are taken from C++.
Before Java was invented there were other languages like COBOL, FORTRAN, C, C++,
Small Talk, etc. These languages had few disadvantages which were corrected in
Java. Java was invented by a team of 13 employees of Sun Microsystems, Inc. which
is lead by James Gosling, in 1991. The team includes persons like Patrick Naughton,
Chris Warth, Ed Frank, and Mike Sheridan, etc. Java was developed as a part of the
Green project. Initially, it was called Oak, later it was changed to Java in 1995.
History of Java
The C language developed in 1972 by Dennis Ritchie had taken a decade to
become the most popular language.
In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language
with included OOP fundamentals and features.
A project named “Green” was initiated in December of 1990, whose aim was
to create a programming tool that could render obsolete the C and C++
programming languages.
Finally in the year of 1991 the Green Team was created a new Programming
The java team has listed the following terms as java buzz words.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple: Java programming language is very simple and easy to learn, understand, and
code. Most of the syntaxes in java follow basic programming language C and object-
oriented programming concepts are similar to C++. In a java programming language,
many complicated features like pointers, operator overloading, structures, unions, etc.
have been removed. One of the most useful features is the garbage collector it makes
java simpler.
Secure: Java is said to be more secure programming language because it does not
have pointers concept, java provides a feature "applet" which can be embedded into
a web application. The applet in java does not allow access to other parts of the
computer, which keeps away from harmful programs like viruses and unauthorized
access.
Portable: Portability is one of the core features of java which enables the java
programs to run on any computer or operating system. For example, an applet
developed using java runs on a wide variety of CPUs, operating systems, and browsers
connected to the Internet.
Robust: Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage
collector), java is a strictly typed language, it has a strong set of exception
handling mechanism,and many more.
High performance: Java provides high performance with the help of features like
JVM, interpretation, and its simplicity.
Distributed: Java programming language supports TCP/IP protocols which enable the
java to support the distributed environment of the Internet. Java also supports Remote
Method Invocation (RMI), this feature enables a program to invoke methods across a
network.
Dynamic: Java is said to be dynamic because the java byte code may be dynamically
updated on a running system and it has a dynamic memory allocation and de-
allocation (objects and garbage collector).
In java, primitive data type includes byte, short, int, long, float, double, char, and
boolean.
The following table provides more description of each primitive data type.
Let's look at the following example java program to illustrate primitive data types in
javaand their default values.
Example
public class PrimitiveDataTypes
{
byte i; short j; int k; long l; float m;
double n; char ch; boolean p;
public static void main(String[] args)
{
PrimitiveDataTypes obj = new PrimitiveDataTypes();
System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);
System.out.println("m = " + obj.m + ", n = " + obj.n);
System.out.println("ch = " + obj.ch);
System.out.println("p = " + obj.p);
}
}
OUTPUT:
D:\TKREC\Java>java PrimitiveDataTypes
i = 0, j = 0, k = 0, l = 0
m = 0.0, n = 0.0
ch =
p = false
In java, examples of non-primitive data types are String, Array, List, Queue, Stack,
Class, Interface, etc.
P.Ramesh, Assistant Professor, AIML Dept, 14
TKREC
OOP through Java UNIT-1
Example:
public class NonPrimitiveDataTypes
{
String str;
public static void main(String[] args)
{
String name = "B Tech Smart Class!";
String wish = "Hello, ";
NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();
System.out.println("str = " + obj.str); //using addition method
System.out.println(wish.concat(name));
}
}
OUTPUT:
D:\TKREC\Java>java NonPrimitiveDataTypes
str = null
Hello, B Tech Smart Class!
Syntax:
data_type variable_name; (or)
data_type variable_name_1; (or)
data_type variable_name = value; (or)
data_type variable_name_1 = value;
1. Local variables
2. Instance variables or Member variables or Global variables
3. Static variables or Class variables
4. Final variables
Local variables: The variables declared inside a method or a blocks are known as local
variables. A local variable is visible within the method in which it is declared. The local
variable is created when execution control enters into the method or block and
destroyed after the method or block execution completed.
Example:
public class LocalVariables
{
public void show()
{
int a = 10;
//static int x = 100;
System.out.println("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
System.out.println("Inside display method, b = " + b);
// trying to access variable 'a' - generates an ERROR
System.out.println("Inside display method, a = " + a);
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>java LocalVariables
Inside show method, a = 10
Inside display method, b = 20
Instance variables or member variables or global variables: The variables
declared inside a class and outside any method, constructor or blocks are known as
instance variables or member variables. These variables are visible to all the
methods of the class. The changes made to these variables by method affectsall the
methods in the class. These variables are created separate copy for every object of
that class.
Example
public class ClassVariables
{
int x = 100;
public void show()
{
System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display()
{
System.out.println("Inside display method, x = " + x);
}
public static void main(String[] args)
{
ClassVariables obj = new ClassVariables();
obj.show();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>java ClassVariables
Inside show method, x = 100
Inside display method, x = 200
Static variables or Class variables: A static variable is a variable that declared using
static keyword. The instance variables can be static variables but local variables cannot.
Static variables are initialized only once, at the start of the program execution. The
static variable only has one copy per class irrespective of how many objects we
create.
Example
public class StaticVariablesExample
{
int x, y; // Instance variables
static int z; // Static variable
StaticVariablesExample(int x, int y)
{
this.x = x;
this.y = y;
}
public void show()
{
int a; // Local variables
System.out.println("Inside show method,");
System.out.println("x = " + x + ", y = " + y + ", z = " + z);
}
public static void main(String[] args)
{
Final variables: A final variable is a variable that declared using final keyword. The
final variable isinitialized only once, and does not allow any method to change it's
value again. The variable created using final keyword acts as constant. All variables
like local,instance and static variables can be final variables.
Example
public class FinalVariableExample
{
final int a = 10;
void show()
{
System.out.println("a = " + a);
// a = 20; Error due to final variable cann't be modified
}
public static void main(String[] args)
{
FinalVariableExample obj = new FinalVariableExample();
obj.show();
}
}
OUTPUT:
D:\TKREC\Java>javac FinalVariableExample.java
FinalVariableExample.java:6: error: cannot assign a value to final variable a
a = 20; //Error due to final variable cann't be modified
1 error
D:\TKREC\Java>java FinalVariableExample
a = 10
Java Arrays
An array is a collection of similar data values with a single name. An array can also be
defined as, a special type of variable that holds multiple values of the same data type at
a time.
In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values. The index value of an array
starts with '0' and ends with 'size-1'. We use the index value to access individual
elements of an array. In java, there are two types of arrays and they are as follows.
Creating an array: In the java programming language, an array must be created using
new operator and with a specific size. The size must be an integer value but not a byte,
short, or long. We use the following syntax to create an array.
Syntax
data_type array_name[ ] = new data_type[size]; (or)
data_type[ ] array_name = new data_type[size];
Example
public class ArrayExample
{
public static void main(String[] args)
{
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
}
}
OUTPUT:
D:\TKREC\Java>java ArrayExample
Value at index 0 - 10
Length of the array - 5
In java, an array can also be initialized at the time of its declaration. When an array is
initialized at the time of its declaration, it need not specify the size of the array and
useof the new operator. Here, the size is automatically decided based on the number
of values that are initialized.
Example
public class ArrayExample
{
public static void main(String[] args)
{
short list[] = null;
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
OUTPUT:
D:\TKREC\Java>java ArrayExample1
Exception in thread "main" java.lang.NullPointerException: Cannot store to short
array because "<local1>" is null
at ArrayExample1.main(ArrayExample1.java:6)
Example
public class ArrayExample
{
public static void main(String[] args)
{
short list[] = {10, 20, 30};
list[4] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
OUTPUT:
D:\TKREC\Java>java ArrayExample2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4
out of bounds for length 3
at ArrayExample2.main(ArrayExample2.java:6)
Looping through an array: An entire array is accessed using either simple for statement
or for-each statement. Look at the following example program to display sum of all the
elements in a list.
Example
import java.util.Scanner;
public class Arrayloops
{
public static void main(String[] args)
{
int n, sum = 0;
Scanner s = new Scanner(System.in);
When we create a two-dimensional array, it created with a separate index for rows
and columns. The individual element is accessed using the respective row index
followed by the column index.
A multidimensional array can be initialized while it has created using the following
syntax.
Syntax
data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};
When an array is initialized at the time of declaration, it need not specify the size of
the array and use of the new operator. Here, the size is automatically decided based
on the number of values that are initialized.
The above statement creates a two-dimensional array of three rows and two columns.
Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java
providesa rich set of operators.
In java, operators are classified into the following four types.
1. Arithmetic Operators
2. Relational (or) Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Conditional Operators
Let's look at each operator in detail.
1. Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical
operations like addition, subtraction, multiplication, division, modulus, increment,
decrement, etc.,
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
++ Increment a++
-- Decrement a--
< Returns TRUE if the first value is smaller than 10 < 5 is FALSE
second value otherwise returns FALSE
> Returns TRUE if the first value is larger than 10 > 5 is TRUE
second value otherwise returns FALSE
<= Returns TRUE if the first value is smaller than or 10 <= 5 is FALSE
equal to second value otherwise returns FALSE
>= Returns TRUE if the first value is larger than or 10 >= 5 is TRUE
equal to second value otherwise returns FALSE
3. Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into
one condition. The following table provides information about logical operators.
& Logical AND - Returns TRUE if all conditions are false & true => false
TRUE otherwise returns FALSE
| Logical OR - Returns FALSE if all conditions are false | true => true
FALSE otherwise returns TRUE
^ Logical XOR - Returns FALSE if all conditions are true ^ true => false
same otherwise returns TRUE
&& Short-circuit AND - Similar to Logical AND (&), false & true => false
but once a decision is finalized it does not
evaluate remaining.
4. Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to
the left- hand side variable (Lvalue). The assignment operator is used in different
variants along with arithmetic operators. The following table describes all the
assignment operators in the java programming language.
+= Add both left and right-hand side values and store the result A += 10
into left-hand side variable
|= Logical OR assignment -
5. Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming
language. When we use the bitwise operators, the operations are performed based on
binary values.
The following table describes all the bitwise operators in the java programming
language.
6. Conditional Operators
The conditional operator is also called a ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first, we verify a
condition, then we perform one operation out of the two operations based on the
condition result. If the condition is TRUE the first option is performed, if the condition
is FALSE the second option is performed.
Expressions
In any programming language, if we want to perform any calculation or to frame any
condition etc., we use a set of symbols to perform the task. These set of symbols
makes an expression. In the java programming language, an expression is defined as
follows.
Operands are the values on which the operators perform the task. Here operand can
bea direct value or variable or address of memory location.
Expression Types: In the java programming language, expressions are divided into
THREE types. They are as follows.
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
Example
Postfix Expression: The expression in which the operator is used after operands is
called postfix expression. The postfix expression has the following general structure.
Example
Prefix Expression: The expression in which the operator is used before operands is
called a prefix expression. The prefix expression has the following general structure.
Example
In java, the control statements are the statements which will tell us that in
which order the instructions are getting executed. The control statements are used
to control the order of execution according to our requirements. Java provides
several control statements, and they are classified as follows.
Types of Control Statements: In java, the control statements are classified as follows.
Selection Control Statements (Decision Making Statements)
Iterative Control Statements (Looping Statements)
Jump Statements
for-each statement
Jump Statements
In java, the jump statements are used to terminate a block or take the
execution controlto the next iteration. Java provides the following jump statements.
break
continue
return
if statement in java
In java, we use if statement to test a condition and decide the execution of a block of
statements based on that condition result. if statement checks, the given condition
then decides the execution of a block of statements. If the condition is true, then the
block of statements is executed and if it is False, then the block of statements is
ignored.
Example: -
class If
{
public static void main(String args[])
{
// defining age variable
int age=40;
// checking the age
if(age>30)
{
System.out.println("Age is Greater than 30");
}
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java If
Age is Greater than 30
Example: -
public class IfElse
{
Syntax
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
}
}
Example: -
public class NestedIf
{
public static void main(String[] args)
{
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
}
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java NestedIf
You are eligible to donate blood
Syntax
if(condition_1)
{
condition_1 true-block;
}
else if(condition_2)
{
condition_2 true-block;
condition_1 false-block too;
}
Example: -
public class IfElseIf
{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
P.Ramesh, Assistant Professor, AIML Dept, 31
TKREC
OOP through Java UNIT-1
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java IfElseIf
C grade
switch statement in java
Using the switch statement, one can select only one option from more number of
options very easily. In the switch statement, we provide a value that is to be compared
with a value associated with each option. Whenever the given value matches the value
associated with an option, the execution starts from that option. In the switch
statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
Example: -
public class Switch
{
public static void main(String[] args)
{
//Specifying month number
int month=8;
String monthString="";
//Switch statement
switch(month){
//case statements within the switch block
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
default:System.out.println("Invalid Month!");
}
//Printing month of the given number
System.out.println(monthString);
}
}
OUTPUT:
D:\TKREC\Java>java Switch
8 - August
Example:
while(num <= 10)
{
System.out.println(num);
num++;
}
Example: -
public class While
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
System.out.println(i);
i++;
}
}
}
OUTPUT:
D:\TKREC\Java>java While
1
2
3
4
5
Example: -
public class DoWhile
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=5);
}
}
OUTPUT:
D:\TKREC\Java>java DoWhile
1
2
3
4
5
for statement in java: The for statement is used to execute a single statement
or a block of statements repeatedly as long as the given condition is TRUE.
Example:
for(int i = 0; i < 10; i++)
{
System.out.println("i = " + i);
}
Example: -
public class For
{
public static void main(String[] args)
{
//Code of Java for loop
for(int i=1;i<=4;i++)
{
System.out.println(i);
}
}
}
OUTPUT:
D:\TKREC\Java>java For
1
2
3
4
for-each statement in java: The Java for-each statement was introduced since Java
5.0 version. It provides an approach to traverse through an array or collection in
Java. The for-each statement also known as enhanced for statement. The for-each
statement executes the block of statements for each element of the given array or
collection.
Example:
for(int i : arrayList)
{
System.out.println("i = " + i);
}
Example: -
public class ForEach
{
public static void main(String[] args)
{
//Declaring an array
int arr[]={12,23,44,56,78};
The Java break statement 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
Example: -
public class Break
{
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:
D:\TKREC\Java>java Break
1
2
3
4
32
33
continue statement: The continue statement is used to move the execution control to
the beginning of the looping statement. When the continue statement is encountered
in a looping statement, the execution control skips the rest of the statements in the
looping block and directly jumps to the beginning of the loop. The continue statement
can be used with looping statements like while, do-while, for, and for-each.
Example: -
//inside the for loop.
public class Continue
{
public static void main(String[] args)
{
//for loop
for(int i=1;i<=6;i++)
{
if(i==3)
{
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
OUTPUT:
D:\TKREC\Java>java Continue
1
2
4
5
6
labeled break and continue statements: The java programming language does not
support goto statement, alternatively, the break and continue statements can be used
with label.
Example: -
//with label inside an inner loop to continue outer loop
public class ContinueLabel
{
return statement: In java, the return statement used to terminate a method with or
without a value. The return statement takes the execution control to the calling
function. That means the return statement transfer the execution control from called
function to the calling function by carrying a value.
Example: -
public class ReturnType
{
public int add() // without arguments
{
int x = 30;
int y = 70;
int z = x+y;
return z;
}
The two terms type casting and the type conversion are used in a program to convert one data
type to another data type. The conversion of data type is possible only by the compiler when they
are compatible with each other.
Type conversion
If a data type is automatically converted into another data type at compile time is known as type
conversion. The conversion is performed by the compiler if both data types are compatible with
each other
Example
Converting an int into long and long into float
int i=100;
long l=I;
float f=l;
i value is 100
l value is 100
f value is 100.0
Ex: byte con be converted to int type easily without losing data
byte-->short-->int-->long-->float-->double
Ex: conversion float to int type will not convert implicitly and require some explicit casting
double-->float-->long-->int-->short -->byte
Note: while doing explicit type casting, we may lose some amount of actual data.
Example
Converting a double into long and long into int
double d=100.0;
long l=(long)d;
int i=(int)l;
d value is 100.0
l value is 100
i value is 100
Note: Type conversion done by the compiler and type casting done by the user
Example
class TypeConversion
{
public static void main(String[] args)
{
int x = 10;
float y;
//automatically converts the integer type into float type
y = x;
System.out.println("After conversion, float value "+ y);
}
}
OUTPUT:
D:\TKREC\Java >java TypeConversion
After conversion, float value 10.0
Example
class TypeCasting
{
public static void main(String[] args)
{
double d=10.05;
long l= (long)d;
int i=(int)l;
System.out.println("The value of d is:"+d);
System.out.println("After conversion, l is:"+l);
System.out.println("After conversion, i is:"+i);
}
}
OUTPUT:
D:\TKREC\Java >java TypeCasting
The value of d is :10.05
After conversion, l is: 10
After conversion, i is: 10
class Example
{
Concepts of Classes:
Java is an object-oriented programming language, so everything in java program
must be based on the object concept. In a java programming language, the class
concept definesthe skeleton of an object.
The java class is a template of an object. The class defines the blueprint of an
object. Every class in java forms a new data type. Once a class got created, we can
generate as many objects as we want. Every class defines the properties and
behaviors of an object. All the objects of a class have the same properties and
behaviors that were defined in theclass.
Look at the following picture to understand the class and object concept.
Creating a Class: In java, we use the keyword class to create a class. A class in java
contains properties as variables and behaviors as methods. Following is the syntax of
class in the java.
Syntax
class <ClassName>
{
data members declaration;
methods defination;
}
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the
classis said to be instantiated. All the objects that are created using a single class have
the same properties and methods. But the value of properties is different for every
object. Following is the syntax of class in the java.
Example: -
//Defining a Class.
class DefiningClass
{
//defining fields
int id;//field or data member or instance variable
String name;
OUTPUT:
D:\TKREC\Java>java DefiningClass
0
Null
Example: -
class CreatingObject
{
int id;
String name;
}
class Intialization
{
public static void main(String args[])
{
CreatingObject obj=new CreatingObject();
obj.id=546;
obj.name="Siri";
System.out.println(obj.id+" \n "+obj.name); //printing members with a white space
}
}
OUTPUT:
D:\TKREC\Java>java Intialization
546
Siri
Methods:
A method is a block of statements under a name that gets executes only when it is
called. Every method is used to perform a specific task. The major advantage of
methods is code re-usability (define the code once, and use it many times).
Creating a method: A method is created inside the class and it may be created with
anyaccess specifier. However, specifying access specifier is optional.
Syntax
class <ClassName>
{
<accessSpecifier> <returnType> <methodName>( parameters )
{
block of statements;
}
}
Calling a method: In java, a method call precedes with the object name of the class
to which it belongs and a dot operator. It may call directly if the method defined with
the static modifier. Every method call must be made, as to the method name with
parentheses (), and it must terminate with a semicolon.
{
public static void main (String args[])
{
A constructor is a special method of a class that has the same name as the class
name.
The constructor gets executes automatically on object creation. It does not
require the explicit method call.
A constructor may have parameters and access specifies too.
In java, if you do not provide any constructor the compiler automatically
creates a default constructor.
Example
class Demo
{
String name;
// constructor
Demo()
{
System.out.println("Constructor is called");
name="Java";
}
public static void main(String[] args)
{
// Constructor is invoked while creating on object of the Demo class
Demo obj = new Demo();
System.out.println("The Name is: " + obj.name);
}
}
OUTPUT:
D:\TKREC\Java>java Demo
Constructor is called
The Name is: Java
Types of Constructor
In Java, constructors can be divided into 3 types:
No-Arg Constructor
Parameterized Constructor
Default Constructor
No-Arg Constructor: Similar to methods, a Java constructor may or may not have any
parameters (arguments). If a constructor does not accept any parameters, it is known as a no-
argument constructor
Example
class Test
{
int i;
// constructor with no parameter
Test()
{
i = 10;
System.out.println("Constructor is called");
}
public static void main(String[] args)
{
// calling the constructor without any parameter
Test obj = new Test();
System.out.println("Value of i is: " + obj.i);
}
OUTPUT:
D:\TKREC\Java>java Test
Constructor is called
Value of i is: 10
Parameterized Constructor: A Java constructor can also accept one or more parameters.
Such constructors are known as parameterized constructors (constructor with
parameters).
Example
class Main
{
String languages;
// constructor accepting single value
Main(String lang)
{
languages = lang;
System.out.println(languages + " Programming Language");
}
Default Constructor: If we do not create any constructor, the Java compiler automatically
create a no-arg constructor during the execution of the program. This constructor is
called default constructor.
Example
class Test
{
int a;
boolean b;
public static void main(String[] args)
{
// A default constructor is called
Access control
Access Control in Java refers to the mechanism used to restrict or allow access to
certain parts of a Java program, such as classes, methods, and variables
In Java, the access specifiers (also known as access modifiers) used to restrict the
scope or accessibility (visibility) of a class, constructor, variable, method or data
member of class and interface.
Default: If we do not explicitly specify any access modifier for classes, methods,
variables, etc, then by default the default access modifier is considered.
Example
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
OUTPUT:
D:\TKREC\Java>javac B.java
B.java:3: error: package pack does not exist
import pack.*;
^
B.java:8: error: cannot find symbol
A obj = new A();//Compile Time Error
^
symbol: class A
location: class B
Private: When variables and methods are declared private, they cannot be accessed
outside of the class
Example
class Data
{
// private variable
private String name;
}
public class Main
{
public static void main(String[] main)
{
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "Java";
}
}
OUTPUT:
D:\TKREC\Java>javac Main.java
Main.java:16: error: name has private access in Data
d.name = "Java";
^
1 error
Protected: When methods and data members are declared protected, we can access
them within the same package as well as from subclasses.
Example
class Student
{
// protected method
protected void display()
{
System.out.println("I am a Student");
}
}
class siri extends Student
{
public static void main(String[] args)
{
// create an object of Dog class
siri s = new siri();
// access protected method
s.display();
}
}
OUTPUT:
D:\TKREC\Java>java siri
I am a Student
Here the protected method display() inside the Student class. Since protected methods can be
accessed from the child classes, we are able to access the method of Student class from the siri
class.
Public: When methods, variables, classes, and so on are declared public, then we can
access them from anywhere. The public access modifier has no scope restriction.
Example
class Student
{
// public variable
public int id;
// public method
public void display()
{
System.out.println("I am a Student.");
System.out.println(" My ID is:" +id);
}
}
// Main class
public class Main
{
public static void main( String[] args )
{
// accessing the public class
Student s = new Student();
In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data
members and methods.
Example
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData()
{
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass
{
void accessData()
{
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}
}
OUTPUT:
AccessModifiersExample.java:24: error: d has private access in ParentClass
System.out.println("d = " + d); // private member can't be accessed
^
1 error
D:\TKREC\Java>java AccessModifiersExample
Inside ParentClass
a = 10
b = 20
c = 30
d = 40
Inside ChildClass
a = 10
b = 20
c = 30
This keyword
In Java, this keyword is used to refer to the current object inside a method or a constructor
The most common use of this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or
constructor parameter).
Example
class Student
{
// instance variables
int rollno;
String name;
Student(int rollno,String name) // formal parameters
{
this.rollno=rollno;
this.name=name;
}
void display()
{
System.out.println(rollno+" "+name);
}
}
class Test
{
public static void main(String args[])
{
Student s1=new Student(111,"siri");
Student s2=new Student(112,"sai");
s1.display();
s2.display();
}
}
OUTPUT:
D:\TKREC\Java>java Test
111 siri
112 sai
Example
class Student
{
// instance variables
int rollno;
String name;
Student(int r,String n) // formal parameters
{
rollno=r;
name=n;
}
void display()
{
System.out.println(rollno+" "+name);
}
}
class Test
{
public static void main(String args[])
{
Student s1=new Student(111,"xyz");
Student s2=new Student(112,"abc");
s1.display();
s2.display();
}
}
OUTPUT:
D:\TKREC\Java>java Test
111 xyz
P.Ramesh, Assistant Professor, AIML Dept, 56
TKREC
OOP through Java UNIT-1
112 abc
Garbage collection
Garbage collection in Java is the automated process of deleting code that's no longer needed or
used. This automatically frees up memory space and ideally makes coding Java apps easier for
developers. Java applications are compiled into bytecode that may be executed by a JVM.
Overloading methods
In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading.
Note: The return types of the above methods are not the same. It is because method overloading
is not associated with return types. Overloaded methods may have the same or different return
types, but they must differ in parameters.
Example
class Demo
{
void test()
{
System.out.println("No Parameter");
}
// Overload test for one integer parameter
void test(int a)
{
System.out.println("a is:"+a);
}
// Overload test for one String parameter
void test(String s)
{
System.out.println("s is:"+s);
}
// Overload test for one integer parameter
void test(int a, int b)
{
System.out.println("a and b is:"+a+ " "+b);
}
}
class Overload
{
Example
class Demo
{
void test()
{
System.out.println("No Parameter");
}
// Overload test for one integer parameter
void test(int a, int b)
{
System.out.println("a and b is:"+a+ " "+b);
}
// Overload test for a double parameter
void test(double d)
{
System.out.println("Inside test(double)d:"+d);
}
}
class Overload
{
public static void main(String[] args)
{
Demo d=new Demo();
int i=40;
d.test();
d.test(10,20);
d.test(i);// this will invoke test(double)
d.test(12.3);//this will invoke test(double)
}
P.Ramesh, Assistant Professor, AIML Dept, 58
TKREC
OOP through Java UNIT-1
}
OUTPUT:
D:\TKREC\Java>java Overload
No Parameter
a and b is :10 20
Inside test(double)d:40.0
Inside test(double)d:12.3
Overloading constructors
Similar to Java method overloading, we can also create two or more constructors with different
parameters. This is called constructors overloading.
Example1
class ConDemo
{
int value1;
int value2;
ConDemo()
{
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}
// constructor with a single parameter
ConDemo(int a)
{
value1 = a;
System.out.println("Inside 2nd Constructor");
}
// constructor with two parameters
ConDemo(int a, int b)
{
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display()
{
System.out.println("Value1 "+value1);
System.out.println("Value2 "+value2);
}
public static void main(String args[])
{
// call constructor with no parameter
ConDemo d1 = new ConDemo();
d1.display();
// call constructor with single parameter
Example2
/* Here, Box defines three constructors to initialize the dimensions of a box various ways. */
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
Method binding
In java, binding is the process of linking a method call to its corresponding method
implementation. Binding decides which method implementation is classed when a method is
called. Binding can happen either at runtime or at compile time
Static Binding: When type of the object is determined at compiled time (by the compiler), it is
known as static binding.
static binding use type of the class and fields
Overloading is an example of static binding
private, final and static methods and variables uses static binding
Example
class Student
{
private void show()
{
P.Ramesh, Assistant Professor, AIML Dept, 61
TKREC
OOP through Java UNIT-1
System.out.println("Studying...");
}
public static void main(String args[])
{
StudentStatic s=new StudentStatic();
s.show();
}
}
OUTPUT:
D:\TKREC\Java>java Student
Studying...
Dynamic Binding: When type of the object is determined at run-time, it is known as dynamic
binding.
Dynamic binding uses object to resolve binding
Method overriding is the example of Dynamic binding
Object and Virtual methods used in dynamic binding
Example
class Teacher
{
void show()
{
System.out.println("Teaching...");
}
}
class Student extends Teacher
{
void show()
{
System.out.println("Studying...");
}
public static void main(String args[])
{
Teacher t=new Student();
t.show();
}
}
OUTPUT:
D:\TKREC\Java>java Student
Studying...
Inheritance
The inheritance is a very useful and powerful concept of object-oriented programming.
In java, using the inheritance concept, we can use the existing features of one class in
another class. The inheritance provides a great advantage called code re-usability.
Withthe help of code re-usability, the commonly used code in an application need not be
written again and again.
Example:
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java
Programmer salary is:40000.0
Bonus of Programmer is:10000
Overriding
The method overriding is the process of re-defining a method in a child class that is
already defined in the parent class.
If the same method is defined in both the superclass and the subclass, then the method
of the subclass class overrides the method of the superclass. This is known as method
overriding.
In the case of the method overriding, the method binding happens at run time. The
method binding which happens at run time is known as late binding. So, the method
overriding follows late binding.
The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
Example
class A
{
public void displayInfo()
{
System.out.println(" This is class A method ");
}
}
class B extends A
{
@Override
public void displayInfo()
{
Exceptions
An exception is an unexpected event that occurs during program execution. It disrupts the normal
flow of the program's instructions
We have 3 types of exceptions
Checked exceptions (Compile Time)
Unchecked exceptions (Run time)
Error
Parameter passing
Parameter passing in Java refers to the mechanism of transferring data between methods or
functions.
Java supports two types of parameters passing techniques
Call-by-value
Call-by-reference.
Types of Parameters
Formal Parameters: A variable and its corresponding data type are referred to as
formal parameters when they exist in the definition or prototype of a function or
method
Example
void add(int a, int b)
{
---
P.Ramesh, Assistant Professor, AIML Dept, 64
TKREC
OOP through Java UNIT-1
---
}
Actual Parameters: The value or expression that corresponds to a formal parameter and is
supplied to a function or method during a function or method call is referred to as an actual
parameter is also known as an argument.
Example
add(10);
Call by value: In Call-by-value the copy of the value of the actual parameter is
passed to the formal parameter of the method. Any of the modifications made to the
formal parameter within the method do not affect the actual parameter.
In Java, when you pass a primitive type to a method, it is passed by value. Thus, what
occurs to the parameter that receives the argument has no effect outside the method.
For example, consider the following program:
Example
// Primitive types are passed by value.
class Test
{
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}
OUTPUT:
D:\TKREC\Java>java CallByValue
a and b before call: 15 20
a and b before call: 15 20
As you can see, the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10. When you pass an object to a
method, the situation changes dramatically, because objects are passed by what is effectively
call-by-reference
When you pass this reference to a method, the parameter that receives it will refer to the same
object as that referred to by the argument. This effectively means that objects are passed to
methods by use of call-by-reference. Changes to the object inside the method do affect the object
used as an argument. For example, consider the following program:
Example
// Objects are passed by reference.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("a and b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("a and b after call: " +ob.a + " " + ob.b);
}
}
OUTPUT:
D:\TKREC\Java>java CallByRef
a and b before call: 15 20
a and b before call: 30 10
As you can see, in this case, the actions inside meth( ) have affected the object used as an
argument. As a point of interest, when an object reference is passed to a method, the reference
itself is passed by use of call-by-value.
Note: When a primitive type is passed to a method, it is done by use of call-by-value. Objects
are implicitly passed by use of call-by-reference.
Recursion
Java supports recursion. Recursion is the process of defining something in terms of itself. As it
relates to Java programming, recursion is the attribute that allows a method to call itself. A
method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The factorial of a
number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 ×
2 × 3, or 6. Here is how a factorial can be computed by use of a recursive method:
Example
// A simple example of recursion.
class Factorial
{
// this is a recursive method
int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
OUTPUT:
D:\TKREC\Java>java Recursion
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
If you are unfamiliar with recursive methods, then the operation of fact( ) may seem a bit
confusing. Here is how it works. When fact( ) is called with an argument of 1, the function
returns 1; otherwise, it returns the product of fact(n–1)*n. To evaluate this expression, fact( ) is
called with n–1. This process repeats until n equals 1 and the calls to the method begin
returning.
Example
class A
{
----
----
class B
{
---
---
}
}
Thus, if class B is defined within class A, then B does not exist independently of A. A nested class
has access to the members, including private members, of the class in which it is nested.
However, the enclosing class does not have access to the members of the nested class.
Example
class Outer
{
// static nested class
static class Inner
{
int a = 1;
int b = 2;
int getTotal()
{
return a + b;
}
}
}
public class StaticNested
{
public static void main(String[] args)
{
// create an object of the static nested class using the name of the outer class
Outer.Inner obj = new Outer.Inner();
System.out.println("Total Number is: " + obj.getTotal());
}
}
OUTPUT:
D:\TKREC\Java>java Recursion
Total Number is: 3
Non-Static Nested Class: A non-static nested class is a class within another class. It has access to
members of the enclosing class (outer class). It is commonly known as inner class. Since the inner
class exists within the outer class, you must instantiate the outer class first, in order to instantiate
the inner class.
An inner class is a non-static nested class. It has access to all of the variables and methods of its
outer class and may refer to them directly in the same way that other non-static members of the
outer class do.
The following program illustrates how to define and use an inner class. The class named
Outer has one instance variable named x, one instance method named test( ), and
defines one inner class called Inner.
Example
// Demonstrate an inner class.
class Outer
{
int x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner
{
void display()
{
System.out.println("Display x is " + x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer o = new Outer();
o.test();
}
}
OUTPUT:
D:\TKREC\Java>java Recursion
The string created using a character array cannot be extended. It does not allow to
append more characters after its definition, but it can be modified.
The String class defined in the package java.lang package. String is probably the most
commonly used class in Java’s class library
Java defines one operator for String objects: +. It is used to concatenate two strings.
For example, this statement
String myString = "I" + " like " + "Java.";
results in myString containing “I like Java.”
Example
// Demonstrating Strings.
class StringDemo
{
public static void main(String args[])
{
String str1 = "First String";
String str2 = "Second String";
String str3 = str1 + " and " + str2;
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}
OUTPUT:
D:\TKREC\Java>java StringDemo
First String
Second String
First String and Second String
The String class contains several methods that you can use. Here are a few. You can
test two strings for equality by using equals( ). You can obtain the length of a string
by calling the length( ) method. You can obtain the character at a specified index
within a string by calling charAt( ).
Example
// Demonstrating some String methods.
class StringDemo2
{
public static void main(String args[])
{
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of str1: " + str1.length());
System.out.println("Char at index 3 in str1: " + str1.charAt(3));
if(str1.equals(str2))
System.out.println("str1 == str2");
else
System.out.println("str1! = str2");
if(strOb1.equals(str3))
System.out.println("str1 == str3");
else
System.out.println("str1! = str3");
}
}
OUTPUT:
D:\TKREC\Java>java StringDemo2
Length of str1: 12
Char at index 3 in str1: s
str1! = str2
str1 == str3
Example
public class JavaStringMethods
{
public static void main(String[] args)
{
String title = "Java Tutorials";
String siteName = "JavaProgram.com";
OUTPUT:
D:\TKREC\Java\UNIT-I>java JavaStringMethods
Index of 'T': 5
Last index of 'a': 11
Empty: false
Ends with '.com': true
Equals: false
Sub-string: am.co
Upper case: JAVAPROGRAM.COM
Of course, you can have arrays of strings, just like you can have arrays of any other type
of object.
Example:
// Demonstrate String arrays.
class StringDemo3
{
public static void main(String args[])
{
String str[] = { "one", "two", "three" };
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " + str[i]);
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java StringDemo3
str[0]: one
str[1]: two
str[2]: three