Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Module 1

Uploaded by

jothi1083
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Module 1

Uploaded by

jothi1083
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Object Oriented Programming Using

Java

course code: 22MCA22


Module-1
OOPS CONCEPTS AND JAVA PROGRAMMING

OOP : OOP is a language which uses object and


classes in programming.

Ex : C++, Java, JavaScript, python, c#, VB.NET, PHP,


Ruby, etc.
OOP Concepts
Classes and objects :
Classes: In object-oriented programming, a class is a
template definition of the methods and variables in a particular
kind of object.
A class is a group of objects that share common properties and
behavior.
Class consists of variables and methods which are common to
all the objects.
Ex: Person, car, box etc.
Objects
An object is created from a class. An object is called an
instance of a class.
For example, suppose Bicycle is a class then Mountain
Bicycle, Sports Bicycle, Touring Bicycle, etc can be
considered as objects of the class.
Data Abstraction : Data abstraction is the process of hiding
certain details and showing only essential information to the
user.
Ex: A car is viewed as a car rather than its individual
components.
Encapsulation
Binding (or wrapping) code and data together into a
single unit are known as encapsulation.
A java class is the example of encapsulation. Java
bean is the fully encapsulated class because all the data
members are private here.

Inheritance :
The process by which object of one class gets the
properties of another class.
Benefits of inheritance
 Indented tohelp REUSE the existing code with little or no
modification .
 Easy to implement real word models.
 Inheritance can save time and effort as the main code need
not be written again.
 Inheritance provides a clear model structure which is easy
to understand.
 An inheritance leads to less development and maintenance
costs.
Polymorphism
Polymorphism refers to the ability of a class to
provide different implementations of a method,
depending on the type of object that is passed to the
method. (Taking more than one form ) Java allows
us to perform the same action in many different
ways.
Ex: Method overriding.
Procedural and OOP paradigm
Procedural Oriented Programming Object-Oriented Programming

1. In procedural programming, the program 1.In object-oriented programming, the


is divided into small parts called functions program is divided into small parts
called objects.
2. Procedural programming follows a top- 2.Object-oriented programming follows
down approach. a bottom-up approach.
3. There is no access specifier in procedural 3. OOP has access specifiers like private,
programming. public, protected, etc.
4. Adding new data and functions is not 4. Adding new data and function is easy.
easy.
5. It does not provides data hiding, so less 5. OOP provides data hiding so it is more
secure. secure.
6. In procedural programming, 6. Overloading is possible in object-
overloading is not possible. oriented programming.

7. In procedural programming, 7. In object-oriented programming,


there is no concept of data hiding the concept of data hiding and
and inheritance. inheritance is used.

8. Procedural programming is used 8. Object-oriented programming is


for designing medium-sized used for designing large and
programs. complex programs.

9. Code reusability absent in 9. Code reusability present in


procedural programming, object-oriented programming.

10. Examples: C, FORTRAN, Pascal, 10. Examples: C++, Java, Python,


Basic, etc. C#, etc.
Java Programming
History of java
 Java was developed in the early 1990s by James Gosling as an
object-oriented programming language. Over the years, the
language has been the foundation of millions of applications
across many platforms, such as Windows, Macintosh, UNIX,
Android-based handheld devices, Embedded Systems, and
corporate solutions.
 The language, initially called 'Oak' after an oak tree that stood
outside Gosling's office, also went by the name 'Green' and
ended up later being renamed as Java, from a list of random
words.
Java comments
 Comments in Java are the statements that are not
executed by the compiler and interpreter. It can be used
to provide information or explanation about the variable,
method, class or any statement. It can also be used to
hide program code for a specific time.
 Single-line comments start with two forward slashes ( // ).
Any text between // and the end of the line is ignored by
Java (will not be executed).
 Multi-line comments start with /* and ends with */ . Any text
between /* and */ will be ignored by Java.
Java datatypes

 Data types specify the different sizes and values that can
be stored in the variable.
There are two types of data types in Java:
 Primitive data types: The primitive data types include
Boolean, char, byte, short, int, long, float and double.
 Non-primitive data types: The non-primitive data types
include classes, interfaces and arrays.
Datatype Size
boolean 1 bite

char 2 byte

byte 1 byte

short 2 byte

Int 4 byte

Long 8 byte

Float 4 byte

Double 8 byte
Boolean : The Boolean data type is used to store only two
possible values: true and false. This data type is used for
simple flags that track true/false conditions.
Ex: boolean one=false

Byte datatype: The byte data type is an example of primitive


data type. It is an 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.
Ex: byte a=20

Short datatype : The short data type is a 16-bit signed two's


complement integer. Its value-range lies between -32,768 to 32,767
(inclusive). Its minimum value is -32,768 and maximum value is
32,767. Its default value is 0.
Ex: short s=300
Int datatype: The int data type is a 32-bit signed two's complement
integer. Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its default value is 0.
Ex: int a=2500

Long datatype: The long data type is a 64-bit two's complement integer. Its
value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its default value is 0.
Ex: long l=1000000

Flot datatype: The float data type is a single-precision 32-bit IEEE 754
floating point. Its value range is unlimited. It is recommended to use a float
(instead of double) if you need to save memory in large arrays of floating
point numbers. Its default value is 0.0F.
Ex: float f1 = 234.5f
Java variable
A variable is a container which holds the value
while the Java program is executed. A variable is
assigned with a data type.
A variable is the name of a reserved area allocated
in memory. In other words, it is a name of the
memory location.

Declaration of variable
Syntax: datatype variablename;
Ex: int a,b,c;
Types of variable

1. Local variable
2. Class variable (static)
3. Instance variable
1.Local Variable: A variable declared inside the
body of the method is called local variable. You can use
this variable only within that method.

Ex: void add()


{
int a ;
int x,y,z;
}
void sum()
{
int empno;
}
2.Class variables
Class variables also known as static variables
are declared with the static keyword in a class, but
outside a method, constructor or a block. There would
only be one copy of each class variable per class,
regardless of how many objects are created from it.
3.Instance Variable: declared in a class outside
of any method, constructor or block. As instance
variables are declared in a class, these variables are
created when an object of the class is created and
destroyed when the object is destroyed.
Ex: class emp
{
int empno;
double salary;
}
emp e1,e2,e3;
Scope and life time of variable
The general scope of a class variable is throughout
the class and the lifetime of a class variable is until the
end of the program or as long as the class is loaded in
memory.

Variable Scope Lifetime


Local variable With the block which is defined Until the control leaves the
block in which it is declared.
Instance variable Throughout the class except in static Until the object is available in
method memory
Class variables All through the class Until end of the program
Operators

Operator in java is a symbol that is used to


perform operation.

Examples: +,-,*,/,++,--etc
Types of Operators
Arithmetic Operators.
Unary Operators.
Assignment Operators.
Relational Operators.
Logical Operators.
Ternary Operators
Bitwise Operators.
Shift Operators.
Operator hierarchy

The Priority or Precedence is the order in which the


operators are to be performed is called the Hierarchy
of operators. The associativity specifies the operator's
direction to be evaluated, it may be left to right or
right to left.
Expression

An expression is a construct made up of


variables, operators, and method invocations,
which are constructed according to the
syntax of the language, that evaluates to a
single value.

Ex: s=a+b/c
Evaluation of Expression

Evaluating an expression typically


produces a new value, which can be
stored in a variable, used to make a
decision, and so on.

3+4*4+5*(4+3)-1
Type conversion and casting
Within an expression, It is possible to mix
two or more different types of data as long as
they are compatible with each other.

For example, we can mix short and long with


in an expression because they both are
numeric type.
All char, byte and short values are
promoted to int.
If one operand is of long, the whole
expression is promoted to long.
If one operand is float, the entire expression
is promoted to float.
If any operand is double, the result is
double.
class Example
{
public static void main(String args[])
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Enumerated datatype
An enum type is a special data type that enables
for a variable to be a set of predefined constants. The
variable must be equal to one of the values that have
been predefined for it.

The value() method return an array containing all


the values of the enum.
class Example
{
public enum direction { north, south, east, west}
public static void main(String args[])
{
for (direction d : direction.values())
{
System.out.println(d);
}
}
}
Control statements in Java
Java compiler executes the code from top
to bottom. The statements in the code are
executed according to the order in which
they appear. However, Java provides
statements that can be used to control the
flow of Java code. Such statements are
called control flow statements. It is one of the
fundamental features of Java, which
provides a smooth flow of program.
1.Decision Making statements
1.if statements
2.switch statement
2.Loop statements
1. do while loop
2. while loop
3. for loop
4.for-each loop
3.Jump statements
1.break statement
2.continue statement
If Statement:
In Java, the "if" statement is used to evaluate a
condition. The control of the program is diverted
depending upon the specific condition. The condition
of the If statement gives a Boolean value, either true
or false. In Java, there are four types of if-statements
given below.
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
Simple if statement:
It is the most basic statement among all control flow
statements in Java. It evaluates a Boolean expression and
enables the program to enter a block of code if the
expression evaluates to true.

Syntax
if(condition)
{
statement 1; //executes when condition is true
}
Ex :
if(5>2)
{
System.out.println(“5 is greater “);
}
if else statement

Syntax : if(test condition)


{
true block statement
}
else
{
false block statement
}
else..if ladder:
Syntax:
if (condition)
statement 1;
else if (condition)
statement 2;
else
statement;
if(condition)
{
code to be executed
if(condition)
{

}
Switch statement

Switch statement executes one statement


from multiple conditions. It is like if-else-if
ladder statement. The switch statement works
with byte, short, int, long, enum types, String
and some wrapper types like Byte, Short, Int,
and Long.
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Looping Statements

Looping in programming languages is a


feature which facilitates the execution of a set
of instructions/functions repeatedly while some
condition evaluates to true. Java provides
three ways for executing the loops.
Looping statements

1. while loop
2. do .. While loop
3. for loop
1. While loop
A while loop is a control flow statement that allows
code to be executed repeatedly based on a given Boolean
condition. The while loop can be thought of as a repeating
if statement.

Syn: while(condition)
{
statements;
}
public class Example
{
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Do…while loop
The Java do-while loop is used to iterate a part of the
program repeatedly, until the specified condition is true. If
the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use a
do-while loop.
Syn:do
{
statements;
}while(condition);
For loop
When you know exactly how many times you want to loop
through a block of code, use the for loop instead of a while loop:
Syn: for(statement1;statement2;statement3)
{
}
Statement 1 is executed (one time) before the execution of the
code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has
been executed.
Ex:
for(int i=0;i<5;i++)
{
System.out.println(i);
}
Jump Statements
Jumping statements are control statements that transfer
execution control from one point to another point in the
program. There are two Jump statements that are provided in
the Java programming language:

1.Break statement.
2.Continue statement.
Break statement
In java the break statement is used to terminate the
execution of the nearest looping statement or switch
statement. The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.

Syntax: break;
or
break label;

where label is the name that identifies a statement or block


of code.
class Exbreak
{ }
public static void main(String args[]) System.out.println(“After block
{ three”);
int i; }
for(i=1;i<4;i++) System.out.println(“After block two”);
{ }
one:{ System.out.println(“After block one “);
two:{ }
three:{ System.out.println(“After for “);
System.out.println(“i is “+i); }
if(i==1) break one; }
if(i==2) break two;
if(i==3) break three;
Continue Statements
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.
Syntax: continue;
or
continue label;
Class ExConti
{
public static void main(String args[])
{
outerloop:
for(int i=1;i<10;i++)
{
System.out.println(“Outer loop pass” );
for(int j=1;j<10;j++)
{
if(j==5)
continue outerloop;
System.out.prinln(j);
}}}
}
Array
Array in java is a group of like-typed variables
referred to by a common name.
In Java all arrays are dynamically allocated.
Arrays are stored in contiguous memory
The variables in the array are ordered, and each has an
index beginning with 0.
Advantages
1. Code Optimization: It makes the code optimized,
we can retrieve or sort the data efficiently.
2. Random access: We can get any data located at an
index position.
Types of arrays :

1.One-dimensional Array: Also known as a linear array,


the elements are stored in a single row.
2.Two-dimensional Array: Two-dimensional arrays
store the data in rows and columns.
3.Multi-dimensional Array: An array consist of more
than two dimension.
One dimensional array
One dimensional array is a list of related variables.

Declaration syntax

type [] array-name=new type[size];


or
type [] array-name;
array-name=new type[size];
Two-dimensional Array

Simplest form of multidimensional array is two-


dimensional array. Two dimensional array can be used to
create a table. An individual item of data is accessed by
specifying its row and column position.

To declare two dimensional array we must specify the


size of both dimension.
Declaration syntax
type [][] array-name=new type[size][size];
or
type [][] array-name;
array-name=new type[size][size];

Ex: int [] [] table=new int[2][3];


Multi-dimensional Array
Java allows arrays with more than two dimensional.

Syntax :
type[] []….[]name=new type[size1][size2]…[sizeN];

Ex:
int [] [] [] mul=new int [4] [5] [2];
Console input and output

The Java Console class is be used to get input from


console. It provides methods to read texts and
passwords.

If you read password using Console class, it will


not be displayed to the user.
import java.io.Console;
class Test
{
public static void main(String args[])
{
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
import java.io.Console;
class Test
{
public static void main(String args[])
{
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);
System.out.println("Password is: "+pass);
}
}
Constructor
A constructor in Java is a special method that is
used to initialize objects. The constructor is called
when an object of a class is created. A contractor
initializes an object when it is created. It has the same
name as its class and is syntactically similar to a
method.
class MyClass
{
int x;
MyClass()
{
x=10;
}
}
class test
{
public static void main(String args[])
{
MyClass c1=new MyClass();
MyClass c2=new MyClass();
}
}
Types of Constructors in Java

Now is the correct time to discuss the types of the


constructor, so primarily there are three types of
constructors in Java are mentioned below:
1.Default Constructor
2.Parameterized Constructor
3.Copy Constructor
Method
A method is a block of code which only runs when it is
called. You can pass data, known as parameters, into a
method. Methods are used to perform certain actions, and
they are also known as functions.

Create A Method: A method must be declared within a


class. It is defined with the name of the method, followed
by parentheses ().
Static fields and methods

The static keyword in Java is used for memory


management mainly. We can apply static keyword
with variables, methods, blocks. The static keyword
belongs to the class than an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block

The static variable gets memory only once in


the class area at the time of class loading.
class Counter
{
static int count=0;
Counter()
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Java static method
If you apply static keyword with any method, it is
known as static method.
A static method belongs to the class rather than the
object of a class.
A static method can be invoked without the need for
creating an instance of a class.
A static method can access static data member and can
change the value of it.
class Calculate
{
static int cube(static int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
Java static block

Is used to initialize the static data member.


It is executed before the main method at the
time of class loading.
Ex: class A2
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Access control

Access modifiers are keywords that can be used to


control the visibility of fields, methods, and constructors
in a class.
1. Private: We can access the private modifier only
within the same class and not from outside the class.

2. Default: We can access the default modifier only


within the same package and not from outside the
package. And also, if we do not specify any access
modifier it will automatically consider it as default.
3. Protected: We can access the protected modifier
within the same package and also from outside the
package with the help of the child class. If we do not
make the child class, we cannot access it from outside the
package. So inheritance is a must for accessing it from
outside the package.
4. Public: We can access the public modifier from
anywhere. We can access public modifiers from within
the class as well as from outside the class and also within
the package and outside the package.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);
obj.msg();
}
}
class A
{
private A()
{}
void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
}
}
this reference
 this can be used to current class instance variable
 this can be used to invoke current class method
 this can be used to current class constructor
 this can be used to pass arguments for method
 this can be used to pass arguments for constructor
call
 this can be used to return current class instance
from class
class Student
{ int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Method overloading
If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same


name of the methods increases the readability of
the program.
Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type
class Adder
{
static int add(int a,int b) {return a+b;}
static int add(int a,int b,int c) {return a+b+c;}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
class Adder
{
static int add(int a, int b) {return a+b;}
static double add(double a, double b) {return a+b;}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Constructor overloading
The constructor overloading can be defined as the
concept of having more than one constructor with different
parameters so that every constructor can perform a
different task.
public class Student {
int id;
String name;
Student()
{
System.out.println("this a default constructor");
}
Student(int i, String n)
{
id = i;
name = n;
}
public static void main(String[] args) {
Student s = new Student();
System.out.println("\nDefault Constructor values: ");
System.out.println("Student Id : "+s.id + "\nStudent Name : "
+s.name);
System.out.println("\nParameterized Constructor values:);
Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Na
me : "+student.name);
}
}
Recursion
Recursion is the technique of making a method
call itself. This technique provides a way to break
complicated problems down into simple problems
which are easier to solve.
class FactorialExample
{
public static void main(String args[]){
int i,fact=1;
int number=5;
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Garbage collection
Garbage Collection is process of reclaiming the
runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
Advantage of Garbage Collection

It makes java memory efficient because garbage


collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector(a part
of JVM) so we don't need to make extra efforts.
Java String Class Methods

The java.lang.String class provides a lot of built-in


methods that are used to manipulate string in Java. By the
help of these methods, we can perform operations on
String objects such as trimming, concatenating,
converting, comparing, replacing strings etc.
String Methods
toUpperCase() and
toLowerCase() method
trim() method
startsWith() and
endsWith() method
charAt() Method
length() Method
replace() Method

You might also like