Professional Documents
Culture Documents
Object Oriented Programming Through Java: G.Praveen Itdept-Snist
Object Oriented Programming Through Java: G.Praveen Itdept-Snist
By.
G.Praveen Kumar
Assit.Prof , IT Dept.
SNIST.
G.Praveen ITDept-SNIST 1
UNIT I
G.Praveen ITDept-SNIST 2
Objective:
On the completion of the unit, a student should be able to:
i)Write compile and execute simple java programs
ii) Understand the syntax of classes and objects creation in java
iii) Explain the differences between classes and objects
iv)differentiate methods and constructors
v) Understand constructor and method overloading
vi) Understand how to handle strings in java
G.Praveen ITDept-SNIST 3
Introduction TO Programming Languages
& Features of JAVA
History of Java, Java buzzwords,
G.Praveen ITDept-SNIST 4
“A programming language is a notational system for describing computation in a
machine-readable and human-readable form. A programming language is a tool for
developing executable models for a class of problem domains.”
OR
“ A programming language is a set of rules that provides a way of telling a
computer what operations to perform”
G.Praveen ITDept-SNIST 5
Interpreter Compiler
Scans the entire program and
Translates program one statement at a
translates it as a whole into machine
time.
code.
It takes large amount of time to
It takes less amount of time to
analyze the source code but the
analyze the source code but the
overall execution time is
overall execution time is slower.
comparatively faster.
No intermediate object code is Generates intermediate object code
generated, hence are memory which further requires linking, hence
efficient. requires more memory.
Continues translating the program It generates the error message only
until the first error is met, in which after scanning the whole program.
case it stops. Hence debugging is Hence debugging is comparatively
easy. hard.
Programming language like
Programming language like C, C++
HTML,JAVA Script , Python, Ruby
use compilers.
use interpreters.
G.Praveen ITDept-SNIST 6
G.Praveen ITDept-SNIST 7
History of Java
The Birth of JAVA - as a technology for Set Top Boxes !
The Java platform and language began as an internal project at Sun
Microsystems in December 1990, providing an alternative to the C++/C
programming languages. Engineer Patrick Naughton, James Gosling and
Mike Sheridan were attempting to develop a new technology for
programming next generation smart appliances (like set-top boxes!), which
Sun expected to be a major new opportunity. It was called the Green project.
G.Praveen ITDept-SNIST 8
Year Progress
1990 Sun decided to developed software that could be used for
electronic devices. And the project called as Green Project
head by James Gosling.
1991 Announcement of a new language named ―Oak‖
1992 The team verified the application of their new language to
manage a list of home appliances using a hand held device.
1993 The WWW appeared on the Internet and transformed the
text-based interface to a graphical rich environment.
1994 The team developed a new Web browsed called ―Hot
Java‖ to locate and run Applets
1995 Oak was renamed to Java, as it did not survive ―legal‖
registration. Many companies such as Netscape and
Microsoft announced their support for Java.
1996 Java language is now famous for Internet programming as
well as a general purpose
G.Praveen OO language.
ITDept-SNIST 9
Year Progress
1997 Sun releases Java Development Kit(JDK 1.1)
1998 Sun releases Software Development Kit (SDK 1.2)
1999 Sun releases Java 2 platform Standard Edition (J2SE)
and Enterprise Edition(J2EE).
2000 J2SE with SDK 1.3 was released.
G.Praveen ITDept-SNIST 10
Introduction to JAVA
Java is on Object-Oriented , cross plat form ,
multipurpose programming language Developed by
James Gosling and his team at Sun Microsystems.
Gosling's new language needed to be
accessible by a variety of computer processors.
In 1994, and he understand that such a language would be
ideal for use with web browsers and Java's connection
to the internet began.
In 1995, Netscape Incorporated released its latest version of
the Netscape browser which was capable of running Java programs.
G.Praveen ITDept-SNIST 11
The original name of this language was Oak, until it was discovered that a
programming language already existed that was named Oak.
It is customary for the creator of a programming language to name the language
anything he chooses. As the story goes, after many hours of trying to come up with a
new name, the development team went out for coffee and the name Java was born.
While Java is viewed as a programming language to design applications for the
Internet, it is in reality a general all purpose language which can be used independent
of the Internet.
G.Praveen ITDept-SNIST 12
Features of JAVA
1. Simple
2.Secure
3.Object Oriented
4. Robust
5.Platform Independent
6.Multi Threading
7.Architectural Neutral
8.Portable
9.High Performance
10.Ease of Use
11.Improved Polyglot programming
12.Improved Security and performance
G.Praveen ITDept-SNIST 13
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.
The confusing and ambiguous concepts of C++ are either left out in Java or they have
been re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of
C++.
2) Secure
Java is very secure language . With java secure features it enable us to develop
virus free, temper free system. Java program always runs in Java runtime environment
with almost null interaction with system OS, hence it is more secure.
G.Praveen ITDept-SNIST 14
b)Exception handling concept: The concept of exception handling enables Java to
capture a series of errors that helps developers to get rid of risk of crashing the system.
G.Praveen ITDept-SNIST 16
G.Praveen ITDept-SNIST 17
Introduction to OOP’s (Object-Oriented Programming Concepts)
G.Praveen ITDept-SNIST 18
Class:- A class is a set of objects with similar properties (attributes), common behavior
(operations), and common link to other objects. The complete set of data and code of an
object can be made a user defined data type with the help of class. The objects are variable
of type class. A class is a collection of objects of similar type. Classes are user defined
data types and work like the build in type of the programming language. Once the class
has been defined, we can make any number of objects belonging to that class. Each object
is related with the data of type class with which they are formed.
As we learned that, the classification of objects into various classes is based on its
properties (States) and behavior (methods). Classes are used to distinguish are type of
object from another. The important thing about the class is to identify the properties and
procedures and applicability to its instances.
For example:College-
SNIST
IT
XYZ
G.Praveen ITDept-SNIST 20
Polymorphism:- When one task is performed by different
ways known as polymorphism.
“POLY+MORPHISM=“MANY+FORM”
‘HAVING MANY FORMS is know as Polymorphism.
For example: To convince the
customer differently, to draw something
e.g. shape or rectangle etc.
In java,
we use method overloading
and method overriding to achieve polymorphism.
Abstraction:- Hiding internal details and showing
functionality is known as abstraction. For example: phone call,
we don't know the internal processing.
In java, we use abstract class and interface to achieve
abstraction.
Encapsulation:- Binding (or wrapping) code and data together into a single unit is known
as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because
all the data members are private here.
G.Praveen ITDept-SNIST 21
Robust:-Java makes an effort to eliminate error level codes by highlight mainly
on compile time error checking and runtime checking. But the main areas which
Java improved were Memory Management and mishandled Exceptions by
introducing automatic Garbage Collector and Exception Handling.
Platform Independent:- All programming languages such as C, C++ etc which
are compiled into platform specific machines. Java is guaranteed to be write-
once, run-anywhere language.
A Java program is compiled into byte code. This byte code is platform
independent and can be run on any machine, plus this byte code
format also provide security. Any machine with Java Runtime Environment can
run Java Programs.
G.Praveen ITDept-SNIST 22
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many
tasks simultaneously. Benefit of multithreading is that it utilizes same memory and
other resources to execute multiple threads at the same time, like While typing,
grammatical errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent
features. Everything related to storage is predefined, example: size of primitive data
types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language
like C or C++. But, Java enables high performance with the use of just-in-time
compiler.
G.Praveen ITDept-SNIST 23
JVM (Java Virtual Machine) :- JVM (Java Virtual Machine) is an abstract
machine. It is a specification that provides runtime environment in which java byte
code can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).
G.Praveen ITDept-SNIST 24
Internal Architecture of JVM
JVM Architecture
G.Praveen ITDept-SNIST 25
1)Classloader:- Classloader is a subsystem of JVM that is used to load class
files.
2) Class(Method) Area:- Class(Method) Area stores per-class structures such
as the runtime constant pool, field and method data, the code for methods.
3) Heap:- It is the runtime data area in which objects are allocated.
4) Stack:- Java Stack stores frames. It holds local variables and partial results,
and plays a part in method invocation and return. Each thread has a
private JVM stack, created at the same time as thread. A new frame is
created each time a method is invoked. A frame is destroyed when its
method invocation completes.
G.Praveen ITDept-SNIST 26
5) Program Counter Register:- PC (program counter) register. It
contains the address of the Java virtual machine instruction currently
being executed.
6) Native Method Stack:- It contains all the native methods used in the
application
.
7) Execution Engine:- It contains:
a) A virtual processor
b) Interpreter: Read byte code stream then execute the
instructions.
c)Just-In-Time(JIT) compiler: It is used to improve the
performance.JIT compiles parts of the byte code that
have similar functionality at the same time. Reduces the
amount of time needed for compilation. Here the term ?
compiler? refers to a translator from the instruction set of a Java
virtual machine (JVM) to the instruction set of a specific CPU.
G.Praveen ITDept-SNIST 27
Variables and Data Types in Java:-
Variable is name of reserved area allocated in memory. it is a name of memory
location.
eg:- int a=35; //a is varaible it stroes value 35.
G.Praveen ITDept-SNIST 28
1) Local Variable:-
A variable which is declared inside the method is called local variable.
2) Instance Variable:-
A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
3) Static variable:-
A variable that is declared as static is called static variable. It cannot be local.
We will have detailed learning of these variables in next chapters.
class IT-2A
{
int data=11;//instance variable
static int Code=31;//static variable
void method()
{
int n=01;//local variable
}
}//end of class
G.Praveen ITDept-SNIST 29
Scope and Lifetime of Variables in Java:-
Scope and Lifetime of Variables. The scope of a variable defines the
section of the code in which the variable is visible. As a general
rule, variables that are defined within a block are not accessible outside that
block. The lifetime of a variable refers to how long the variable exists before it
is destroyed.
G.Praveen ITDept-SNIST 30
Data Types in Java:- Data types are used to allocate the memory .Data types
represent the different values to be stored in the variable. In java, there are two
types of data types:
Primitive data types(or) Predefined
Non-primitive data types (or) User defined
G.Praveen ITDept-SNIST 31
Data Type Default Default Range
Value size
boolean false 1 bit true or false
char '\u0000' 2 byte 0 to 65,536 (unsigned)
G.Praveen ITDept-SNIST 32
Operators:- Operator in java is a symbol that is used to perform special operations.
For example: +, -, *, / etc.
There are basically two types of Operators
1) Unary Operator
2)Binary Operator
1)Unary Operator:- This operator perform operation on single operand (Variable);
eg:-a=a+10;
2) Binary Operator:- This operator perform operation on more than ne operands
Eg:- c=a+b;
G.Praveen ITDept-SNIST 33
Java Operator Precedence
Operator Type Category Precedence
Incrment/Decrement postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
G.Praveen ITDept-SNIST 35
class SS
{
public static void main(String args[])
{
Student2a s1 = new Student2a();
Student2a s2 = new Student2a();
s1.get(001,"KIRAN");
s2.get(043,"NAVEEN");
s1.display();
s2.display();
} }
OUTPUT:-
C:\praveen\JAVA>java SS
1 KIRAN SNIST
35 NAVEEN SNIST
G.Praveen ITDept-SNIST 36
G.Praveen ITDept-SNIST 37
class Student2a
{
int sno;
String name;
static String college ="SNIST";
void get(int r,String n)
{
sno = r;
name = n;
}
void display ()
{System.out.println(sno+" "+name+" "+college);
}}
class s11 extends Student2a
{
college="JNTU";//
void show()
{System.out.println(sno+" "+name+" "+college);
}}
G.Praveen ITDept-SNIST 38
class SS1
{
s1.get(001,"KIRAN");
s2.get(043,"NAVEEN");
s1.display();
s2.display();
}
}
G.Praveen ITDept-SNIST 39
If-else Statement:- if statement is used to test the condition. It checks boolean
condition: true or false. There are various types of if statement in java.
1)if statement 2) if-else statement 3) nested if statement
IF Statement:- The Java if statement tests the condition.
It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:-
class Con1
{
public static void main(String args[])
{
int n;
n=10;
if(n%5==0)
{
System.out.println("the number "+n+"is divided by 5");
}
}}
G.Praveen ITDept-SNIST 40
IF-else Statement:- The Java if-else statement also
tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition){ //code if condition is true }
else{ //code if condition is false }
G.Praveen ITDept-SNIST 42
G.Praveen ITDept-SNIST 43
Switch Statement:-
The Java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement.
Syntax:
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;
}
G.Praveen ITDept-SNIST 44
G.Praveen ITDept-SNIST 45
G.Praveen ITDept-SNIST 46
Compare switch and nested if-else
G.Praveen ITDept-SNIST 47
G.Praveen ITDept-SNIST 48
Type conversion and costing:-Assigning a value of one type to a variable
of another type is known as Type Casting.
Eg:- int x = 10;
byte y = (byte)x;
Type casting is classified into two types
1. Widening Casting(Implicit)
2. Narrowing Casting(Explicitly done)
G.Praveen ITDept-SNIST 49
public class Testcasting1
{
public static void main(String[] args)
{
int i = 25;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}}
OUTPUT:-
C:\praveen>java Testcasting1
Int value 25
Long value 25
Float value 25.0
G.Praveen ITDept-SNIST 50
2. Narrowing Casting(Explicitly done) :- larger type value to a variable of smaller
type is called explicit type casting.
G.Praveen ITDept-SNIST 51
Arrays:- “An array is a Indexed collection of fixed number of homogenous
data elements”.
An array can be either primitive or reference type. It gets memory in heap area.
Index of array starts from zero to size-1.
G.Praveen ITDept-SNIST 53
Note: To find the length of an array, we can use the following
syntax: array_name.length. There are no braces infront of length. Its not length().
G.Praveen ITDept-SNIST 54
G.Praveen ITDept-SNIST 55
OUTPUT:-
C:\praveen>java Bsort
Enter size of array
5
Enter elements in to array
56
89
3
12
1
Array Before Bubble Sort
56 89 3 12 1
Array After Bubble Sort
1 3 12 56 89
G.Praveen ITDept-SNIST 56
Multidimensional array:- A multi-dimensional array is very much similar to a
single dimensional array. It can have multiple rows and multiple columns unlike
single dimensional array.
Array Declaration:-
dataType[][] identifier; (or) = int [][] a
dataType [][] identifier ; (or) = int [][]a
dataType identifier[][]; (or) =int a[][]
dataType [] identifier []; = int []a[]
Initialization of Array:-
int[ ][ ] arr = new int[size-n][size-m]; = int[ ][ ] M = new int[5][5];
G.Praveen ITDept-SNIST 57
class Twoarray
{
public static void main(String args[]){
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}}
OUTPUT:-
C:\praveen>java Twoarray
1234
11 12 14 15
14 24 34 44 G.Praveen ITDept-SNIST 58
G.Praveen ITDept-SNIST 59
OUTPUT:-
C:\praveen>java Matadd
enter no of rows matrix A
2
enter no of cols matrix A
2
enter no of rows matrix B
2
enter no of cols matrix B
2
enter elements in to matrix A
2 2 2 2
enter elements in to matrix B
22 2 2
sum matrix is:
4 4
4 4
G.Praveen ITDept-SNIST 60
Jagged Array:- Jagged means to have an uneven edge or surface.A jagged array means to
have a multi-dimensional array with uneven size of rows in it.
G.Praveen ITDept-SNIST 61
Class:- A class is a collection of fields (data members) and methods (procedure or
function) that operate on that data.
(or)
A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity.
A class in Java can contain:
fields
methods
constructors
blocks
nested class and interface
Syntax to declare a class:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}
Note:- fields (data members) are used to create methods and methods are
used to identifies behavior (or) significant of class.
G.Praveen ITDept-SNIST 62
Adding Fields: Class Student with fields
Class Student
{
int stuno;
double stufee;
String studentname;
}
Note:- The fields are also called as instance variables.
Adding Methods :-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:
Return-type MethodName (parameter-list)
{
Method-body;
}
Eg:- void get(int a,int b)
{
int c;
c=a+b;
}
G.Praveen ITDept-SNIST 63
Advantage of Method:-
Code Reusability
Code Optimization
An object is a specimen of a class. Software objects are often used to model real-
world objects.
new keyword in Java:-
The new keyword is used to allocate memory at run time. All objects get memory
in Heap memory area.
G.Praveen ITDept-SNIST 64
G.Praveen ITDept-SNIST 65
Constructor :- Constructor is a special type of method , method name is same as
class name is called constructor. It is used to initialize memory to the method at
object creation. 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.
I.Constructor name must be same as its class name
II.Constructor must have no explicit return type
G.Praveen ITDept-SNIST 66
Default Constructor:- A constructor that have no parameter is known as default
constructor.
Sy ntax:-
<classname>()
{
……
}
Eg:- class exp()
{
Int a,b;
Exp()
{ }
parameterized constructor:- A constructor that have parameters is known as
parameterized constructor.
Sy ntax:-
<classname>()
{
……
}
Eg:- class exp()
{
int a,b; G.Praveen ITDept-SNIST 67
G.Praveen ITDept-SNIST 68
Difference between constructor and method in java:-
G.Praveen ITDept-SNIST 69
Method in JAVA:-A Java method is a collection of statements that are grouped
together to perform an operation. When you call the System.out.println()
Creating Method:-
public static int method Name(int a, int b)
{
// body
}
Here,
public static − modifier
int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters
G.Praveen ITDept-SNIST 70
Method definition consists of a method header and a method body.
modifier returnType nameOfMethod (Parameter List)
{ // method body }
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the
statements.
public static int minFunction(int n1, int n2)
{
int min;
if (n1 > n2) min = n2;
else
min = n1;
return min; }
G.Praveen ITDept-SNIST 71
Method Overloading:- A class has two or more methods by the same name but
different parameters, it is known as method overloading.
G.Praveen ITDept-SNIST 72
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
By changing number of arguments
By changing the data type
G.Praveen ITDept-SNIST 73
This keyword:-this is a keyword in Java which is used as a reference to the
object of the current class, with in an instance method or a constructor.
Using this we can refer the members of a class such as constructors, variables and
methods.
G.Praveen ITDept-SNIST 74
G.Praveen ITDept-SNIST 75
Garbage Collection:-Garbage means unreferenced objects.
Garbage Collection is process of retrieve the runtime unused memory
automatically. i.e it is a way to destroy the unused objects.
Where as in C language we use free() function and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
1.It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
2.It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
object can be unreferenced by following ways
By nulling the reference
By assigning a reference to another
By nulling a reference:-
Student s1 = new Student(); S1=null;
By assigning a reference to another:-
Emp e1=new Empl(); Emp e2=new Emp();
e1=e2;//now the first object referred by e1 is available for garbage collection
G.Praveen ITDept-SNIST 76
finalize() method:-
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
This method is defined in Object class as:
void finalize()
{
}
gc() method:-
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc()
{
}
G.Praveen ITDept-SNIST 77
ACCESS SPECIFIERS:-The Access Modifiers are used to access the classes,
constructors, methods and fields out side the world , i.e. a class can control what
information or data can be accessible by other classes.
I. Access Modifiers
II. Non-Access Modifiers
G.Praveen ITDept-SNIST 78
a. Default (no value):The default access level is declared by not writing any
access modifier at all. Any class, field, method or constructor that has no
declared access modifier is accessible only by classes in the same package.
b. private: The private (most restrictive) modifiers can be used for members but
cannot be used for classes and Interfaces. Fields, methods or constructors
declared private are strictly controlled, which means they cannot be accessed by
anywhere outside the class
c. protected: The protected fields or methods, cannot be used for classes and
Interfaces. Fields, methods and constructors declared protected in a super-class
can be accessed only by subclasses in other packages. Classes in the same
package can also access protected fields, methods and constructors as well,
even if they are not a subclass of the protected member’s class.
d. public: Members (variables, methods, and constructors) declared public (least
restrictive) within a public class are visible to any class in the Java program,
whether these classes are in the same package or in another package. Below
screen shot shows eclipse view of public class with public members.
G.Praveen ITDept-SNIST 79
Default Access Modifier – (No Keyword) default access modifier means we do not
explicitly declare an access modifier for a class, field, method, etc.
The fields in an interface are implicitly public static final and the methods in an
interface are by default public.
Example:-
Any simple java class program
G.Praveen ITDept-SNIST 80
Private Access Modifier – Private Methods, variables, and constructors that are
declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot
be private. Variables that are declared private can be accessed outside the class, if
public methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides
data from the outside world.
G.Praveen ITDept-SNIST 81
C:\praveen>javac accprivate.java
accprivate.java:23: error: a has private access in A
System.out.println("Value of a is:"+ob.a); ^
1 error
G.Praveen ITDept-SNIST 82
Public Access Modifier – Public class, method, constructor, interface, etc.
declared public can be accessed from any other class. The fields, methods,
blocks declared inside a public class can be accessed from any class belonging
to the Java Universe.
the public class are access is in a different package, and all the public class still
needs to be imported. Because of class inheritance, all public methods and
variables of a class are inherited by its subclasses.
Protected Access Modifier – Protected Variables, methods, and constructors,
which are declared protected in a super class can be accessed only by the
subclasses in other package.
The protected access modifier cannot be applied to class and interfaces.
Methods, fields can be declared protected,
G.Praveen ITDept-SNIST 83
Access Control and Inheritance
The following rules for inherited methods are enforced −
Methods declared public in a super class also must be public in all subclasses.
Methods declared protected in a super class must either be protected or public in
subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.
G.Praveen ITDept-SNIST 84
II. Non-Access Modifiers:-
Java provides a number of non-access modifiers to achieve many other
functionality.
i. static
ii. Final
iii. Abstract
iv. Synchronized
G.Praveen ITDept-SNIST 85
The Static Modifier
Static Variables:- The static keyword is used to create variables that will exist
independently of any instances created for the class. Only one copy of the static
variable exists regardless of the number of instances of the class.
Static variables are also known as class variables. Local variables cannot be
declared static.
Static Methods:- The static keyword is used to create methods that will exist
independently of any instances created for the class.
Static methods do not use any instance variables of any object of the class they are
defined in. Static methods take all the data from parameters and compute something
from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a
dot and the name of the variable or method.
G.Praveen ITDept-SNIST 86
The Final Modifier:-
Final Variables
A final variable can be explicitly initialized only once. A reference variable
declared final can never be reassigned to refer to an different object.
However, the data within the object can be changed. So, the state of the object can
be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a
class variable.
public class Test
{
final int value = 10; // The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue()
{
value = 12; // will give an error
}
}
G.Praveen ITDept-SNIST 87
Final Methods:-
A final method cannot be overridden by any subclasses. As mentioned
previously, the final modifier prevents a method from being modified in a
subclass.
The main intention of making a method final would be that the content of the
method should not be changed by any outsider.
Example
You declare methods using the final modifier in the class declaration, as in the
following example
public class Test
{
public final void changeName()
{
// body of method
}
}
G.Praveen ITDept-SNIST 88
Final Classes:
The main purpose of using a class being declared as final is
to prevent the class from being subclassed. If a class is
marked as final then no class can inherit any feature from the
final class.
G.Praveen ITDept-SNIST 89
The abstract Modifier:-
Abstract Class
An abstract class can never be instantiated. If a class is declared as abstract then
the sole purpose is for the class to be extended.
A class cannot be both abstract and final (since a final class cannot be
extended). If a class contains abstract methods then the class should be declared
abstract. Otherwise, a compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods
EG:-pROG
Abstract Methods
An abstract method is a method declared without any implementation. The
methods body (implementation) is provided by the subclass. Abstract methods
can never be final or strict.
Any class that extends an abstract class must implement all the abstract methods
of the super class, unless the subclass is also an abstract class.
If a class contains one or more abstract methods, then the class must be declared
abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();
EG:-
G.Praveen ITDept-SNIST 90
The Synchronized Modifier:-
The synchronized keyword used to indicate that a method can be accessed by
only one thread at a time. The synchronized modifier can be applied with any
of the four access level modifiers.
public synchronized void showDetails()
{
.......
}
G.Praveen ITDept-SNIST 91
Java has modifiers other than access modifiers they are
static
final
static: static can be used for members of a class. The static members of the
class can be accessed without creating an object of a class.
final: This modifier applicable to class, method, and variables. This modifier
tells the compiler not to change the value of a variable once assigned. If applied
to class, it cannot be sub-classed. If applied to a method, the method cannot be
overridden in sub-class.
Modifier class constructor method Data/variables
G.Praveen ITDept-SNIST 92
Modifier class constructor method Data/variables
static Yes
G.Praveen ITDept-SNIST 93
Recursion:-A method in java that calls itself is called recursive method.
It makes the code compact.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Eg:- public class Receg1 {
static void p(){
System.out.println("SNIST-JAVA");
p();
}
OUTPUT:-
G.Praveen ITDept-SNIST 94
import java.util.*;
class Recfact {
static int fact(int n)
{
if (n == 1)
return 1;
else
return(n * fact(n-1));
}
public static void main(String[] args) {
Scanner s1= new Scanner(System.in);
int n;
System.out.println("Enter any no");
n=s1.nextInt();
System.out.println("Factorial of 5 is: "+fact(n));
} }
OUTPUT:-
C:\praveen>javac Recfact.java
C:\praveen>java Recfact
Enter any no
9
Factorial of 5 is: 362880 G.Praveen ITDept-SNIST 95
import java.util.*;
class Recfib {
static int n1=0,n2=1,n3=0;
static void fib(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
fib(count-1);
} } OUTPUT:-
public static void main(String[] args) C:\praveen>javac Recfib.java
{
Scanner s1= new Scanner(System.in); C:\praveen>java Recfib
int n; Enter any no
System.out.println("Enter any no"); 8
0 1 1 2 3 5 8 13
n=s1.nextInt();
System.out.print(n1+" "+n2);//printing 0 and 1
fib(n-2);//n-2 because 2 numbers are already printed
}}
G.Praveen ITDept-SNIST 96
Difference between object and class:-
There are many differences between object and class. A list of differences between object and
class are
SNo. given below
Object Class
SNO OBJECT CLASS
1) Object is an instance of a class. Class is a blueprint or template from which objects
are created.
2) Object is a real world entity such as Class is a group of similar objects.
CAR,PEN,MOBILE
3) Object is a physical entity. Class is a logical entity.
4) Object is created through new Class is declared using class keyword e.g.
keyword mainly class Student{}
e.g. Student s1=new Student();
5) Object is created many times as per Class is declared once.
requirement.
6) Object allocates memory when it is Class doesn't allocated memory when it is created.
created.
7) There are many ways to create There is only one way to define class in java using
object in java such as new keyword, class keyword.
new Instance() method, clone()
method, factory method and
deserialization.
G.Praveen ITDept-SNIST 97
Java Command Line Arguments:-The java command-line argument is an
argument i.e. passed at the time of running the java program
The arguments passed from the console can be received in the java program and
it can be used as an input, and it provides a convenient way to check the
behavior of the program for the different values. W e can pass N (1,2,3 and so
on) numbers of arguments from the command prompt.
class Cmd
{
public static void main(String ar[])
{
System.out.print(ar[0]);
System.out.print(ar[1]);
System.out.print(ar[2]);
System.out.print(ar[3]);
}}
OUTPUT:-
C:\praveen>java Cmd SREENIDHI INSTITUTE SCIENCE TECHNOLOGY
SREENIDHIINSTITUTESCIENCETECHNOLOGY
G.Praveen ITDept-SNIST 98
class Cmd2 OUTPUT:-
{ C:\praveen>javac Cmd2.java
public static void main(String ar[]) C:\praveen>java Cmd2 2 12 JAVA CLASS
{ 2
int a,b; 12
a=Integer.parseInt(ar[0]); JAVACLASS
b=Integer.parseInt(ar[1]);
System.out.println(a); class Cmd1
System.out.println(b); {
System.out.print(ar[2]); public static void main(String ar[])
System.out.print(ar[3]); { int a,b,c;
}} a=Integer.parseInt(ar[0]);
b=Integer.parseInt(ar[1]);
Output:- System.out.println(a);
C:\praveen>javac Cmd1.java System.out.println(b);
C:\praveen>java Cmd1 12 13 SNIST ITDEPT c=(a+b);
12 System.out.print(ar[2]);
13 System.out.println(ar[3]);
SNISTITDEPT System.out.println("SUM IS:"+c);
SUM IS:25
}}
G.Praveen ITDept-SNIST 99
Java String:- string is basically an object that represents sequence of char values. An
array of characters works same as java string.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
Creating Strings:-
There are two ways to create String object:
1.By string literal
2.By new keyword
1)String Literal:-Java String literal is created by using double quotes.
Eg:- String s1=“SREENIDHI INSTITUTE OF SCIENCE & TECHNOLOGY”;
Each time we create a string literal, the JVM checks the string constant pool first. If
the string already exists in the pool, a reference to the pooled instance is returned. If
string doesn't exist in the pool, a new string instance is created and placed in the pool.
From the above example only one object will be created. Firstly JVM will not find
any string object with the value "SREENIDHI INSTITUTE OF SCIENCE &
TECHNOLOGY" in string constant pool, so it will create a new object. After that it
will find the string with the value "SREENIDHI INSTITUTE OF SCIENCE &
TECHNOLOGY" in the pool, it will not create new object but will return the
reference to the same instance.
G.Praveen ITDept-SNIST 101
Note: String objects are stored in a special memory area known as string constant pool.
Why java uses concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already
in string constant pool).
2.By new keyword:-
String s=new String(“JAVA ");//creates two objects and one reference variable
By using new keyword, JVM will create a new string object in normal(non pool)
heap memory and the literal “JAVA" will be placed in the string constant pool. The
variable s will refer to the object in heap(non pool).
Eg:-
public class Str1{
public static void main(String args[]){
String s1="SNIST";//creating string by java string literal
char ch[]={'I','T','D','E','P','T'};
String s2=new String(ch);//converting char array to string
String s3=new String("JAVA CLASS");//creating java string by new keyword
System.out.println(s1); OUTPUT:-
System.out.println(s2); C:\praveen>java Str1
System.out.println(s3); SNIST
}} ITDEPT
JAVA CLASS
G.Praveen ITDept-SNIST 102
Java String class methods:-The java.lang.String class provides many useful methods to perform
operations on sequence of char values.
From the above example java class(s1) is not changed but a new object is
created with java classis not good . That is why string is known as immutable.
From the above figure that two objects are created but s reference variable still refers to
“Java class" not to “Java class is not good".
But if we explicitely assign it to the reference variable, it will refer to “Java class not good"
object
.For example: above program
class stringcomparison3{
public static void main(String args[]){
String s1="JAVA";
String s2="JAVA"; OUTPUT:-
String s3=new String("JAVA"); C:\praveen>java stringcomparison3
System.out.println(s1==s2); true
System.out.println(s1==s3); false
} }
true (because both refer to same instance)
false(because s3 refers to instance created in nonpool)
Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str, creates StringTokenizer with specified string and
String delim) delimeter.
StringTokenizer(String str, creates StringTokenizer with specified string,
String delim, boolean delimeter and returnValue. If return value is true,
returnValue) delimiter characters are considered to be tokens. If it
is false, delimiter characters serve to separate
tokens.
2) String is slow and consumes more memory when StringBuffer is fast and
you concat too many strings because every time it consumes less memory when
creates new instance. you cancat strings.