You are on page 1of 75

DEPT & SEM : CSE & I SEM

SUBJECT NAMEOBJECT ORIENTED PROGRAMMING


: THROUGH JAVA

19A05303T
COURSE CODE :
I
UNIT :
P LAKSHMI
PREPARED BY :
CONCEPTS:
• Introduction to Object Oriented Programming
• The History and Evolution of Java
• Introduction to Classes
• Objects, Methods
• Constructors, this keyword, Garbage Collection
• Data Types, Variables,
• Type Conversion and Casting , Arrays
• Operators, Control Statements,
• Method Overloading, Constructor Overloading
• Parameter Passing, Recursion,
• String Class and String handling methods.

COURSE: OOPJ UNIT: 1 Pg. 2


OBJECT ORIENTED PROGRAMMING
 What is Java ?
•Java is a “Programming Language”.
 What is a programming Language?

Programming
Spoken
Languages
Languages

Fig . 1.1:Person to person communication Fig . 1.2:person to system communication

 A programming language is set of instructions , used to establish communication


between human and a system

COURSE: OOPJ UNIT: 1 Pg. 3


JAVA’S LINEAGE

 Java is related to C++, which is a direct descendant of C.


 Much of the character of Java is inherited from these two languages.
 From C, Java derives its syntax. Many of Java’s object oriented features were influenced
by C++.
Earlier languages (cobal, pascal,etc..)

C Language (Procedure oriented)

C++ Language (Object oriented, platform dependent)

Java Language (Object oriented, platform independent)

COURSE: OOPJ UNIT: 1 Pg. 4


OBJECT ORIENTED PROGRAMMING CONCEPTS

COURSE: OOPJ UNIT: 1 Pg. 5


COURSE: OOPJ UNIT: 1 Pg. 6
COURSE: OOPJ UNIT: 1 Pg. 7
COURSE: OOPJ UNIT: 1 Pg. 8
COURSE: OOPJ UNIT: 1 Pg. 9
COURSE: OOPJ UNIT: 1 Pg. 10
COURSE: OOPJ UNIT: 1 Pg. 11
COURSE: OOPJ UNIT: 1 Pg. 12
COURSE: OOPJ UNIT: 1 Pg. 13
THE HISTORY AND EVOLUTION OF JAVA
 Java was developed by James Gosling and his
team at Sun Microsystems, Inc. in 1991.
 This language was initially called “Oak,” but was
renamed “Java” in 1995.
 But the history of Java starts with the Green
project .
 Java team members (also known as Green Team) Fig . 1.3 : James Gosling
 Initiated this project to develop a software for
digital devices such as set-top boxes, televisions,
etc. However, it was suited for internet
programming.
 Green Team thought choose c and c++
languages to develop project ,but they face
problem with that languages that is both
languages are platform dependent.
 Green Team start a new project that develop a
new language that should platform independent. Fig . 1.4 : James Gosling and his team

COURSE: OOPJ UNIT: 1 Pg. 14


JAVA’S MAGIC: THE BYTECODE

 Java bytecode is the instruction set for the Java Virtual Machine.
 Java byte code is the combination of object code and assembly code .
 When we write a program in Java, firstly, the compiler compiles that program and a
bytecode (class file) is generated for that piece of code.
 When we wish to run this .class file is exicuted by JVM and generate matching code.

Fig . 1.5: java Architecture


COURSE: OOPJ UNIT: 1 Pg. 15
JAVA BUZZWORDS
1.Simple
->(easy to learn and write)
2.Secure
(provides data security through encapsulation )

3.Portable
(they can be executed on any kind OS)

4.Object-Oriented
(it is complete object oriented programming)

5.Robust
(it is very strong with type checking

6.Multithreaded

( java support Multithreading)

COURSE: OOPJ UNIT: 1 Pg. 16


7.Architecture neutral
(java is platform independent)

8.Interpreted

(java maintain both compiler and interpreter)
9.High Performance

(java maintain JIT compiler)
10.Distributed

(Java supports distributed computation using Remote Method Invocation (RMI)
concept. )
11.Dynamic
(Libraries are dynamically linked during runtime

COURSE: OOPJ UNIT: 1 Pg. 17


CLASSES

 A class is a collection of Objects. Objects may be fields (data) and methods


(procedure or function) that operate on that data.
(Or)
 A class is a blueprint or template from which individual objects are created.

Circle (Class name)

Centre (Variables)
radius
circumference()
area()

Fig . 1.6: Class Structure

COURSE: OOPJ UNIT: 1 Pg. 18


CLASSES

 A class is a collection of fields (data) and methods (procedure or function) that


operate on that data.

The basic syntax for a class definition:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}

 Bare bone class – no fields, no methods


public class Circle
{
// my circle class
}

COURSE: OOPJ UNIT: 1 Pg. 19


ADDING FIELDS: CLASS CIRCLE WITH FIELDS

 Add fields
public class Circle
{
public double x, y; // centre coordinate
public double r; // radius of the circle
}

 The fields (data) are also called the instance varaibles.


 A class with only data fields has no life. Objects created by such a class cannot
respond to any messages.
 Methods are declared inside the body of the class but immediately after the
declaration of data fields.
 The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}
COURSE: OOPJ UNIT: 1 Pg. 20
ADDING METHODS TO CLASS CIRCLE

public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference()
{
return 2*3.14*r;
}
public double area() Method Body
{
return 3.14 * r * r;
}
}

COURSE: OOPJ UNIT: 1 Pg. 21


VARIABLE TYPES

A class can contain any of the following variable types.


 Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.
 Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
 Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword(can be used to refer the common property of all
objects.)

COURSE: OOPJ UNIT: 1 Pg. 22


Exp:
public class Dog { void hungry()

static String animal_type; // Class variable {

String breed; // instance variable String foodtype; //Local variable

int age; }

String color; void sleeping()

void barking() {

{ }
}

COURSE: OOPJ UNIT: 1 Pg. 23


CREATING OBJECTS OF A CLASS:

 Objects are created dynamically using the new keyword.


 aCircle and bCircle refer to Circle objects

aCircle = new Circle();

bCircle = new Circle();

bCircle = aCircle;


aCircle
bCircle

COURSE: OOPJ UNIT: 1 Pg. 24


aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;

Before Assignment After Assignment

aCircle bCircle aCircle bCircle

P Q P Q

COURSE: OOPJ UNIT: 1 Pg. 25


AUTOMATIC GARBAGE COLLECTION
 The object Q does not have a reference and cannot be used in future.
 The object becomes a candidate for automatic garbage collection.
 Java automatically collects garbage periodically and releases the memory used to be
used in the future.
ACCESSING OBJECT/CIRCLE DATA:
Syntax for accessing data defined in a structure.

ObjectName . VariableName
ObjectName .MethodName(parameter-list)

Circle aCircle = new Circle();


aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0

COURSE: OOPJ UNIT: 1 Pg. 26


USING CIRCLE CLASS:

// Circle.java: Contains both Circle class and its user class


//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+"
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Area="+area);
COURSE: OOPJ UNIT: 1 Pg. 27
CONSTRUCTOR
 Constructor in java is a special type of method that is used to initialize the object.
 Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
RULES FOR CREATING JAVA CONSTRUCTOR:
There are basically two rules defined for the constructor.
1.Constructor name must be same as its class name
2.Constructor must have no explicit return type
TYPES OF JAVA CONSTRUCTORS
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

COURSE: OOPJ UNIT: 1 Pg. 28


EXAMPLE OF DEFAULT CONSTRUCTOR
class Bike1
{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

Output:
Bike is created

COURSE: OOPJ UNIT: 1 Pg. 29


EXAMPLE OF PARAMETERIZED CONSTRUCTOR
class Student4
{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
COURSE: OOPJ UNIT: 1 Pg. 30
this KEYWORD

 this is a reference variable that refers to the current object in java.


 It is a keyword in java language represents current class object.
 this is always a reference to the object on which the method was invoked.
 It can be used in side of method or constructor.
USAGE OF THIS KEYWORD
 It can be used to refer current class instance variable. { this.x }
 this() can be used to invoke current class constructor from another method or constructor.
{ this(); }
 It can be used to invoke current class method (implicitly)
{ this.add() }
 It can be passed as an argument in the method call.
{ add(this);}
 It can be passed as argument in the constructor call.
 It can also be used to return the current class instance.
{ return this; }
COURSE: OOPJ UNIT: 1 Pg. 31
WHY USE THIS KEYWORD IN JAVA ?

 The main purpose of using this keyword is to differentiate the formal parameter and
data members of class.
 whenever the formal parameter and data members of the class are similar then jvm
get ambiguity (no clarity between formal parameter and member of the class)
 To differentiate between formal parameter and data member of the class, the data
member of the class must be preceded by "this".

COURSE: OOPJ UNIT: 1 Pg. 32


EXAMPLE WITHOUT USING THIS KEYWORD
class Employee
{ int id; String name;
Employee(int id,String name)
{ id = id;
name = name;
}
void show()
{ System.out.println(id+" "+name); }
public static void main(String args[])
{ Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show(); e2.show();
}
}
Output
0 null 0 null

COURSE: OOPJ UNIT: 1 Pg. 33


EXAMPLE WITH USING THIS KEYWORD
class Employee
{ int id; String name;
Employee(int id,String name)
{ this. id = id;
this. name = name;
}
void show()
{ System.out.println(id+" "+name); }
public static void main(String args[])
{ Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show(); e2.show();
}
}
Output
111 Harry 112 Jacy

COURSE: OOPJ UNIT: 1 Pg. 34


this: to invoke current class method

35
COURSE: OOPJ UNIT: 1 Pg. 35
this() : to invoke current class constructor

class A{

A(){System.out.println("hello a");}

A(int x){

this();

System.out.println(x);

class TestThis5{

public static void main(String args[]){

A a=new A(10);

}}

Out put:

hello a
36
10 COURSE: OOPJ UNIT: 1 Pg. 36
Calling parameterized constructor from default constructor:

class A{

A(){

this(5);

System.out.println("hello a");

A(int x){

System.out.println(x);

class TestThis6{

public static void main(String args[]){

A a=new A();

}}

Out put:

5 37
COURSE: OOPJ UNIT: 1 Pg. 37
this: to pass as an argument in the method

class S2{

void m(S2 obj){

System.out.println("method is invoked");

void p(){
Hear this refer
m(this); current class object
}

public static void main(String args[]){

S2 s1 = new S2();

s1.p();

} }

Out put:
38
method is invoked COURSE: OOPJ UNIT: 1 Pg. 38
: this keyword can be used to return current class instance

We can return this keyword as an statement from the method. In such case, return
type of the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement

return_type method_name()

{
Control jump from out
return this; of method

}
39
COURSE: OOPJ UNIT: 1 Pg. 39
GARBAGE COLLECTION:
 In java, garbage means unreferenced objects created by new operator dynamically.
 Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
 To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
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.
 If you want to make your object eligible for Garbage Collection, assign its reference
variable to null.
 Primitive types are not objects. They cannot be assigned null.

COURSE: OOPJ UNIT: 1 Pg. 40


DATA TYPES :
Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to


2,147,483,647
long 8 bytes Stores whole numbers from -
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing
6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing
15 decimal digits
boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values

COURSE: OOPJ UNIT: 1 Pg. 41


VARIABLES:

 Variables are containers for storing data values


DECLARING (CREATING) VARIABLES:
 To create a variable, you must specify the type and assign it a value:
Syntax: type variable = value;
 Where type is one of Java's types (such as int or String), and variable is the name of
the variable (such as x or name). The equal sign is used to assign values to the
variable.
 To create a variable that should store text, look at the following Example
 Create a variable called name of type String and assign it the value "John":

String name = "John";


System.out.println(name);

COURSE: OOPJ UNIT: 1 Pg. 42


TYPE CONVERSION AND CASTING
 Java provides various datatypes to store various data values.
 Converting one primitive datatype into another is known as type casting (type
conversion) in Java.
 Widening − Converting a lower datatype to a higher datatype is known as widening. In
this case the casting/conversion is done automatically therefore, it is known as implicit
type casting. In this case both datatypes should be compatible with each other.

Fig . 1.7 : Winding type


 Narrowing − Converting a higher datatype to a lower datatype is known as narrowing.
In this case the casting/conversion is not done automatically, you need to convert
explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type
casting. In this case both datatypes need not be compatible with each other.

Exp:
int x=5,x1; Fig . 1.8:Narrowing type
byte b=8,b1;
x1=b; //Winding
b1=(byte) x; // Narrowing
COURSE: OOPJ UNIT: 1 Pg. 43
ARRAYS

DECLARING AND CREATING AN ARRAY VARIABLE:


 Do not have to create an array while declaring array variable
<type> [] variable_name;
<type> variable_name[];
Ex:
int [] prime;
int prime[];
 Above both syntaxes are equivalent
 No memory allocation at this point
 In Java we allocate memory for array variables with the help of “new” keyword.
 Define an array as follows:
variable_name=new <type>[N];
Ex: primes=new int[10];
 Declaring and defining in the same statement:
int[] primes=new int[10];
 In JAVA, int is of 4 bytes, total space 4*10=40 bytes
COURSE: OOPJ UNIT: 1 Pg. 44
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current
minimum
for ( int i=0; i < array.length; i++ )
if ( array[ i ] < min )
min = array[ i] ;
System.out.println("The minimum of this array is:
" + min );
}
}
O/P: The minimum of this array is: -20
COURSE: OOPJ UNIT: 1 Pg. 45
DEFAULT INITIALIZATION:
 When array is created, array elements are initialized default as
• Numeric values (int, double, etc.) to 0
• Boolean values to false
• Char values to ‘\u0000’ (unicode for blank character)
• Class types to null
TWO-DIMENSIONAL ARRAYS
float[][] temperature=new float[10][365];
• 10 arrays each having 365 elements
• First index: specifies array (row)
• Second Index: specifies element in that array (column)
• I n JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
THREE-DIMENSIONAL ARRAY:
long[][][] beans=new long[5][10][30];
COURSE: OOPJ UNIT: 1 Pg. 46
OPERATORS:

GROUP OF OPERATORS:
 Arithmetic Operators(+,-,*,/ ,%)
• Assignment Operator(=)
• Order of Precedence
• Increment/Decrement Operators(++,--)
 Relational Operators(<,>,<=,>=,==,!=)
 Logical Operators(&&,||,!)
 Bitwise Operators(~,&,|,^)
 Shift Operators(>>,>>>,>>)
 Ternary Operator(?)

COURSE: OOPJ UNIT: 1 Pg. 47


OPERATORS PRECEDENCE

Parentheses (), inside-out


Increment/decrement ++, --, from left to right
Multiplicative *, /, %, from left to right
Additive +, -, from left to right
Relational <, >, <=, >=, from left to right
Equality ==, !=, from left to right
Logical AND &&
Logical OR ||
Assignment =, +=, -=, *=, /=, %=

COURSE: OOPJ UNIT: 1 Pg. 48


SHIFT OPERATORS :

 Shift Left (<<) Fill with Zeros


 Shift Right (>>) Based on Sign
 Shift Right (>>>) Fill with Zeros
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4
a 00000000000000000000000000000011 3
a << 2 00000000000000000000000000001100 12
<<
Left
b 11111111111111111111111111111100 -4
b << 2 11111111111111111111111111110000 -16

a 00000000000000000000000000000011 3
a >> 2 00000000000000000000000000000000 0
>>
Left
b 11111111111111111111111111111100 -4
b >> 2 11111111111111111111111111111111 -1

COURSE: OOPJ UNIT: 1 Pg. 49


SHIFT OPERATOR >>>:

int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4

a 00000000000000000000000000000011 3
a >>> 2 00000000000000000000000000000000 0
>>>
Right 0
b 11111111111111111111111111111100 -4
b >>> 2 00111111111111111111111111111111 +big

COURSE: OOPJ UNIT: 1 Pg. 50


SHIFT OPERATOR EXAMPLES

public class Example


{
public static void main(String[] args)
{
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4

> java Example


a<<2 = 12
System.out.println("a<<2 = " + (a<<2));
b<<2 = -16
a>>2 = 0
System.out.println("b<<2 = " + (b<<2));
b>>2 = -1
a>>>2 = 0
b>>>2 = 1073741823
System.out.println("a>>2 = " + (a>>2));
>

System.out.println("b>>2 = " + (b>>2)); COURSE: OOPJ UNIT: 1 Pg. 51


THE ?(TERNARY) OPERATOR

 Java includes a special ternary operator that can replace certain types of if – then -
else statements. This operator is ?.
The syntax is:
expression1?expression2:expression3;
Hear expression1 returns boolean value.
 If expression1 returns true then expression2 is executed, if expression1 return
false then expression3 is exicuted.
EXAMPLE :
class CheckEvenNumber
{
public static void main( String args[] ) {
int number = 3;
String msg = (number % 2 == 0) ? " The number is even!" : " The number is odd!";
System. out. println(msg);
} }

COURSE: OOPJ UNIT: 1 Pg. 52


CONTROL STATEMENTS

Fig . 1.9 Fig . 1.10

COURSE: OOPJ UNIT: 1 Pg. 53


Fig . 1.11

COURSE: OOPJ UNIT: 1 Pg. 54


Fig . 1.12

COURSE: OOPJ UNIT: 1 Pg. 55


Fig . 1.13

COURSE: OOPJ UNIT: 1 Pg. 56


METHOD/CONSTRUCTOR OVERLOADING
 In Java, it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different.
 If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
 Method overloading is one of the ways that Java supports polymorphism.
ADVANTAGE OF METHOD OVERLOADING:
 Method overloading 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

COURSE: OOPJ UNIT: 1 Pg. 57


1. METHOD OVERLOADING: CHANGING NO. OF ARGUMENTS
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));
}
}
Out put:
22
33
COURSE: OOPJ UNIT: 1 Pg. 58
2) METHOD OVERLOADING: CHANGING DATA TYPE OF ARGUMENTS
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));
}
}
Out put:
22
24.9 COURSE: OOPJ UNIT: 1 Pg. 59
Note:
 In java, method overloading is not possible by changing the return type of the method
only because of ambiguity.
 We can also overload java main() method. You can write any number of main methods in
a class by method overloading. But JVM calls main() method which receives string array as
arguments only. Let's see the simple example:
 If there are matching type(int & long) arguments in the method, type promotion is not
performed.
 We can also overload constructor methods
Exp:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
} Out put: main with String[] COURSE: OOPJ UNIT: 1 Pg. 60
PARAMETER PASSING

 In general, there are two ways that a computer language can pass an argument.
1. call-by-value(pass values).
2. call-by-reference(pass object).
 Java also use above two ways to pass an argument.
 When you pass a primitive type to a method, it is passed by value
 When you pass an object to a method, it is call-by-reference

COURSE: OOPJ UNIT: 1 Pg. 61


// PRIMITIVE TYPES ARE PASSED BY VALUE.(CALL 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);
} }
The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20
COURSE: OOPJ UNIT: 1 Pg. 62
// OBJECTS ARE PASSED THROUGH THEIR REFERENCES (CALL 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 PassObjRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
} }
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
COURSE: OOPJ UNIT: 1 Pg. 63
RECURSION:
 Java supports recursion.
 Recursion is the process of defining something in terms of itself
 Java programming, recursion is the attribute that allows a method to call itself.
 A method that calls itself is said to be recursive.

EXAMPLE FOR RECURTION:


class Factorial {

// this is a recursive method

int fact(int n) {

int result;

if(n==1) return 1;

result = fact(n-1) * n;

//fact(3-1)*3->fact(2-1)*2*3->1*2*3

return result;

}
The output from this program is shown
class Recursion { here:
public static void main(String args[]) {

Factorial f = new Factorial(); Factorial of 3 is 6


System.out.println("Factorial of 3 is " + f.fact(3));
Factorial of 4 is 24
Factorial of 5 is 120
System.out.println("Factorial of 4 is " + f.fact(4));

System.out.println("Factorial of 5 is " + f.fact(5));


COURSE: OOPJ UNIT: 1 Pg. 64
EXPLORING THE STRING CLASS
 Java does not support String type, it is not a simple type .
 String is an array of characters.It is under the package java.lang.*;
 In java String is an “Object”.
 Strings in java are immutable
 Once created they cannot be altered and hence any alterations will lead to creation of
new string object
 String is thread safe. It can not be used by two threads simultaneously
 Note: Object is the super class for all classes in java
String s1 = “Example”
String s2 = new String(“Example”)
String s3 = “Example”
 The difference between the three statements is that, s1 and s3 are pointing to the same
memory location i.e. the string pool . s2 is pointing to a memory location on the heap.
 Using a new operator creates a memory location on the heap.
 Concatinting s1 and s3 leads to creation of a new string in the pool.
COURSE: OOPJ UNIT: 1 Pg. 65
STRING METHODS
Method Description Return
Type
charAt() Returns the character at the specified index (position) char

codePointAt() Returns the Unicode of the character at the specified index int

codePointBefore() Returns the Unicode of the character before the specified index int

codePointCount() Returns the Unicode in the specified text range of this String int

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences int

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence of characters boolean

contentEquals() Checks whether a string contains the exact same sequence of boolean
characters of the specified CharSequence or StringBuffer
copyValueOf() Returns a String that represents the characters of the character array String

endsWith() Checks whether a string ends with the specified character(s) boolean

equals() Compares two strings. Returns true if the strings are equal, and false if boolean
not

COURSE: OOPJ UNIT: 1 Pg. 66


CONTENT BEYOND SYLLABUS

JAVA VERSIONS:
Version - Release date Version - Release date
•JDK Beta - 1995 •Java SE 8 - March 2014
•JDK 1.0 - January 1996 •Java SE 9 - September 2017
•JDK 1.1 - February 1997 •Java SE 10 - March 2018
•J2SE 1.2 - December 1998 •Java SE 11 - September 2018
•J2SE 1.3 - May 2000 •Java SE 12 - March 2019
•J2SE 1.4 - February 2002 •Java SE 13 - September 2019
•J2SE 5.0 - September 2004 •Java SE 14 - March 2020
•Java SE 6 - December 2006 •Java SE 15 - September 2020
•Java SE 7 - July 2011

COURSE: OOPJ UNIT: 1 Pg. 67


CONTENT BEYOND SYLLABUS
STRUCTURE OF JAVA PROGRAMMING

Fig . 1.14
COURSE: OOPJ UNIT: 1 Pg. 68
Scanner Class :
Import java.util.Scanner;
Class Exp
{
public static void main(String[] args)
{
int num;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter num value”);
num=sc.nextInt();
System.out.println(“num:”+num);
}
}
COURSE: OOPJ UNIT: 1 Pg. 69
Import java.util.Scanner;
class Array
{
public static void main ( String[] args )
{
int[] array = new int[5];
Scanner sc=new scanner(System.in);
System.out.println(“Enter elements in to ayyay”);
for ( int i=0; i < 5; i++ )
{
array[i]=sc.nextInt();
}
System.out.println(“Array elements:”);
for ( int i=0; i < 5; i++ )
{
System.out.println(“array[“ + i + ”]” + array[i]);
}
}
}
COURSE: OOPJ UNIT: 1 Pg. 70
Scanner Methods:
nextBoolean() : Reads a boolean value from the user

nextByte() : Reads a byte value from the user

nextDouble() :Reads a double value from the user

nextFloat():Reads a float value from the user

nextInt() :Reads a int value from the user

nextLine():Reads a String value from the user

nextLong():Reads a long value from the user

nextShort():Reads a short value from the user

COURSE: OOPJ UNIT: 1 Pg. 71


Lexical Issues
There are many atomic elements of Java.
Java programs are a collection of
whitespace,

identifiers,

comments,

literals,

operators,

Separators

keywords.

COURSE: OOPJ UNIT: 1 Pg. 72


UNIT OUTCOMES:
Student should be able to
Understand the syntax, semantics and features of Java Programming Language.
Learn object oriented features and understanding type conversion and casting.
Understand different types of string handling functions and its usage.

COURSE: OOPJ UNIT: 1 Pg. 73


DIGITAL RESOURCES

 Lecture Notes - Lecture Notes

 Video Lectures - Video Lecture

 E-Book - Java The Complete Reference Ninth Edition

 Model Papers - JNTUA Question Papers

COURSE: OOPJ UNIT: 1 Pg. 74


THANK YOU

COURSE: OOPJ UNIT: 1 Pg. 75

You might also like