[go: up one dir, main page]

0% found this document useful (0 votes)
3 views18 pages

Introduction to OOP concept-1

This document provides an introduction to Object-Oriented Programming (OOP) concepts, including principles like data abstraction, encapsulation, inheritance, and polymorphism. It covers the basics of classes and objects, data types, operators, input methods, conditional constructs, and looping mechanisms in Java. Additionally, it discusses error types, comments, and mathematical library methods, emphasizing the structure and functionality of Java programming.

Uploaded by

shobharoy79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

Introduction to OOP concept-1

This document provides an introduction to Object-Oriented Programming (OOP) concepts, including principles like data abstraction, encapsulation, inheritance, and polymorphism. It covers the basics of classes and objects, data types, operators, input methods, conditional constructs, and looping mechanisms in Java. Additionally, it discusses error types, comments, and mathematical library methods, emphasizing the structure and functionality of Java programming.

Uploaded by

shobharoy79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

CHAPTER-1 INTRODUCTION TO OOP CONCEPT

Paradigm - Programming paradigm is an approach to solve problem using some


programming language.

POP OOP

Process of dividing a program into number of Process of dividing a program into number of
methods. objects

Not suitable for solving complex problems Suitable for solving complex problems

No data hiding Allows data hiding

No reusability Allows reusability.

Principles of Object Oriented Programming:

1. Data Abstraction- It is the process of showing only the essential features of an object while hiding
the background details.

Eg- While withdrawing money from the ATM we only have to enter the pin, amount to be withdrawn.
Rest of the details remains hidden.

Q. How can we implement Abstraction?

Ans. By defining a class and implementing only what is essential for creating an object.

2. Encapsulation- It is the process of wrapping data and functions into a single unit.

Eg: Consider ATM as an object, it combines data like Account number, balance, pin etc. and methods
like deposit, transfer, withdraw etc. into a single unit.

How can we implement Encapsulation.

Ans. By creating an object of class.

3. Inheritance- It is the process of transferring or sharing properties from once class to another.

Eg: class Maruti Alto derives properties from class Car.

How can we implement Inheritance ?

Ans. By creating a base/super class and deriving the properties into a subclass using the keyword
extends.

4. Polymorphism- When the same object or method can take multiple forms.

Eg: Object mobile phone can be used for calling , texting, video conferencing etc.

How can we implement polymorphism?

Ans. Method overloading

What is the similarity between Abstraction and Encapsulation?


Ans. Both promote data hiding.

What is the difference between Abstraction and Encapsulation?

Abstraction is hiding details by not implementing the non-essential in a class details whereas
Encapsulation is hiding data by wrapping the details within an object, thus securing from
unauthorized access.

What is Data hiding?

Ans. Securing data from unauthorized access.

How can we implement data hiding.

Ans. When an object is created, it acts like a black box by only show. ing the essential details and the
internal mechanism is hidden from the user.

Chapter-2 Elementary concept of Object and class.


1. Class – It is a blueprint or prototype used to create objects with similar characteristics and
behaviour.

Eg-We can use a blueprint of a car to create n number of cars.

2. Object- It is an identifiable entity with some characteristics and behaviour.

Eg.- Object pen has characteristics like colour, type, model and behaviour like used for writing.

An object has the following properties:

State/Attributes- are individual characteristics that differentiate an object from another.

Eg: Name, age, height of a student.

Behaviour- are the functions performed by the object.

Eg: study, read, write etc..

How state/attributes can be implemented in our program?

Ans. Through variables.

How behaviour can be implemented ?

Ans. Through methods.

Class as an object factory- A class can produce multiple objects of the same type.

Benefits of class

1. Helps in implementing reusability of code.

2. Helps in encapsulating variables and methods into objects (data hiding)


What is message passing?

Ans. Objects of a class communicate with each other by passing messages through methods. This is
called message passing.

Class as a blueprint-A class acts as a blueprint that represents a set of objects that share common
characteristics and behaviour.

Class as a user defined data type- Class contains data members and methods that can be accessed
and used by creating an instance of class. It is also called user defined/composite data type as it
contains data members(variables) of different data types.

Creating an instance(object) of class:

Syntax: class_name ob=new class_name();

Eg: Car ob=new Car();

Object Class

An instance of class A blueprint used for creating objects

Physical entity (occupies space in Logical entity.

the memory)

Chapter-3 Values and Data types


Character Set- a set of letters, digits and special characters that are valid in a particular language.

Unicode- The character set of Java. It is a 2 byte character set used to represent almost all characters
in languages around the world.

ASCII- is a code that uses numbers to represent characters. 0 to 127 [128 characters]

A-Z=65-90

a-z=97-122

0-9=48-57

Escape sequence:

It is a combination of characters tha has a special meaning to the Java compiler. It is preceded by a
slash followed by one or more characters.

Eg= “\t”, “ \n”, ‘\u0000’, “ \f”, “ \\” etc.

Token- smallest unit of a program . Also called building blocks of a program.

Eg- keywords, identifiers, literals, operators, punctuators/separators.

Keywords- reserved words that convey a special meaning to the java compiler.

Eg- class, int, for, while, if


Identifiers- are the names of variables, methods, classes, packages and interfaces.

Rules:

Must start with a letter or underscore (_) or dollar ($)

Must not start with a digit

Cannot be used as identifier

Can be of any length

Literals-data items which remain fixed.

Types of literals

1. Integer- whole numbers eg. 10, -12

2. Real- numbers with decimal point eg. 15.7

3. Character- single character enclosed in single quotes eg- ‘a’

4. String-sequence of characters enclosed in double quotes eg-“abc”

5. boolean-true/false

6. null-special literal represented by keyword null or ‘\0’

Operators-special symbols that are used to perform predefined operations. Eg- +,−¿

Puctuators/separators-used to separate the variables, literals, characters or statements

Eg- (),{},[], , , ., ; etc

Data types- type of value to be stored in a variable.

Primitive non primitive

Built in data types derived or reference data types

Independent of any type depends on primitive type

Eg-int, char class, array

Data type Size in Range Default value


bytes

Byte 1 byte 7
−2 ¿ +2 −1
7
0

Short 2 bytes 15
−2 ¿+2 −1
15
0
Int 4 bytes 31
−2 ¿ +2 −1
31
0

Long 8 bytes 63
−2 ¿+ 2 −1
63
0L

Float 4 bytes −3.4 E+ 38 ¿+3.4 E+38 0.0f

Double 8 bytes −1.8 E+308 ¿+1.8 E+308 0.0d

Char 2 bytes 0 to 65535[0 to 216-1] ‘\u0000’

Boolean 1 bit true or false False

Non Null
primitive

Variable- named location in the memory that can store data temporarily.

Declaring variable:

data_type variable name;

Initializing variables-assigning value to a variable

1. static initialisation-during declaration : eg int a=10;

2. dynamic initialization-at runtime: eg: c=a+b; or a=sc.nextInt();

Scope of variable- part of program where it can be accessed.

1. local variable- declared inside method

Eg. int sum(){int a;}

Or int sum(int a){}

2. Global variable: outside method body.

2.1 instance variable- objects have distinct copy of this variable

2.2 class variable-same copy is shared by all objects

Eg: class A{

int a; //instance variable

static int a;//class variable }

Declaring a variable as constant:

final datatype var=value;

once a variable is defined as constant, the value of the variable becomes constant and no new value
can be assigned to that variable.
Type conversion- converting variable of one type to another

1. implicit/conversion- automatic conversion done by compiler

Eg: int+float=float

long+double=double

int+char=int

2. explicit conversion/typecasting-forceful conversion performed by the user

Example;

double c; int a,b;

c=(double)a/b;

data types in order of size :

Ascending: boolean, byte, short, char, int, float, long, double

Descending: double, long, float, int, char, short, byte, boolean

Chapter-4 Operators in Java


Operators are special symbols that can be used to perform predefined operations on one or more
operands.

Forms of operators:

1.Unary operators- operate on single operands.

Unary ¿, Unary ¿, Logical Not(!) , ++¿ , −−¿

2. Binary operators- operate on two operands.

ARITHMETICAL+ ,−,∗,/, % ,

RELATIONAL< ,≤,> ,≥,=¿

LOGICAL∧¿ ,∨¿

3. TERNARY-Operates on 3 operands- ? :

Types of operators:

Arithmetical operators- used to perform arithmetical operations on two operands. +,−,∗,/, % ,

Relational operators- returns true/false after comparing two operands. ¿ ,≤,>,≥,=¿

Logical operator-returns true/false after comparing the result of one or expressions. ¿∧,∨¿ ,!

Assignment- assigns a value from right side of an expression to left side operand- ¿
Short hand assignment +¿ ,−¿ ,∗¿ , %=,/¿

Operator precedence

˙
1.B-Brackets (), {},[ ], (.)

2. U- Unary ++,−−,+,−, !

3. N-new

4. A- Arithmetical 1.∗,/, % 2.+,−¿

5.R- Relational ¿ ,≤,>,≥¿

6. L- Logical ¿∧,∨¿

7. T- Ternary ? :

8. A- Assignment ¿, shorthand assignment +¿ ,−¿ ,∗¿ ,/¿ , %=¿

Associativity- operators with same precedence are evaluated from either left to right or right to left.

Example: a+ b−c ( left to right)

! (a>b∧¿ a> c) (right to left)

Dot (.)- operator is used to call/invoke a member method. Eg. sc.next()

new- operator is used to allocate space for the object/array at runtime.

CHAPTER-5 Input in Java


Package- a group of classes. Eg. java.io, java.util, java.lang

import- keyword used to call a package in a program.

Types of input:

1. Using Scanner class

2. argument/parameter – void main(int a,int b) or void main(String ar[])

3. InputStreamReader and BufferedReader class

Methods of Scanner class:

nextByte()-accept whole number in byte

nextShort()-accept whole number in short

nextLong()-accept whole number in long

nextFloat()-accept real/fraction number in float

nextDouble()-accept real/fraction number in double


next()-accept a single word. [ without any space, space acts as terminator]

nextLine()-accepts a sentence. [ reads sequence of characters including space until enter key is
pressed]

Errors

1. Syntax errors- Errors due to incorrect syntax in a program such as missing semicolon, brackets or
misspelt keyword. These errors are detected by java compiler.

2. Logical Errors- Errors due to incorrect logic by the programmer such as wrong use of operator.
These errors can neither be detected by the compiler nor by JVM.

3. Runtime Errors- Errors due to incorrect input while the program is running. Eg- division by zero,
square root of a negative number etc.

Comments -A brief description of the source code ignored by the compiler.

1. single line comment- //

2. multiline comment- /*………*/

3. documentation comment- /**………*/

Chapter 6 Mathematical Library methods


Return type Method name Description

depends on the type of argument abs() returns the absolute value of


an argument.
(byte/short/int/long/float/double)
Eg Mat h .|(−6)|=6

depends on the type of argument min() returns the minimum of two


arguments.

Eg Mat h . min(−2,−3)=−3

depends on the type of argument max() returns the maximum of two


arguments.

Eg Mat h . max (−3 ,−7)=−3

Double floor() returns the closest double


value¿or ¿ the argument

Eg Mat h . floor (3.7)=3.0

Double ceil() returns the closest double


value¿or ¿ the argument
Eg Mat h . ceil (3.1)=4.0

double pow() returns the result after raising


x to the power of y

Eg Mat h . pow(5 , 2)=25.0

double sqrt() returns the square root of a


positive agument

Eg Mat h . √ ( 4)=2.0

double cbrt() returns the cube root of an


argument

Eg Mat h . cbrt (125)=5.0

Double random() returns a double fraction value


¿ 0.0∧¿ 1.0

int/long round() returns the closest rounded off


integer

Mat h .round (2.5)=2

Write a java statement to generate random numbers from 1 to 10

∫ r =¿
Write a java statement to generate random numbers within min value (m) and max value (n)

∫ r =¿
Note- Math class and it’s respective methods are defined in java.lang package which is imported by
default.

Exception / Runtime error

Math.sqrt(negative argument)=NaN

Chapter-7 Conditional Constructs


Selection statements-when a block of statements are to be executed based on the result of a
condition.

Types:

1. if statement- executes a block of statements if the condition is true otherwise control exits and
moves to the next statement .

Syntax:

if(condition/boolean expr.){
statements}

2. if….else – executes the statements in the if block if the test expression in if evaluates to true
otherwise the statements inside else block are executed.

Syntax::

If(condition/boolean expr){

Statements; }

else{

statements;}

3. if…else if- can be used to check multiple conditions. If the first condition evaluates to true, then the
rest of the conditions are skipped otherwise the control moves to the next condition.

Syntax:

If(condition/boolean expression){

Statement}

else if(condition/boolean expr){

statement}

else{

statement}

4. Nested if- if statement containing another if statement

Syntax:

if(boolean expression){

if(boolean expression){

statement}

else{

statement}

5. switch – can be used to check multiple conditions as an alternative to if…else if

Syntax

switch(expr){

case label1:
statement

break;

case label2:

statement

break;

default:

statement}

switch v/s if

if switch

● supports all data types ● supports only int/char

● supports range of values ● works on exact match of values

fall through-absence of break statement after one or more cases results in fall through.

Eg: switch(expr){case label 1: case label2: case label3: statement;break;}

Chapter-8 LOOPING/ITERATION
Loop- is a control statement used to perform repetitive tasks.

Types:

1. entry controlled- first condition is checked, later statements inside looping body are executed [for,
while]

2. exit controlled- first statements inside looping body are executed atleast once, later condition is
checked. [do…while]

The ‘for’ loop- when the number of iterations are fixed.

Syntax:

for(initialization; test expr; update){statements}

The ‘while’ loop- when the number of iterations are not fixed

Syntax:

Intialisation;

while(test expr.){ statement ; update};

The ‘do-while’ loop- used when the statements in loop body are to be executed atleast once.

Initiaisation;
do{ statement; update}while(test expr);

null/empty loop- a loop that does not contain any statements in its body.

eg 1. for(int i=1;i<=10;i++){} or for(int i=1;i<=10;i++); or int i=1;

Infinite loop- a never ending loop whose stop condition always evaluates to true.

Eg for(;;) or while(true)

Jump statements- allow the control to jump from one part of program to another depending on the
result of a boolean expr.

break- terminates the loop depending on the result of a boolean expression

Eg. for(int i=1;i<=10;i++){ if(i==5)break; System.out.println(i);}

continue- skips the statements after it and resumes for the next iteration/update

or for(int i=1;i<=10;i++){if(i%2==0)continue; System.out.println(i);}

Library classes
Wrapper class-predefined classes stored in java.lang package, used to convert from primitive to String and vice
versa.

List of wrapper classes

Byte, Short,Integer,Long,Float,Double,Character,Boolean

Autoboxing- process of automatically converting primitive type into wrapper class object type.

Eg: int a=10; Integer i=new Integer(a);

Unboxing-process of converting wrapper class object into primitive type.

Eg:Integer i=new Integer(10); int j=i;

Character wrapper class

Return type Method name Description

boolean isLetter() Returns true if the argument is a letter

boolean r=Character.isLetter(c);

boolean isDigit() Returns true if the argument is a digit

boolean r=Character.isDigit(c);

boolean isLetterOrDigit() Returns true if the argument is either a letter or digit.

boolean r=Character.isLetterOrDigit(c);

boolean isWhitespace() Returns true if the argument is a whitespace


boolean r=Character.isWhitespace(c);

boolean isUpperCase() Returns true if the argument is in uppercase

boolean r=Character.isUpperCase(c);

boolean isLowerCase() Returns true if the argument is in lowercase

boolean r=Character.isLowerCase(c);

char toUpperCase() Returns the character after converting it to uppercase if in lowercase

char c=Character.toUpperCase(c);

char toLowerCase() Returns the character after converting it to lowercase if in uppercase

char c=Character.toLowerCase(c);

String Library methods

Int length() Returns the length of the string

(counts from 1)

int l=s.length();

Char charAt() Returns a character from specified position in the


String.

char c=s.charAt(2);

String replace() Returns the string after replacing all occurances of a


character in the string with another character.

String s1=s.replace(‘a’,’*’);

String toUpperCase() Returns the String after converting all its characters
to uppercase if in lowercase.

Eg- String s1=s.toUpperCase();

String toLowerCase() Returns the String after converting all its characters
to lowercase if in uppercase.

Eg- String s1=s.toLowerCase();

String substring() Returns a part of String from the given String


according to the specified start, end arguments.

String s1=s.substring(start,end);

Would extract from start till end-1

String s2=s.substring(start);
Would extract from start till end-1

Boolean equals() Returns true if both the Strings are equal without
ignoring their case.

boolean r=s.equals(s1);

Boolean equalsIgnoreCase() Returns true if both the Strings are equal after
ignoring their case.

boolean r=s.equalsIgnoreCase(s1);

Int compareTo() Returns 0 if both the Strings are equal, >0 if first
String is greater, <0 if Second String is greater
without ignoring their case.

int r=s.compareTo(s1);

Int compareToIgnoreCase() Returns 0 if both the Strings are equal, >0 if first
String is greater, <0 if Second String is greater
without ignoring their case.

int r=s.compareToIgnoreCase(s1);

String concat() Returns a new String after


merging one or more Strings.

String s3=s1.concat(s2);

String trim() Returns the string after


removing spaces from
beginning and end of the String.

String s1=s.trim();

User Defined Methods


Method- is a block of statements for performing a specified task.

Advantages:

1. reusability of code

2. modularity

3. easy debugging

4. reduces complexity

Types of methods:

1. pure- method that does not modify the state of received parameter.
Eg: int pure(int a){ return a;}

2. impure- method that modifies the state of received parameter.

void impure(int a[]){ for(int i=0;i<a.length;i++)a[i]*=2;}

Method definition- consists of method header/prototype and method body.

1. method header/prototype- first line of method definition consisting of [access specifier/modifier], return
type, method name and [parameter list]. Eg- public int find(int x)

Access specifier- defines the visibility of a method

2. method body- one or more statements enclosed in pair of curly brackets.

Parts of method header/prototype

1. access specifier/ access modifier- defines the visibility of a method/variable from within or outside
the class premises.

1. public-member can be accessed from anywhere inside/outside the class premises

2. private-member can be accessed from only within the class in which it is defined.

3. protected-only accessible by subclass.

4. default/package-member without any access specifier. Can be accessed across the same package.

2. Non access modifiers- notify the behaviour of a method/variable (member)

1. Static

class variable instance variable

only one copy of this variable is shared Each object has distinct copy of this variable.

by all objects of class.

class y{ static int a;} class y{ int a;}

static method non static method

Not a part of the instance/ It is a part of the object of object of a class. of a class.

Eg-Math.sqrt() eg- sc.nextInt()

final-keyword used to define a variable as a constant.

Eg. final int a=5;

3. return type- depicts the type of value returned by a method

byte/short/int/long/float/double/char/boolean/void

void-no return

4. method name-user defined/identifier

5. parameters- list of arguments enclosed in brackets


formal parameters- parameters present in method prototype; receive the value during method call

eg- add(int x,int y)

actual parameters-parameters present in method call statement. pass the value during method call.

Eg- ob.add(10,20);

6. method signature-refers to the number and type of arguments in the method

eg- add(int x, int y)

Binding- linking function call with function signature

1. Static binding / early binding- linking method call with method signature during compilation.

2. Dynamic binding/late binding-linking method call with method signature at runtime

Ways of calling a method

1. pass by value/call by value-during a method call actual parameter gets copied into formal parameter,
an changes in the formal parameter doesn’t reflect on the actual parameter.

2. Pass by reference/call by reference- during a method call actual parameter gets copied into formal
parameter, any changes in formal parameter reflects on the actual parameter.

Four different ways in which a method can be defined

1. With parameter and with return

Eg. int product(int x, int y){return x*y;}

2. Without parameter and with return

Eg. int product(){ Scanner sc=new Scanner(System.in); System.out.println(“enter x,y”);

x=sc.nextInt(); y=sc.nextInt(); return x*y;}

3. With parameter and without return.

Eg. void product(int x, int y){System.out.println(x*y);}

4. Without parameter and without return

void product(){Scanner sc=new Scanner(System.in); System.out.println(“enter x,y”);

x=sc.nextInt(); y=sc.nextInt(); System.out.println(x*y);}

method overloading-more than one method in a class with the same name but differentiated by number or
type of arguments.

class overlaod{

int compute(int s){return s*s;}

int compute(int l, int b){ return l*b;}


double compute(int r){ return Math.PI*r*r;}

OR

class overload{

void volume()

{ Scanner sc=new Scanner(System.in);

System.out.println(“Enter l,b,h”); int l=sc.nextInt();

int b=sc.nextInt(); int h=sc.nextInt();

System.out.println(l*b*h); }

void volume(int r)

System.out.println(4.0/3*Math.PI*r*r*r);

Arrays-collection of similar type of elements with a common name

Data type variable_name []=new data type []l;

Declaration: int a[]=new int[10];

Initialization: assigning value during array declaration

int a[]={10,20,30,40};

int a[][]={{1,2,3},{3,4,5}};

Index/subscript-individual cell/location of array storing an element.

Types

1. Single dimensional-array elements are stored in linear/consecutive memory locations

2. Double dimensional array- array elements are stored in a row × column format

Calculating size of an array

Size of array data type × number of elements

Ar.length-refers to number of rows

Ar[i].length-refers to number of columns.

Constructor-special method that has same name of class; used to initialize data members of a class.

Types:
1. Default constructor-contructor without any parameter; used to initialize data members with default or
definite values.

Eg. class y{

int a;

y()

A=10;

}}

2. Parameterised constructor-constructor that has parameter in its header; used to initialize data
members with parameter values.

Eg. class y{

int a;

y(int x)

a=x;

}}

You might also like