SlideShare a Scribd company logo
JAVA PROGRAM
SCION RESEARCH AND DEVELOPMENT
2
SCION RESEARCH AND DEVELOPMENT
language and why we use programming languages.
JAVA
Java Tutorial
It is one of the programming language or technology used for developing web
applications. Using this technology you can develop distributed application. A
Java language developed at SUN Micro Systems in the year 1995 under the
guidance of James Gosling and their team. In other word It is a programming
language suitable for the development of web applications. It is also used for
developing desktop and mobile application. Born
This language was developed at SUN Microsystems in the year 1995 under the
guidance of James Gosling and their team.
Prerequisites
Before learning of This tutorial no need to learn any programming
language like C and C++. But you have knowledge of programming
3
Java is one of the programming language or technology used for developing web
applications. Java language developed at SUN Micro Systems in the year 1995
under the guidance of James Gosling and there team. Originally SUN Micro
Systems is one of the Academic university (Stanford University
SCION RESEARCH AND DEVELOPMENT
Network)
JAV
A
JAVA
Whatever the software developed in the year 1990, SUN Micro Systems has
released on the name of oak, which is original name of java (scientifically oak is
one of the tree name). The OAK has taken 18 months to develop.
The oak is unable to fulfill all requirements of the industry. So James Gosling
again reviews this oak and released with the name of java in the year 1995.
Scientifically java is one of the coffee seed name.
Java divided into three categories, they are
J2SE (Java 2 Standard Edition)
J2EE (Java 2 Enterprise Edition)
J2ME (Java 2 Micro or Mobile Edition)
J2SE - J2SE is used for developing client side
applications.
J2EE - J2EE is used for developing server side
applications.
J2ME - J2ME is used for developing mobile or
wireless application.
4
SCION RESEARCH AND DEVELOPMENT
All versions of java
Java Version SE 7
J2SE 1.2 is called as
Dolphin and it is
released on 28 July,
2011.
Features
• Strings in switch
Statement
• Type Inference for Generic Instance
Creation, Multiple Exception Handling
• Support for Dynamic Languages
• Try with Resources
• Java nio Package
• Binary Literals, underscore in literals
• Diamond Syntax
• Automatic null Handling 5
SCION RESEARCH AND DEVELOPMENT
JAVA VERSIONS
Java Version SE 6
J2SE 1.2 is called as Mustang and it is released on 11 December, 2006.
Features
• Scripting Language Support
• JDBC 4.0 API
• Java Compiler API
• Pluggable Annotations
• Native PKI, Java GSS, Kerberos and LDAP support.
• Integrated Web Services.
• Lot more enhancements.
6
SCION RESEARCH AND DEVELOPMENT
JAVA VERSIONS
J2SE Version 5.0
J2SE 1.2 is called as Tiger and it is released on 30 September, 2004.
Features
• Generics
• Enhanced for Loop
• Auto boxing/Unboxing
• Type safe Enums
• Varargs
• Static Import
• Metadata (Annotations)
• Instrumentation
JAVA VERSIONS
7
SCION RESEARCH AND DEVELOPMENT
J2SE Version 1.4
J2SE 1.2 is called as Merlin and it is released on 6 February, 2002.
Features
• XML Processing
• Java Print Service
• Logging API
• Java Web Start
• JDBC 3.0 API, Assertions
• Preferences API
• Chained Exception
• IPv6 Support
• Regular Expressions
JAVA VERSIONS
• Image I/O API
8
SCION RESEARCH AND DEVELOPMENT
J2SE Version 1.3
J2SE 1.2 is called as Kestrel and it is released on 8 May, 2000.
Features
• Java Sound
• Jar Indexing
• A huge list of enhancements in almost all the java area.
JAVA VERSIONS
9
SCION RESEARCH AND DEVELOPMENT
J2SE Version 1.2
J2SE 1.2 is called as playground and it is released on 8 December, 1998.
Features
• Collections framework.
• Java String memory map for constants.
• Just In Time (JIT) compiler.
• Jar Signer for signing Java Archive (JAR) files.
• Policy Tool for granting access to system resources.
• Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and
Drop, and Java 2D class libraries.
• Java Plug-in
• Scrollable result sets, BLOB, CLOB, batch update, user-defined types in
JDBC.
10
• Audio support in Applets.
SCION RESEARCH AND DEVELOPMENT
JAVA VERSIONS
JDK Version 1.1
JDK 1.1 is released on 19 January, 1997
Features
• JDBC (Java Database connectivity)
• Inner Classes
• Java Beans
• RMI (Remote Method Invocation)
• Reflection(introspection only)
JDK Version 1.0
JDK 1.0 is called as OAK, and it is released on 23 January, 1996.
11
SCION RESEARCH AND DEVELOPMENT
JAVA VERSIONS
Basic Points of Java
Java is a platform independent, more powerful, secure, high
performance, multithreaded programming language. Here we discuss some
points related to Java.
Define byte
Byte code is the set of optimized instructions generated during
compilation phase and it is more powerful than ordinary pointer code.
Define JRE
The Java Runtime Environment (JRE)
is part of the Java
Development Kit(JDK). It contains a set of
libraries and tools for
developing Java application. The Java Runtime Environment
provides the
minimum requirements for executing a Java application
12
JAVA BASIC
Define JVM
JVM is set of programs developed by sun Micro System and supplied as a part
of the JDK for reading line by line of byte code and it converts into a native
understanding form of operating system. The Java language is one of the
compiled and interpreted programming language.
Garbage Collector
The Garbage Collector is the system Java program which runs in the
background along with a regular Java program to collect un-Referenced
(unused) memory space for improving the performance of our applications.
Note: Java programming does not support destructor concept in place of
destructor, we have garbage collector program.
13
SCION RESEARCH AND DEVELOPMENT
JAVA BASIC
Define an API
An API (Application Programming Interface) is a collection of packages, a
package is the collection of classes, interfaces and sub-packages. A sub-
package is a collection of classes, Interfaces and sub packages etc.
Java programming contains user friendly syntax so that we can develop
effective applications. in other words if any language is providing user friendly
syntax, we can develop error free applications.
Definition of JIT
JIT is the set of programs developed by SUN Micro System and added as a
part of JVM, to speed up the interpretation phase.
14
SCION RESEARCH AND DEVELOPMENT
JAVA BASIC
Network based application
Network based application are mainly classified into two types.
1. Centralized Applications
2. Distributed Applications
Centralized
applications
• In this scenario multiple client
system depends on single server
system.
• The major drawback in this
architecture is if any problem
occurred on server system that will
be reflected on every client system.
15
SCION RESEARCH AND DEVELOPMENT
JAVA BASIC
Distributed applications
In this scenario multiple client system are depends on multiple server system
so that even problem occurred in one server will never be reflected on any
client system.
Note: In this architecture same
application is distributed in
multiple server system.
Java is a very powerful
language can be used to
developed both client server
architecture and distributed
architecture based application.
16
SCION RESEARCH AND DEVELOPMENT
JAVA BASIC
17
• Simple
• Platform Independent
• Architectural Neutral
• Portable
• Multi Threading
• Distributed
• Networked
• Robust
• Dynamic
• Secured
• High Performance
• Interpreted
JAVA FEATURES
Features of Java
Features of a language are nothing but the set of services or facilities provided
by the language vendors to the industry programmers. Some important
features of java are;
Important Features of Java
• Object Oriented
SCION RESEARCH AND DEVELOPMENT
Simple
It is simple because of the following factors:
• It is free from pointer due to this execution time of application is
improved. [Whenever we write a Java program without pointers then
internally it is converted into the equivalent pointer program].
• It has Rich set of API (application protocol interface).
• It has Garbage Collector which is always used to collect un-Referenced
(unused) Memory location for improving performance of a Java program. It
contains user friendly syntax for developing any applications.
JAVA FEATURES
18
SCION RESEARCH AND DEVELOPMENT
Platform Independent
A program or technology is said to be platform independent if and only if
which can run on all available operating systems with respect to its
development and compilation. (Platform represents O.S).
JAVA FEATURES
19
SCION RESEARCH AND DEVELOPMENT
Architectural Neutral
Architecture represents processor.
A Language or Technology is said to be Architectural neutral which can run on
any available processors in the real world without considering their
development and compilation.
JAVA FEATURES
The languages like C, CPP are treated as architectural dependent.
20
SCION RESEARCH AND DEVELOPMENT
Portable
If any language supports platform independent and architectural neutral
feature known as portable. The languages like C, CPP, Pascal are treated as non-
portable language. It is a portable language. According to SUN microsystem.
Multithreaded
A flow of control is known as a thread. When any Language executes
multiple thread at a time that language is known as multithreaded e. It is
multithreaded.
21
SCION RESEARCH AND DEVELOPMENT
JAVA FEATURES
Distributed
Using this language we can create distributed applications. RMI and EJB are
used for creating distributed applications. In distributed application multiple
client system depends on multiple server systems so that even problem
occurred in one server will never be reflected on any client system.
Note: In this architecture
same
22
SCION RESEARCH AND DEVELOPMENT
application is
distributed in multiple
server system.
JAVA FEATURES
Networked
It is mainly designed for web based applications, J2EE is used for
developing network based applications.
Robust
Simply means of Robust are strong. It is robust or strong Programming
Language because of its capability to handle Run-time Error, automatic garbage
collection, the lack of pointer concept, Exception Handling. All these points
make It robust Language.
Secure
It is a more secure language compared to other language; In this language,
all code is covered in byte code after compilation which is not readable by
23
human.
SCION RESEARCH AND DEVELOPMENT
JAVA FEATURES
Dynamic
It supports Dynamic memory allocation due to this memory wastage is reduce
and improve performance of the application. The process of allocating the
memory space to the input of the program at a run-time is known as dynamic
memory allocation, To programming to allocate memory space by dynamically
we use an operator called 'new' 'new' operator is known as dynamic memory
allocation operator.
Interpreted
It is one of the highly interpreted programming languages.
Object Oriented
It supports OOP's concepts because of this it is most secure language, for
24
this topic you can read our oop's concepts in detail.
SCION RESEARCH AND DEVELOPMENT
JAVA FEATURES
High performance
• It have high performance because of following reasons;
• This language uses Byte code which is faster than ordinary pointer code so
Performance of this language is high.
• Garbage collector, collect the unused memory space and improve the
performance of the application.
• It has no pointers so that using this language we can develop an
application very easily.
• It support multithreading, because of this time consuming process can be
reduced to executing the program.
25
SCION RESEARCH AND DEVELOPMENT
JAVA FEATURES
SET PATH
How to Set Path and Classpath in Java
Setting path and classpath in Java is very simple but before do this process you
need to know about path variable and classpath variable. Here I will show you
how to set path and classpath in Java in very simple and easy way.
Path Variable
Path variable is set for providing path for all Java tools like java, javac, javap,
javah, jar, applet viewer which are used in java programming. All these tools are
available in bin folders so we set path up to bin folders.
Classpath Variable
Classpath variable is set for providing a path for predefined Java classes
which is used in our application. All classes are available in lib/rt.jar so we
set classpath upto lib/rt.jar.
26
SCION RESEARCH AND DEVELOPMENT
SET PATH
JDK Folder Hierarchy
27
SCION RESEARCH AND DEVELOPMENT
Why set path ?
The following programming error is generally for all Java programmers when
they compile any Java program.
'javac' is not recognized as an internal or external command, operable
program or batch file.
When you get this type of error, then your operating system cannot find the
Java compiler (javac). To solve this error you need to set the PATH variable.
Javac is a tool which is available in bin folder so you must set the PATH upto
bin folder. In a bin folder all tools are available like javap, javah, jar, javac,
java, appletviewer etc. All these tools are used for different- different purpose.
28
SCION RESEARCH AND DEVELOPMENT
SET PATH
SET PATH
29
SCION RESEARCH AND DEVELOPMENT
set the path and classpath
Go on my computer icon and right click, after that click on properties
option.
SET PATH
30
SCION RESEARCH AND DEVELOPMENT
SET PATH
Now click on advance setting
31
SCION RESEARCH AND DEVELOPMENT
Click on advance Click on Environment variables
SET PATH
32
SCION RESEARCH AND DEVELOPMENT
Now one dialog box is appear,
now ignore this but do not close.
SET PATH
Click on new button which is below the first box.
33
SCION RESEARCH AND DEVELOPMENT
SET PATH
Now open my computer open c:/ > Programs Files > java > java1.6.0 > bin
copy this path
34
SCION RESEARCH AND DEVELOPMENT
SET PATH
Now come back on previous open dilogbox and write variable name 'path' and
for variable value paste all copied path up to the bin folder. Put .; at the end. It
(.) selects all the tools from the bin folder.
35
SCION RESEARCH AND DEVELOPMENT
Now open my computer open c:/ > Programs Files > java > java1.6.0 > jre >
lib > rt.jar copy this path
Note: rt.jar is available in lib folder this jar files contains all classes of jdk.
SET PATH
36
SCION RESEARCH AND DEVELOPMENT
Note: Finally after set classpath
Restart your system, or you can re-
open command prompt. 37
SCION RESEARCH AND DEVELOPMENT
SET PATH
Now again come back on Environment variable dilogbox and click on new. Now
one box is open and write path variable as 'classpath' and for variable value
paste all copied paths upto rt.jar. Put .; at the end. It (.) selects all the classes
from lib folder.
Path classpath
path variable is set for providing path for all
java tools like java, javac, javap, javah, jar,
appletviewer
classpath variable is set for provide path of all
java classes which is used in our application.
38
SCION RESEARCH AND DEVELOPMENT
SET PATH
Difference between path and classpath in Java
• Path - Path variable is set for providing path for all Java tools like java,
javac, javap, javah, jar, appletviewer. In Java to run any program we use java
tool and for compile Java code use javac tool. All these tools are available in
bin folder so we set path upto bin folder.
• Classpath - classpath variable is set for providing path of all Java classes
which is used in our application. All classes are available in lib/rt.jar so we
set classpath upto lib/rt.jar.
SET PATH
JDK Folder Hierarchy
39
SCION RESEARCH AND DEVELOPMENT
All the tools are present in bin folder so we set path upto bin folder.
40
SCION RESEARCH AND DEVELOPMENT
SET PATH
Path variable is set for use all the tools like java, javac, javap, javah, jar,
appletviewer etc.
Example
"C:Program FilesJavajdk1.6.0bin"
SET PATH
Classpath variable is used to set the path for all classes which is used in our
program so we set classpath upto rj.jar. in rt.jar file all the .class files are
present. When we decompressed rt.jar file we get all .class files.
Example
"C:Program FilesJavajre1.6.0jrelibrt.jar" In above rt.jar is a jar file
where all the .class files are present so we set the classpath upto rt.jar.
41
SCION RESEARCH AND DEVELOPMENT
FIRST JAVA PROGRAM
First Java Program
Requirements for java Program
For executing any java program we
need given things.
• Install the JDK any version if
you don't have installed it.
• Set path of the jdk/bin directory.
• Create the java program
• Compile and run the java
program
Steps For compiling and
executing the java program
• Java is very simple programming language first we write a java program and
save it with program class name.
• In below program we create a java program with "First" name so we
save this program with "First.java" file name. We can save our java
program anywhere in our system or computer.
42
SCION RESEARCH AND DEVELOPMENT
Create First program
Example
class First{
public static void main(String[] args)
{
System.out.println("Hello Java");
System.out.println("My First Java Program");
} }
Compile and Execute Java Code
To compile: javac First.java
To execute: java First
Output
Hello Java
FIRST JAVA PROGRAM
43
My First Java Program
SCION RESEARCH AND DEVELOPMENT
Save Java Program
Syntax: Filename.java
Example: First.java
Compile Java Program
Syntax: Javac
Filename.java
Example: Javac First.java
44
SCION RESEARCH AND DEVELOPMENT
Note: Here Javac and Java are called tools or application programs or exe files
developed by sun micro system and supply as a part of jdk 1.5/1.6/1.7 in bin
folder. Javac is used for compile the java program and java is used for run the
java program.
FIRST JAVA PROGRAM
FIRST JAVA PROGRAM
During the program execution internally following steps will be
occurs.
• Class loader subsystem loads or transfer the specified class into main
memory(RAM) from secondary memory(hard disk)
• JVM takes the loaded class
• JVM looks for main method because each and every java program start
executing from main() method.
• Since main() method of java is static in nature, JVM call the main() method
with respect to loaded class (Example: First as First.main(--))
• Note: A java program can contain any number of main method but JVM start
execution from that main() method which is taking array of object of
String class.
45
SCION RESEARCH AND DEVELOPMENT
The java launcher tool then runs your application with an instance of the
46
Java Virtual Machine (JVM).
SCION RESEARCH AND DEVELOPMENT
FIRST JAVA PROGRAM
Compile and Run Java Program
In the Java programming language, all source code is first written in plain text
files and save with the .java extension. After compilation, .class files are
generated by javac compiler. A .class file does not contain code that is native to
your processor; it instead contains bytecodes (it is machine language of the
Java Virtual Machine1 (JVM)).
FIRST JAVA PROGRAM
Steps For compile Java Program
First Save Java program with same as
class name with .java extension.
Example: Sum.java
Compile: javac Filename.java
Example: javac Sum.java
Note: Here javac is tools or application
programs or exe files which is used for
Compile the Java program.
Steps For Run Java Program - For run java program use java tool.
Run by: java Filename , Example: java sum
Note: Here java is tools or application programs or exe files which is used
47
for run the Java program.
SCION RESEARCH AND DEVELOPMENT
FIRST JAVA PROGRAM
Steps For compiling and executing the java program
The following sequence of steps represented in the diagram use compiling the
java program and executing the java programs.
In the above diagram javac and
java are called tools or
application programs or exe
files developed by sun micro
system and supply as a part of
jdk 1.5/1.6/1.7 in bin folder
(starting directory of java is
called java home directory).
48
SCION RESEARCH AND DEVELOPMENT
DIFFERENCE B/W JDK,JVM, & JRE
Difference between JDK, JVM and JRE
JVM, JRE, JDK these all the backbone of java language. Each components have
separate works. JDK and JRE physically exists but JVM are abstract machine it
means it not physically exists.
49
SCION RESEARCH AND DEVELOPMENT
JVM
JVM (Java Virtual Machine) is a software. It is a specification that provides
runtime environment in which java bytecode can be executed. It not physically
exists. JVMs are not same for all hardware and software, for example for
window os JVM is different and for Linux VJM is different. JVM, JRE and JDK
are platform dependent because configuration of each OS differs. But, Java is
platform independent.
JRE
The Java Runtime Environment (JRE) is part of the Java Development Kit
(JDK). It contains set of libraries and tools for developing java application.
The Java Runtime Environment provides the minimum requirements for
executing a Java application. It physically exists. It contains set of libraries +
50
other files that JVM uses at runtime.
SCION RESEARCH AND DEVELOPMENT
DIFFERENCE B/W JDK,JVM, & JRE
JDK
The Java Development Kit (JDK) is primary components. It physically exists.
It is collection of programming tools and JRE, JVM.
DIFFERENCE B/W JDK,JVM, & JRE
51
SCION RESEARCH AND DEVELOPMENT
JVM ARCHITECTURE
JVM Architecture in Java
JVM (Java Virtual Machine) is a software. It is a specification that provides
Runtime environment in which java bytecode can be executed.
52
SCION RESEARCH AND DEVELOPMENT
Operation of JVM
JVM mainly performs following operations.
• Allocating sufficient memory space for the class properties.
• Provides runtime environment in which java byte code can be executed
• Converting byte code instruction into machine level instruction.
• JVM is separately available for every Operating System while installing java
software so that JVM is platform dependent.
Note: Java is platform Independent but JVM is platform dependent because
every Operating system have different-different JVM which is install along with
JDK Software.
Class loader subsystem:
Class loader subsystem will load the .class file into java stack and later
sufficient memory will be allocated for all the properties of the java
53
program into following five memory locations.
SCION RESEARCH AND DEVELOPMENT
JVM ARCHITECTURE
• Heap area
• Method area
• Java stack
• PC register
• Native stack
Heap area: - In which object references will be stored.
Method area - In which static variables non-static and static method will be
stored.
Java Stack - In which all the non-static variable of class will be stored and
whose address referred by object reference.
Pc Register
Which holds the address of next executable instruction that means that use
the priority for the method in the execution process?
54
SCION RESEARCH AND DEVELOPMENT
JVM ARCHITECTURE
Native Stack
Native stack holds the instruction of native code (other than java code) native
stack depends on native library. Native interface will access interface between
native stack and native library.
Execution Engine
Which contains Interpreter and JIT compiler whenever any java program is
executing at the first time interpreter will comes into picture and it converts
one by one byte code instruction into machine level instruction JIT compiler
(just in time compiler) will comes into picture from the second time onward if
the same java program is executing and it gives the machine level instruction to
the process which are available in the buffer memory.
Note: The main aim of JIT compiler is to speed up the execution of java
program.
55
SCION RESEARCH AND DEVELOPMENT
JVM ARCHITECTURE
JVM ARCHITECTURE
What is JIT and Why use JIT
• JIT is the set of programs developed by SUN Micro System and added as a
part of JVM, to speed up the interpretation phase.
• In the older version of java compilation phase is so faster than
interpretation phase. Industry has complained to the SUN Micro System
saying that compilation phase is very faster and interpretation phase is very
slow.
• So solve this issue, SUN Micro System has developed a program called JIT
(just in time compiler) and added as a part of JVM to speed up the
interpretation phase. In the current version of java interpretation phase is
so faster than compilation phase. Hence java is one of the highly
interpreted programming languages.
56
SCION RESEARCH AND DEVELOPMENT
Object and class in Java
Object is the physical as well as logical entity where as class is the only logical
entity.
Class: Class is a blue print which is containing only list of variables and
method and no memory is allocated for them. A class is a group of objects
that has common properties.
A class in java contains:
• Data Member
• Method
• Constructor
• Block
• Class and Interface 57
SCION RESEARCH AND DEVELOPMENT
OOPS CONCEPT
OOPS CONCEPT
Object: Object is a instance of class, object has state and behaviors.
An Object in java has three characteristics:
• State
• Behavior
• Identity
State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit,
withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But, it is used internally by
the JVM to identify each object uniquely.
Class is also can be used to achieve user defined data types.
58
SCION RESEARCH AND DEVELOPMENT
OOPS CONCEPT
Real life example of object and class
In real world many examples of object and class like dog, cat, and cow are
belong to animal's class. Each object has state and behaviors.
For example a dog has state:- color, name, height, age as well as
behaviors:- barking, eating, and sleeping.
59
SCION RESEARCH AND DEVELOPMENT
Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also
different states and behaviors.
For Example car has state - color, name, model, speed, Mileage. as we;; as
behaviors - distance travel
OOPS CONCEPT
60
SCION RESEARCH AND DEVELOPMENT
Class Object
1
Class is a container which
collection of variables and
methods.
object is a instance of class
2
No memory is allocated at the
time of declaration
Sufficient memory space will be
allocated for all the variables of class
at the time of declaration.
3
One class definition should exist
only once in the program.
For one class multiple objects can be
created.
61
method; }
SCION RESEARCH AND DEVELOPMENT
Syntax to declare a Class
class Class_Name {
data member;
OOPS CONCEPT
Difference between Class and Object in Java
OOPS CONCEPT
Simple Example of Object and Class
In this example, we have created a Employee class that have two data members
eid and ename. We are creating the object of the Employee class by new
keyword and printing the objects value.
package sample;
public class Program1 {
int eid; // data member (or instance variable) String
ename; // data member (or instance variable)
{
eid=101;
ename="Hitesh";
}
public static
void main(String
args[]){
62
Program1 e=new Program1();
SCION RESEARCH AND DEVELOPMENT
OOPS CONCEPT
// Creating an object of class Employee
System.out.println("Employee ID: "+e.eid);
System.out.println("Name: "+e.ename);
}
}
OUTPUT:
Employee ID: 101
Name: Hitesh
Note: A new keyword is used to allocate memory at runtime, new keyword is
used for create an object of class, later we discuss all the way for create an
object of class.
63
SCION RESEARCH AND DEVELOPMENT
Data Type in Java
Data type is a special keyword used to allocate sufficient memory space for
the data, in other words Data type is used for representing the data in main
memory (RAM) of the computer.
In general every programming language is containing three categories of
data types. They are
• Fundamental or primitive data types
• Derived data types
• User defined data types.
DATA TYPE IN JAVA
64
SCION RESEARCH AND DEVELOPMENT
Primitive data types
• Primitive data types are those whose variables allows us to store only one
value but they never allows us to store multiple values of same type.
• This is a data type whose variable can hold maximum one value at a
time.
Example
int a; // valid
a=10; // valid
a=10, 20, 30; //
invalid
Here "a" store
only one value
at a time
because it is
primitive type
variable.
65
SCION RESEARCH AND DEVELOPMENT
DATA TYPE IN JAVA
Derived data types
• Derived data types are those whose variables allow us to store multiple
values of same type. But they never allows to store multiple values of
different types.
• These are the data type whose variable can hold more than one value of
similar type. In general derived data type can be achieve using array.
Example
int a[] = {10,20,30}; // valid
int b[] = {100, 'A', "ABC"}; // invalid
Here derived data type store only same type of data at a time not store integer,
character and string at same time.
66
SCION RESEARCH AND DEVELOPMENT
DATA TYPE IN JAVA
User defined data types
• User defined data types are those which are developed by programmers by
making use of appropriate features of the language.
• User defined data types related variables allows us to store multiple
values either of same type or different type or both. This is a data type
whose variable can hold more than one value of dissimilar type, in java it is
achieved using class concept.
Note: In java both derived and user defined data type combined name as
reference data type.
In C language, user defined data types can be developed by using struct,
union, enum etc. In java programming user defined datatype can be
developed by using the features of classes and interfaces.
67
SCION RESEARCH AND DEVELOPMENT
DATA TYPE IN JAVA
Example
Student s = new Student(); In java we have eight data type which are
organized in four groups. They are
Integer category data types
Character category data types
Float category data types
Boolean category data types
68
SCION RESEARCH AND DEVELOPMENT
DATA TYPE IN JAVA
Integer category data types
SCION RESEARCH AND DEVELOPMENT
These category data types are used for storing integer data in the main
memory of computer by allocating sufficient amount of memory space.
Integer category data types are divided into four types which are given in
following table Data Type Size Range
1 Byte 1 + 127 to -128
2 Short 2 + 32767 to -32768
3 Int 4 + x to - (x+1)
4 Long 8 + y to - (y+1)
Character category data types
A character is an identifier which is enclosed within single quotes. In java to
represent character data, we use a data type called char. This data type takes
two byte since it follows Unicode character set.
69
Data Type Size(Byte) Range
Char 2 232767 to -32768
DATA TYPE IN JAVA
Data Type Size Range Number of decimal places
70
Float 4 +2147483647 to -2147483648 8
Double 8 + 9.223*1018 16
SCION RESEARCH AND DEVELOPMENT
DATA TYPE IN JAVA
Why Java take 2 byte of memory for store character ?
Java support more than 18 international languages so java take 2 byte for
characters, because for 18 international language 1 byte of memory is not
sufficient for storing all characters and symbols present in 18 languages. Java
supports Unicode but c support ascii code. In ascii code only English language
are present, so for storing all English latter and symbols 1 byte is sufficient.
Unicode character set is one which contains all the characters which are
available in 18 international languages and it contains 65536 characters
Float category data types
Float category data type are used for representing float values. This category
contains two data types, they are in the given table
Boolean category data types
Boolean category data type is used for representing or storing logical values is
true or false. In java programming to represent Boolean values or logical values,
we use a data type called Boolean.
Why Boolean data types take zero byte of memory ?
Boolean data type takes zero bytes of main memory space because Boolean
data type of java implemented by Sun Micro System with a concept of flip -
flop. A flip - flop is a general purpose register which stores one bit of
information (one true and zero false).
Note: In C, C++ (Turbo) Boolean data type is not available for representing true
false values but a true value can be treated as non-zero value and false
values can be represented by zero
71
SCION RESEARCH AND DEVELOPMENT
DATA TYPE IN JAVA
Data Type Default Value Default size
boolean False 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
72
SCION RESEARCH AND DEVELOPMENT
DATA TYPE IN JAVA
Syntax
Variable_name = value;
73
SCION RESEARCH AND DEVELOPMENT
VARIABLE DECLARATION IN JAVA
Variable Declaration Rules in Java
Variable is an identifier which holds data or another one variable is an
identifier whose value can be changed at the execution time of program.
Variable is an identifier which can be used to identify input data in a program.
VARIABLE DECLARATION IN JAVA
Rules to declare a Variable
• Every variable name should start with either alphabets or underscore ( _ ) or
dollar ( $ ) symbol.
• No space are allowed in the variable declarations.
• Except underscore ( _ ) no special symbol are allowed in the middle of
variable declaration
• Variable name always should exist in the left hand side of assignment
operators.
• Maximum length of variable is 64 characters.
• No keywords should access variable name.
Note: Actually a variable also can start with ¥,¢, or any other currency sign.
74
SCION RESEARCH AND DEVELOPMENT
Example of Variable Declaration
class Sum
{
public static void main(String[] args)
{
int _a, ¢b, ¥c, $d, result;
_a=10;
¢b=20;
¥c=30;
$d=40; result=_a+
¢b+¥c+$d;
System.out.println("S
um is :" +result);
}
Output
Sum is : 100
VARIABLE DECLARATION IN JAVA
75
}
SCION RESEARCH AND DEVELOPMENT
Variable initialization
It is the process of storing user defined values at the time of allocation of
memory space.
VARIABLE DECLARATION IN JAVA
Variable declarations
In which sufficient memory will be allocated and holds default values.
Syntax
Datatype variable_name;
byte b1;
76
SCION RESEARCH AND DEVELOPMENT
Syntax
int a= 100;
int b;
b = 25; //
------>
direct
assigned
variable
b = a; //
------>
VARIABLE DECLARATION IN JAVA
Variable assignment
Value is assigned to a variable if that is already declared or initialized.
Syntax
Variable_Name = value
int a = 100;
77
SCION RESEARCH AND DEVELOPMENT
Operators in Java
Operator is a special symbol that tells the compiler to perform specific
mathematical or logical Operation. Java supports following lists of operators.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Ternary or Conditional Operators
OPERATORS IN JAVA
78
SCION RESEARCH AND DEVELOPMENT
Arithmetic Operators
Given table shows all the
and B hold 3.
79
SCION RESEARCH AND DEVELOPMENT
Arithmetic
supported
Language.
operator
by Java
Lets suppose
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
variable A hold 8 and B
hold 3.
Relational Operators
Which can be used to check
the Condition, it always
return true or false. Lets
suppose variable A hold 8
Operators Example (int A=8, B=3) Result
< A<B False
<= A<=10 True
> A>B True
>= A<=B False
== A== B False
!= A!=(-4) True
OPERATORS IN JAVA
Logical Operator
Which can be used to combine more than one Condition?. Suppose you want to
combined two conditions A<B and B>C, then you need to use Logical
Operator like (A<B) && (B>C). Here && is Logical Operator
80
SCION RESEARCH AND DEVELOPMENT
Truth table of Logical Operator
Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True
C1 C2 C1 && C2 C1 || C2 !C1 !C2
T T T T F F
T F F T F T
F T F T T F
F F F F T T
OPERATORS IN JAVA
Assignment operators
Which can be used to assign a value to a variable. Lets suppose variable A
hold 8 and B hold 3.
81
SCION RESEARCH AND DEVELOPMENT
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
=a=b Value of b will be assigned to a
Ternary operator
If any operator is used on three operands or variable is known as ternary
operator. It can be represented with " ?: "
OPERATORS IN JAVA
STRUCTURE OF JAVA PROGRAM
Structure of Java Program
• Structure of a java program is the standard format released by Language
developer to the Industry programmer.
• Sun Micro System has prescribed the following structure for the java
programmers for developing java application.
82
SCION RESEARCH AND DEVELOPMENT
STRUCTURE OF JAVA PROGRAM
• A package is a collection of classes, interfaces and sub-packages. A sub
package contains collection of classes, interfaces and sub-sub packages etc.
java.lang.*; package is imported by default and this package is known as default
package.
• Class is keyword used for developing user defined data type and every java
program must start with a concept of class.
"ClassName" represent a java valid variable name treated as a name of the
class each and every class name in java is treated as user-defined data type.
• Data member represents either instance or static they will be selected based
on the name of the class.
• User-defined methods represents either instance or static they are meant
for performing the operations either once or each and every time.
• Each and every java program starts execution from the main() method. And
83
hence main() method is known as program driver.
SCION RESEARCH AND DEVELOPMENT
STRUCTURE OF JAVA PROGRAM
• Since main() method of java is not returning any value and hence its return
type must be void.
• Since main() method of java executes only once throughout the java program
execution and hence its nature must be static.
• Since main() method must be accessed by every java programmer and
hence whose access specifies must be public.
•Each and every main() method of java must take array of objects of String.
Block of statements represents set of executable statements which are in
term calling user-defined methods are containing business-logic.
The file naming conversion in the java programming is that which-ever class is
containing main() method, that class name must be given as a file
name with an extension .java.
84
SCION RESEARCH AND DEVELOPMENT
MAIN() METHOD IN JAVA
Main() Method in Java
main() method is starting execution block of a java program or any java
program start their execution from main method. If any class contain main()
method known as main class.
Syntax of main() method:
Syntax
public static void main(String args[])
{
.......
.......
}
85
SCION RESEARCH AND DEVELOPMENT
Public
public is a keyword in a java language whenever if it is preceded by main()
method the scope is available anywhere in the java environment that means
main() method can be executed from anywhere. main() method must be
accessed by every java programmer and hence whose access specifier must be
public.
Static
static is a keyword in java if it is preceded by any class properties for that
memory is allocated only once in the program. Static method are executed only
once in the program. main() method of java executes only once throughout the
java program execution and hence it declare must be static.
86
SCION RESEARCH AND DEVELOPMENT
MAIN() METHOD IN JAVA
Void
void is a special data type also known as no return type, whenever it is
preceded by main() method that will be never return any value to the
operating system. main() method of java is not returning any value and hence
its return type must be void.
String args[]
String args[] is a String array used to hold command line arguments in the
form of String values.
In case of main() method following changes are acceptable
1. We can declare String[] in any valid form.
• String[] args
• String args[]
• String []args
87
SCION RESEARCH AND DEVELOPMENT
MAIN() METHOD IN JAVA
2. Instance of String[] we can take var-arg String parameter is String...
Syntax
main(String[] args) --> main(String... args)
3.We can change the order of modifiers i.e Instead of
Syntax
public static we can take static public
4. Instead of args we can take any valid java identifier.
Syntax
public static void main(String a[])
88
SCION RESEARCH AND DEVELOPMENT
MAIN() METHOD IN JAVA
89
Example of override main() method
public class mainclass
{
public static void main(String[] args)
{
System.out.println("Execution starts from
Main()");
}
void main(int args)
System.out.println("Override main()");
}
double main(int i, double d)
{
System.out.println("Override main()");
return d;
}
}
Output
Execution starts from Main()
SCION RESEARCH AND DEVELOPMENT
MAIN() METHOD IN JAVA
We can overload main() method ?
Yes, We can overload main() method. A Java class can have any number of
main() methods. But run the java program, which class should have main()
method with signature as "public static void main(String[] args). If you do any
modification to this signature, compilation will be successful. But, not run the
java program. we will get the run time error as main method not found.
COMMAND LINE
Command Line Arguments in Java
If any input value is passed through the command prompt at the time of
running of the program is known as command line argument by default
every command line argument will be treated as string value and those are
stored in a string array of main() method.
Syntax for Compile and Run CMD programs
Compile By -> Javac Mainclass.java
Run By -> Java Mainclass value1 value2 value3 ....................
90
SCION RESEARCH AND DEVELOPMENT
COMMAND LINE
Program Command Line Argument in Java
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Argument is: "+args[0]);
}
}
Compile and Run above programs
Compile By > Javac CommandLineExample.java
Run By > Java CommandLineExample Porter
Output
Argument is: Porter
91
SCION RESEARCH AND DEVELOPMENT
COMMAND LINE
Example of command-line argument in java
class SumDemo
{
public static void main(String args[])
{
System.out.println("Sum: "+args[0]);
}
}
Compile and Run above programs
Compile By > Javac SumDemo.java
Run By > Java SumDemo
10 20
Output
92
Sum: 30
SCION RESEARCH AND DEVELOPMENT
COMMAND LINE
• When the above statement is executing the following sequence of steps will
take place.
• Class loader sub-system loads SumDemo along with Command line
argument(10, 20) and in main memory.
• JVM takes the loaded class SumDemo along
• with Command line arguments (10, 20) and place the number of values in
the length variable that is 2.
• JVM looks for main() that is JVM will place the Command in the main() in
the form of string class that is.
• Hence all the CMD line arguments of Java are sending to main() method
available in the form of an array of object of String class (every CMD are
available or stored in main method in the form of an array of object of
String class). JVM calls the main() method with respect to load class
93
SumDemo that is SumDemo.main().
SCION RESEARCH AND DEVELOPMENT
Accept command line arguments and display their values
class CMD
{
public static void main(String k[])
{
System.out.println("no. of arguments ="+k.length);
for(int i=0;i< k.length;i++)
{
System.out.println(k[i]);
}
}
}
Note: Except + operator
any numeric
operation
not allowed in command
line arguments.
94
SCION RESEARCH AND DEVELOPMENT
COMMAND LINE
class squareDemo
{ int no, result;
void square(String
s) {
int no=Integer.parseInt(s);
result=no*no;
System.out.println("Square: " +result);
} }
class CMD {
public static void main(String args[])
{ System.out.println("no of arguments:
"+args.length);
squareDemo obj=new squareDemo();
obj.square(args[0]);
} }
95
SCION RESEARCH AND DEVELOPMENT
COMMAND LINE
Square of Number by reading value from command prompt.
System.out.println() in Java
In java language print() and println() are the predefined non-static method
of printStream class used to display value or message either in the same line or
line by line respectively. PrintStream class is having fixed object reference in the
System class (existing as a static properties) so that either print() or println()
method can be called with following syntax..
PRINT LINE
96
SCION RESEARCH AND DEVELOPMENT
Syntax
System.out.print("--------------");
System.out.println("------------");
/* "out" is Object reference of printStream class existing in system class as
a static property. */
97
SCION RESEARCH AND DEVELOPMENT
Example
class PrintStream {
println() { //-----------> non-static
........
}
//-----------> non-static
print() {
........
} }
class System
{
Static PrintStream out;
Static PrintStream err;
}
PRINT LINE
Examples of SOP Statements
Example
System.out.println("Hello"); // ---------> Hello
int x=10, y=20;
System.out.println("x");
System.out.println(x);
// ---------> x
// ---------> 10
System.out.println("Hello"+x);
System.out.println(x+y);
System.out.println(x+y+"Hello");
// ---------> Hello10
// ---------> 30
// ---------> 1020Hello
Example
class Hello {
public static void main(String arg[]) {
System.out.println("Hello word");
Output
Hello Word
PRINT LINE
98
} }
SCION RESEARCH AND DEVELOPMENT
DECISION MAKING STMT
Decision Making Statement in Java
Decision making statement statements is also called selection statement.
That is depending on the condition block need to be executed or not which is
decided by condition. If the condition is "true" statement block will be
executed, if condition is "false" then statement block will not be executed. In
java there are three types of decision making statement.
• if
• if-else
• switch
if-then Statement
if-then is most basic statement of Decision making
statement. It tells to program to execute a certain part
of code only if particular condition is true. 99
SCION RESEARCH AND DEVELOPMENT
Syntax
if(condition)
{
Statement(s)
}
Example if statement
class Hello {
int a=10;
public static void main(String[] args)
{ if(a<15) {
System.out.println("Hello good
morning!");
Hello good morning
100
}
SCION RESEARCH AND DEVELOPMENT
}
}
Output
DECISION MAKING STMT
if-else statement
In general it can be used to execute one block of statement among two blocks,
in java language if and else are the keyword in java.
Syntax
if(condition)
{
Statement(s)
}
else
{
Statement(s)
}…
101
SCION RESEARCH AND DEVELOPMENT
DECISION MAKING STMT
In the above syntax whenever condition is true all the if block statement are
executed, remaining statement of the program by neglecting. If the condition is
false else block statement executed and neglecting if block
statements.
102
SCION RESEARCH AND DEVELOPMENT
DECISION MAKING STMT
Example if else
import java.util.Scanner;
class Oddeven {
public static void
main(String[] args){
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter any number :");
no=s.nextInt();
if(no%2==0)
{ System.out.println("Even
number");
}
else {
System.out.println("Odd number");
Output
Enter any number :
10
Even number
DECISION MAKING STMT
103
} } }
SCION RESEARCH AND DEVELOPMENT
Switch Statement
The switch statement in java language is used to execute the code from
multiple conditions or case. It is same like if else-if ladder statement.
A switch statement work with byte, short, char and int primitive data type,
it also works with enumerated types and string.
Syntax
switch(expression/variable)
{ case value:
//statements
// any number of case statements
break; //optional
default: //optional
//statements
104
}
SCION RESEARCH AND DEVELOPMENT
SWITCH STATEMENT
Rules for apply switch statement
With switch statement use only byte, short, int, char data type (float data type
is not allowed). You can use any number of case statements within a switch.
Value for a case must be same as the variable in switch.
Limitations of switch statement
Logical operators cannot be used with switch statement. For instance
Example
SWITCH STATEMENT
105
case k>=20: // not allowed
SCION RESEARCH AND DEVELOPMENT
Example of switch case
import java.util.*;
class switchCase {
public static void
main(String
arg[]) {
int ch;
System.out.println("Enter any number (1 to 7) :");
Scanner s=new Scanner(System.in); ch=s.nextInt();
switch(ch) {
case 1: System.out.println("Today is Monday");
break;
case 2: System.out.println("Today is Tuesday");
break;
106
SCION RESEARCH AND DEVELOPMENT
SWITCH STATEMENT
Output
Enter any number (1 to 7) :
5
SWITCH STATEMENT
case 3: System.out.println("Today is Wednesday");
break;
case 4: System.out.println("Today is Thursday");
break;
case 5: System.out.println("Today is Friday");
break;
case 6: System.out.println("Today is Saturday");
break;
case 7: System.out.println("Today is Sunday"); default:
System.out.println("Only enter value 1 to 7");
} } }
Today is Friday 107
SCION RESEARCH AND DEVELOPMENT
LOOPING STATEMENT
Looping Statement in Java
Looping statement are the statements execute one or more statement
repeatedly several number of times. In java programming language there are
three types of loops; while, for and do-while.
Why use loop ?
When you need to execute a block of code several number of times then you
need to use looping concept in Java language.
Advantage with looping statement
• Reduce length of Code
• Take less memory space.
• Burden on the developer is reducing.
• Time consuming process to execute the program is reduced.
108
SCION RESEARCH AND DEVELOPMENT
LOOPING STATEMENT
Difference between conditional and looping statement
Conditional statement executes only once in the program where as looping
statements executes repeatedly several number of time.
While loop
In while loop first check the condition if condition is true then control goes
inside the loop body otherwise goes outside of the body. while loop will be
repeats in clock wise direction
Syntax
while(condition)
{
Statement(s)
Increment / decrements (++ or --);
} 109
SCION RESEARCH AND DEVELOPMENT
Example while loop
class whileDemo {
public static void main(String args[])
{ int i=0;
while(i<5)
{ System.out.println(+i
); i++;
}
Output
0
1
2
3
LOOPING STATEMENT
4 110
SCION RESEARCH AND DEVELOPMENT
for loop
for loop is a statement which allows code to be repeatedly executed. For
loop contains 3 parts Initialization, Condition and Increment or
Decrements
Syntax
for ( initialization; condition; increment )
{
statement(s);
}
LOOPING STATEMENT
111
SCION RESEARCH AND DEVELOPMENT
• Initialization: This step is execute first and this is execute only once when
we are entering into the loop first time. This step is allow to declare and
initialize any loop control variables.
• Condition: This is next step after initialization step, if it is true, the body of
the loop is executed, if it is false then the body of the loop does not execute
and flow of control goes outside of the for loop.
• Increment or Decrements: After completion of Initialization and
Condition steps loop body code is executed and then Increment or
Decrements steps is execute. This statement allows to update any loop
LOOPING STATEMENT
112
control variables.
SCION RESEARCH AND DEVELOPMENT
Control flow of for loop
• First initialize the variable
• In second step check condition
• In third step control goes inside loop body and execute.
• At last increase the value of variable
113
• Same process is repeat until condition not false.
SCION RESEARCH AND DEVELOPMENT
LOOPING STATEMENT
LOOPING STATEMENT
Display any message exactly 5 times.
Example of for loop
class Hello {
public static void main(String args[]) {
int i;
for (i=0; i<5; i++)
{ System.out.println("Hello
Friends !");
} } }
Output
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends ! 114
Hello Friends !
SCION RESEARCH AND DEVELOPMENT
do-while
• A do-while loop is similar to a while loop, except that a do-while loop is
execute at least one time.
• A do while loop is a control flow statement that executes a block of code at
least once, and then repeatedly executes the block, or not, depending on a
given condition at the end of the block (in while).
Syntax
do
{
Statement(s)
increment/decrement (++ or --)
}
115
while();
SCION RESEARCH AND DEVELOPMENT
LOOPING STATEMENT
LOOPING STATEMENT
When use do..while loop
• when we need to repeat the statement block at least one time then use do-
while loop. In do-while loop post-checking process will be occur, that is after
execution of the statement block condition part will be executed.
• In below example you can see in this program i=20 and we check condition i
is less than 10, that means condition is false but do..while loop execute once
and print Hello world ! at one time.
116
SCION RESEARCH AND DEVELOPMENT
Example do..while loop
class dowhileDemo {
public static void main(String args[])
{ int i=20;
do {
System.out.println("Hello world !");
i++;
}
while(i<10);
}
}
Output
LOOPING STATEMENT
117
Hello world !
SCION RESEARCH AND DEVELOPMENT
118
Example do..while loop
class dowhileDemo {
public static void main(String args[])
{ int i=0;
do
{ System.out.println(+i
); i++;
}
while(i<5);
} }
Output
1
2
3
4
LOOPING STATEMENT
5
SCION RESEARCH AND DEVELOPMENT
Wrapper classes in java
For each and every fundamental data type there exist a pre-defined class, Such
predefined class is known as wrapper class. The purpose of wrapper class is to
convert numeric string data into numerical or fundamental data. Why use
wrapper classes ?
We know that in java whenever we get input form user, it is in the form of
string value so here we need to convert these string values in different datatype
(numerical or fundamental data), for this conversion we use wrapper classes.
119
SCION RESEARCH AND DEVELOPMENT
WRAPPER CLASS
}
Output
Sum before: 1020
WRAPPER CLASS
Example of wrapper class
class WraperDemo {
public static void main(String[] args)
{ String s[] = {"10", "20"};
System.out.println("Sum before:"+ s[0] + s[1]); // 1020 int
x=Integer.parseInt(s[0]); // convert String to Integer int
y=Integer.parseInt(s[1]); // convert String to Integer int
z=x+y;
System.out.println("sum after: "+z); // 30
}
Sum after: 30 120
SCION RESEARCH AND DEVELOPMENT
WRAPPER CLASS
Explanation: In the above example 10 and 20 are store in String array and next
we convert these values in Integer using "int x=Integer.parseInt(s[0]);" and "int
y=Integer.parseInt(s[1]);" statement In "System.out.println("Sum before:"+ s[0]
+ s[1]);" Statement normally add two string and output is 1020 because these
are String numeric type not number.
121
SCION RESEARCH AND DEVELOPMENT
Converting String data into fundamental or numerical
We know that every command line argument of java program is available in
the main() method in the form of array of object of string class on String data,
one can not perform numerical operation. To perform numerical operation it
is highly desirable to convert numeric String into fundamental numeric value.
Example
• "10" --> numeric String --> only numeric string convert into numeric
type or value.
• "10x" --> alpha-numeric type --> this is not conversion.
• "ABC" --> non-numeric String no conversion.
• "
A" --> char String no conversion.
Only '
A'is convert into ASCII value that is 65 but '
A'is not convert into numeric
value because it is a String value.
122
SCION RESEARCH AND DEVELOPMENT
WRAPPER CLASS
Fundamental DataType Wrapper CalssName
Conversion method from numeric string into
fundamental or numeric value
Byte Byte public static byte parseByte(String)
Short Short public static short parseShort(String)
Int Integer public static integer parseInt(String)
Long Long public static long parseLong(String)
float Float public static float parseFloat(String)
double Double public static double parseDouble(String)
char Character
boolean Boolean public static boolean parseBoolean(String)
123
SCION RESEARCH AND DEVELOPMENT
WRAPPER CLASS
Fundamental data type and corresponding wrapper classes
The following table gives fundamental data type corresponding wrapper class
name and conversion method from numerical String into numerical values or
fundamental value.
WRAPPER CLASS
How to use wrapper class methods
All the wrapper class methods are static in nature so we need to call these
method using class.methodName().
• for Integer: int x=Integer.parseInt(String);
• for float: float x=Float.parseFloat(String);
• for double: double x=Double.parseDouble(String);
Each and every wrapper class contains the following generalized method for
converting numeric String into fundamental values.
124
Here xxx represents any fundamental data type.
SCION RESEARCH AND DEVELOPMENT
NAMING CONVERSION
Naming Conversion of Java
Sun micro system was given following conversions by declaring class,
variable, method etc. So that it is highly recommended to follow this conversion
while writing real time code.
Why Using naming Conversion
Different Java programmers can have different styles and approaches to write
program. By using standard Java naming conventions they make their code
easier to read for themselves and for other programmers. Readability of Java
code is important because it means less time is spent trying to figure
out what the code does, and leaving more time to fix or modify it.
1. Every package name should exist a lower case latter.
Example
package student; // creating package
125
import java.lang; // import package
SCION RESEARCH AND DEVELOPMENT
NAMING CONVERSION
2.First letter of every word of class name or interface name should
exists in upper case.
Example
class StudentDetails {
..... }
interface FacultyDetail {
..... }
3.Every constant value should exists in upper case latter. It is containing
more than one word than it should be separated with underscore (-).
Example
class Student {
final String COLLEGE_NAME="abcd";
126
.... }
SCION RESEARCH AND DEVELOPMENT
NAMING CONVERSION
Note: if any variable is preceded by final keyword is known as
constant value.
Example
class Student {
Final String Student_name="abcd";
}
While declaring variable name, method, object reference the first letter
of first word should be exits in lower case but from the second words
onward the first letter should exists in upper case.
class Student {
String StudentName="xyz";
void instantStudentDetails();
{ .... .... }
127
Student final
SCION RESEARCH AND DEVELOPMENT
According to CamelCase if name is combined with two words, second word will
start with uppercase letter always. General Example studentName,
customerAccount. In term of java programming e.g. actionPerformed(),
NAMING CONVERSION
CamelCase in java naming conventions
Java follows camelcase syntax for naming the class, interface, method and
variable.
128
firstName, ActionEvent, ActionListener etc.
SCION RESEARCH AND DEVELOPMENT
Syntax
import package1.package2.......*;
IMPORT STATEMENT
Import statements in Java
Import is a keyword in java language used to import the predefined properties
of java API into current working java program.
129
Used to import all the predefined properties of given package.
SCION RESEARCH AND DEVELOPMENT
Syntax
import pack1.package2.............Class_Name/Interface_Name;
Used to import specific class or interface in a java program.
Java API is a collection of package, package is a container which is collection of
predefined classes and interfaces.
Note: Import statement should be the first statement of the java programs.
130
SCION RESEARCH AND DEVELOPMENT
IMPORT STATEMENT
Access Modifiers in Java
Access modifiers are those which are applied before data members or
methods of a class. These are used to where to access and where not to access
the data members or methods. In Java programming these are classified into
four types:
• Private
• Default (not a keyword)
• Protected
• Public
Note: Default is not a keyword (like public, private, protected are keyword) If
we are not using private, protected and public keywords, then JVM is by
default taking as default access modifiers.
131
SCION RESEARCH AND DEVELOPMENT
ACCESS MODIFIERS
Note: Protected members of the class are accessible within the same class
and another class of same package and also accessible in inherited class of
132
another package.
SCION RESEARCH AND DEVELOPMENT
ACCESS MODIFIERS
Access modifiers are always used for, how to reuse the features within the
package and access the package between class to class, interface to interface
and interface to a class. Access modifiers provide features accessing and
controlling mechanism among the classes and interfaces.
ACCESS MODIFIERS
Rules for access modifiers:
The following diagram gives rules for Access modifiers.
133
SCION RESEARCH AND DEVELOPMENT
ACCESS MODIFIERS
private: Private members of class in not accessible anywhere in program these
are only accessible within the class. Private are also called class level access
modifiers.
Example
class Hello {
private int a=20;
private void show() {
System.out.println("Hello java"); } }
public class Demo {
public static void main(String args[])
{ Hello obj=new Hello();
System.out.println(obj.a); //Compile
Time Error, you can't access private
obj.show(); //Compile Time Error, you
can't access private methods
134
} }
SCION RESEARCH AND DEVELOPMENT
public static void main(String args[])
{ Hello obj=new Hello();
System.out.println(obj.a);
Output
20
ACCESS MODIFIERS
public: Public members of any class are accessible anywhere in the program
in the same class and outside of class, within the same package and outside of
the package. Public are also called universal access modifiers.
Example
class Hello
{ public int
a=20;
public void show()
{ System.out.println("Hello
java"); } } public class Demo {
135
Hello Java
obj.show(); } }
SCION RESEARCH AND DEVELOPMENT
ACCESS MODIFIERS
protected: Protected members of the class are accessible within the same class
and another class of the same package and also accessible in inherited class of
another package. Protected are also called derived level access modifiers.
In below the example we have created two packages pack1 and pack2. In pack1,
class A is public so we can access this class outside of pack1 but method show
is declared as a protected so it is only accessible outside of package pack1 only
through inheritance.
Example : // save A.java
package demo;
public class DEMO {
protected void
show() {
System.out.println("
Hello Java");
136
} }
SCION RESEARCH AND DEVELOPMENT
//save B.java
package PACKAGE2;
import demo.*;
public class CLASS_2
extends DEMO {
public static void main(String args[])
{ CLASS_2 obj = new CLASS_2();
obj.show();
}
}
Output
Hello Java
ACCESS MODIFIERS
137
SCION RESEARCH AND DEVELOPMENT
ACCESS MODIFIERS
default: Default members of the class are accessible only within the same class
and another class of the same package. The default are also called package level
access modifiers.
Example
//save by A.java
package demo;
public class DEMO
{ void show()
{
System.out.println("
Hello Java");
}
}
138
SCION RESEARCH AND DEVELOPMENT
//save by B.java
package PACKAGE2;
//import demo.*;
public class CLASS_2 {
public static void
main(String args[])
{
DEMO obj = new DEMO(); //Compile Time Error, can't access outside the
package
obj.show(); //Compile Time Error, can't access outside the package
}
}
Output
ACCESS MODIFIERS
Hello Java
139
SCION RESEARCH AND DEVELOPMENT
ARRAY IN JAVA
Array is a collection of similar type of data. It is fixed in size means that you
can't increase the size of array at run time. It is a collection of homogeneous
data elements. It stores the value on the basis of the index value.
Advantage of Array
• One variable can store multiple value:
The main advantage of the array is we can represent multiple value
under the same name.
• Code Optimization:
No, need to declare a lot of variable of same type data, We can retrieve and
sort data easily.
• Random access:
We can retrieve any data from array with the help of the index value.
140
SCION RESEARCH AND DEVELOPMENT
Disadvantage of Array
• The main limitation of the array is Size Limit when once we declare array
there is no chance to increase and decrease the size of an array according to
our requirement,
• Hence memory point of view array concept is not recommended to use. To
overcome this limitation in Java introduce the collection concept.
Types of Array
There are two types of array in Java.
• Single Dimensional Array
• Multidimensional Array
141
SCION RESEARCH AND DEVELOPMENT
ARRAY IN JAVA
Array Declaration
Single dimension array declaration.
Syntax
1. int[] a;
2. int a[];
3. int []a;
Note: At the time of array declaration we cannot specify the size of the array.
For Example int[5] a; this is wrong.
2D Array declaration.
Syntax
1. int[][] a;
2. int a[][];
142
6. int []a[];
4. int[] a[];
SCION RESEARCH AND DEVELOPMENT
3. int [][]a;
ARRAY IN JAVA
5. int[] []a;
int[] arr = new int[10];
(or)
int[] arr =
{10,20,30,40,50};
Accessing array
elements
143
SCION RESEARCH AND DEVELOPMENT
Access the elements of array by using
index value of an elements.
Syntax - arrayname[n-1];
Access Array Elements
int[] arr={10,20,30,40};
System.out.println("Elemen
t at 4th place"+arr[2]);
// The size of array is 10.
ARRAY IN JAVA
Every array in a Java is an object, Hence we can create array by using new
keyword.
Syntax
Example of Array
public class ArrayEx {
public static void main(String []args)
{ int arr[] = {10,20,30};
for (int i=0; i < arr.length; i++)
{ System.out.println(arr[i]);
}
}
}
Output
10
20
30
ARRAY IN JAVA
144
SCION RESEARCH AND DEVELOPMENT
Note:
1) At the time of array creation we must be specify the size of array otherwise
get an compile time error.
For Example
• int[] a=new int[]; Invalid.
• int[] a=new int[5]; Valid
2) If we specify the array size as negative int value, then we will get run-
time error, NegativeArraySizeException.
3) To specify the array size the allowed data types are byte, short, int, char If
we use other data type then we will get an Compile time error.
4) The maximum allowed size of array in Java is 2147483647 (It is the
maximum value of int data type)
145
SCION RESEARCH AND DEVELOPMENT
ARRAY IN JAVA
ARRAY IN JAVA
Difference Between Length and Length() in Java
length: It is a final variable and only applicable for array. It represent size of
array.
Example
int[] a=new int[10];
System.out.println(a.length); // 10
System.out.println(a.length()); // Compile time error
length(): It is the final method applicable only for String objects.
It represents the number of characters present in the String.
Example
String s="Java";
System.out.println(s.length()); // 4
146
System.out.println(s.length); // Compile time error
SCION RESEARCH AND DEVELOPMENT
Final keyword in java
It is used to make a variable as a constant, Restrict method overriding, Restrict
inheritance. It is used at variable level, method level and class level. In java
language final keyword can be used in following way.
• Final at variable level
• Final at method level
• Final at class level
FINAL KEYWORD
147
SCION RESEARCH AND DEVELOPMENT
Final at variable level
Final keyword is used to make a variable as a constant. This is similar to const
in other language. A variable declared with the final keyword cannot be
modified by the program after initialization. This is useful to universal
constants, such as "PI".
Final Keyword in java Example
public class Circle {
public static final double PI=3.14159;
public static void main(String[] args)
{
System.out.println(PI);
}
}
148
SCION RESEARCH AND DEVELOPMENT
FINAL KEYWORD
Final at method level
• It makes a method final, meaning that sub classes can not override this
method. The compiler checks and gives an error if you try to override the
method.
• When we want to restrict overriding, then make a method as a final.
Example
public class A
{ public void fun1()
{
.......
}
public final void
fun2() {
.......
}
149
}
SCION RESEARCH AND DEVELOPMENT
FINAL KEYWORD
class B extends A
{
public void fun1()
{
.......
}
public void fun2()
{
// it gives an error because we can not override final method
}
}
150
SCION RESEARCH AND DEVELOPMENT
FINAL KEYWORD
FINAL KEYWORD
Example of final keyword at method level
class Employee
{
final void disp()
{
System.out.println("Hello Good Morning");
}
}
class Developer extends Employee
{ void disp()
{
System.out.println("How are you ?");
}
151
}
SCION RESEARCH AND DEVELOPMENT
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}
}
Output
It gives an error
152
SCION RESEARCH AND DEVELOPMENT
FINAL KEYWORD
Final at class level
It makes a class final, meaning that the class can not be inheriting by other
classes. When we want to restrict inheritance then make class as a final.
Example
public final class A
{
......
}
public class B extends A
{
// it gives an error, because
we can not inherit final class
}
153
SCION RESEARCH AND DEVELOPMENT
FINAL KEYWORD
Developer obj=new Developer();
Developer obj=new Developer();
obj.show();
154
} }
SCION RESEARCH AND DEVELOPMENT
Output:
It gives an error
FINAL KEYWORD
Example of final keyword at class level
final class Employee
{ int salary=10000;
}
class Developer
extends Employee {
void show() {
System.out.println("H
ello Good Morning");
} }
class FinalDemo {
public static void
main(String args[]) {
THIS KEYWORD
this is a reference variable that refers to the current object. It is a keyword in
java language represents current class object
Usage of this keyword
• It can be used to refer current class instance variable.
• this() can be used to invoke current class constructor.
• It can be used to invoke current class method (implicitly)
• It can be passed as an argument in the method call.
• It can be passed as argument in the constructor call.
• It can also be used to return the current class instance.
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
155
between formal parameter and member of the class)
SCION RESEARCH AND DEVELOPMENT
To differentiate between formal parameter and data member of the class, the
data member of the class must be preceded by "this".
"this" keyword can be use in two ways. 1-
this . (this dot) 2 - this() (this off)
this . (this dot)
which can be used to differentiate
variable of class and formal parameters
of method or constructor.
"this" keyword are used for two purpose,
they are
It always points to current class
object.
• Whenever the formal parameter and data member of the class are similar and
JVM gets an ambiguity (no clarity between formal parameter and data
members of the class).
• To differentiate between formal parameter and data member of the class, the
156
SCION RESEARCH AND DEVELOPMENT
THIS KEYWORD
THIS KEYWORD
Syntax - this.data member of current class.
Note: If any variable is preceded by "this" JVM treated that variable as class
variable.
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);
157
}
SCION RESEARCH AND DEVELOPMENT
THIS KEYWORD
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
158
SCION RESEARCH AND DEVELOPMENT
THIS KEYWORD
In the above example, parameter (formal arguments) and instance variables
are same that is why we are using "this" keyword to distinguish between local
variable and instance variable.
Example of this keyword in java
class Employee {
int id;
String name;
Employee(int id,String name)
{ this.id = id;
this.name = name;
}
void show() {
System.out.println(id+"
"+name); 159
}
SCION RESEARCH AND DEVELOPMENT
THIS KEYWORD
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
Note 1: The scope of "this" keyword is
within the class.
Note 2: The main purpose of using "this" keyword in real life application is to
differentiate variable of class or formal parameters of methods or
constructor (it is highly recommended to use the same variable name
either in a class or method and constructor while working with similar
160
objects).
SCION RESEARCH AND DEVELOPMENT
THIS KEYWORD
Difference between this and super keyword
Super keyword is always pointing to base class (scope outside the class)
features and "this" keyword is always pointing to current class (scope is within
the class) features.
Example when no need of this keyword
class Employee {
int id;
String name;
Employee(int i,String n)
{ id = i;
name = n;
}
void show() {
161
System.out.println(id+" "+name);
SCION RESEARCH AND DEVELOPMENT
}
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
162
SCION RESEARCH AND DEVELOPMENT
THIS KEYWORD
THIS KEYWORD
In the above example, no need of use this keyword because parameter (formal
arguments) and instance variables are different. This keyword is only use
when parameter (formal arguments) and instance variables are same.
this ()
which can be used to call one constructor within the another constructor
without creation of objects multiple time for the same class.
Syntax
this(); // call no parameterized or default constructor
this(value1,value2,.....) //call parameterize constructor
this keyword used to invoke current class method
(implicitly)
By using this keyword you can invoke the method of
the current class. If
you do not use the this keyword, compiler
automatically adds this keyword 163
at time of invoking of the method.
SCION RESEARCH AND DEVELOPMENT
THIS KEYWORD
164
SCION RESEARCH AND DEVELOPMENT
Example of this keyword
class Student {
void show()
{
System.out.prin
tln("You got
A+");
}
void marks()
{
165
}
SCION RESEARCH AND DEVELOPMENT
//no need to use this here because compiler does it.
this.show();
}
void display()
{
show(); //compiler act marks() as this.marks()
THIS KEYWORD
Syntax
You got A+
166
SCION RESEARCH AND DEVELOPMENT
THIS KEYWORD
public static void main(String args[])
{
Student s = new Student();
s.display();
}
}
Rules to use this()
this() always should be the first statement of the constructor. One
constructor can call only other single constructor at a time by using this().
THIS KEYWORD
167
SCION RESEARCH AND DEVELOPMENT
Super keyword in java
Super keyword in java is a reference variable that is used to refer parent class
object. Super is an implicit keyword create by JVM and supply each and every
java program for performing important role in three places.
• At variable level
• At method level
• At constructor level
Need of super keyword:
Whenever the derived class is inherits the base class features, there is a
possibility that base class features are similar to derived class features and JVM
gets an ambiguity. In order to differentiate between base class features and
derived class features must be preceded by super keyword.
Syntax
168
super.baseclass features.
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
Super at variable level:
Whenever the derived class inherit base class data members there is a
possibility that base class data member are similar to derived class data
member and JVM gets an ambiguity.
In order to differentiate between the data member of base class and derived
class, in the context of derived class the base class data members must be
preceded by super keyword.
Syntax
super.baseclass datamember name
if we are not writing super keyword before the base class data member name
than it will be referred as current class data member name and base
class data member are hidden in the context of derived class.
169
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
HR obj=new HR();
obj.display();
170
Salary: 20000.0
} }
SCION RESEARCH AND DEVELOPMENT
Output
SUPER KEYWORD
Program without using super keyword
class Employee
{ float
salary=10000;
}
class HR extends
Employee {
float salary=20000;
void display() {
System.out.println("
Salary:
"+salary);//print
current class salary
} }
class Supervarible {
public static void
main(String[] args)
HR obj=new HR();
obj.display();
171
Salary: 10000.0
} }
SCION RESEARCH AND DEVELOPMENT
Output
SUPER KEYWORD
Program using super keyword al variable level
class
Employee{ float
salary=10000;
}
class HR extends
Employee {
float salary=20000;
void display() {
System.out.println("
Salary:
"+super.salary);//pr
int base class salary
} }
class Supervarible {
public static void
main(String[] args)
Super at method level
• The super keyword can also be used to invoke or call parent class method.
It should be use in case of method overriding. In other word super keyword
use when base class method name and derived class method name have
same name.
• In the below example Student and Faculty both classes have message()
method if we call message() method from Student class, it will call the
message() method of Student class not of Person class because priority of
local is high.
• In case there is no method in subclass as parent, there is no need to use
super. In the example given below message() method is invoked from
Student class but Student class does not have message() method, so you
can directly call message() method.
172
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
SUPER KEYWORD
Example of super keyword at method level
class Student
{ void message()
{
System.out.printl
n("Good
Morning Sir");
}
}
class Faculty extends Student
{ void message()
System.out.println("Good
Morning Students");
}
void display() {
message();//will invoke or call
current class message()
173
}
SCION RESEARCH AND DEVELOPMENT
Output
Good Morning Students
Good Morning Sir
174
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
public static void main(String args[])
{ Student s=new Student();
s.display();
}
}
s.display();
}
175
Good Morning Sir
}
SCION RESEARCH AND DEVELOPMENT
Output
SUPER KEYWORD
Program where super is not required
class Student
{ void message()
{
System.out.printl
n("Good
Morning Sir");
} }
class Faculty extends Student
{ void display() {
message();//will invoke or call
parent class message() method
}
public static void main(String args[])
{ Student s=new Student();
SUPER KEYWORD
Super at constructor level
The super keyword can also be used to invoke or call the parent class
constructor. Constructor are calling from bottom to top and executing from top
to bottom.
To establish the connection between base class constructor and derived
class constructors JVM provides two implicit methods they are:
Super()
Super(...)
Super()
Super()
It is used
for
calling
super
class
176
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
Super keyword used to call base class constructor
Syntax
class Employee {
Employee() {
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{ HR() {
super(); //will invoke or call
parent class constructor
System.out.println("HR class
Constructor");
}
}
177
SCION RESEARCH AND DEVELOPMENT
class Supercons {
public static void main(String[] args)
{ HR obj=new HR();
}
}
Output
Employee class Constructor
HR class Constructor
Note: super() is added in
each class constructor
automatically by compiler
178
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
In constructor, default constructor is provided by compiler automatically but it
also adds super() before the first statement of constructor. If you are creating
your own constructor and you do not have either this() or super() as the first
statement, compiler will provide super() as the first statement
179
of the constructor.
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
Super(...)
Super(...) It is used for calling super class parameterize constructor from the
context of derived class constructor.
Important rules
Whenever we are using either super() or super(...) in the derived class
constructors the super always must be as a first executable statement in the
body of derived class constructor otherwise we get a compile time error.
Rule 1 and Rule 3
Whenever the derived class constructor want to call default constructor of base
class, in the context of derived class constructors we write super().
Which is optional to write because every base class constructor contains
single form of default constructor?
180
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
Rule 2 and Rule 4
Whenever the derived class constructor wants to call parameterized
constructor of base class in the context of derived class constructor we must
write super(...). which is mandatory to write because a base class may contain
multiple forms of parameterized constructors.
The following diagram use possibilities of using super() and
super(........)
181
SCION RESEARCH AND DEVELOPMENT
SUPER KEYWORD
Synchronized is a Modifier which is applicable for the method or block, we
SYNCHRONIZED KEYWORD
Synchronized Keyword in Java
Synchronized Keyword is used for when we want to allowed only one thread
at a time then use Synchronized modifier. If a method or block declared as a
Synchronized then at a time only one thread is allowed to operate on the given
object.
182
can not declare class or variable with this modifier.
SCION RESEARCH AND DEVELOPMENT
SYNCHRONIZED KEYWORD
Advantage of Synchronized
The main advantage of Synchronized keyword is we can resolve data
inconsistency problem.
Dis-Advantage of Synchronized
The main dis-advantage of Synchronized keyword is it increased the waiting
time of thread and effect performance of the system, Hence if there is no
specific requirement it is never recommended to use synchronized keyword.
183
SCION RESEARCH AND DEVELOPMENT
VOLATILE KEYWORD
Volatile Keyword in Java
• If the variable keep on changing such type of variables we have to declare
with volatile modifier.
• Volatile is a modifier applicable only for variables but not for method and
class.
• If a variable declared as volatile then for every thread a separate local copy
will be created.
• Every intermediate modification performed by that thread will takes place in
local copy instead of master copy.
• Once the value got finalized just before terminating the thread the master
copy value will be updated with local stable value.
Advantage of Volatile
The main advantage of Volatile keyword is we can resolve data
184
inconsistency problems.
SCION RESEARCH AND DEVELOPMENT
VOLATILE KEYWORD
Dis-Advantage of Volatile
The main dis-advantage of Volatile keyword is, crating and maintaining a
separate copy for every thread, increases complexity of the programming and
effects performance of the system. Hence if there is no specific requirement it
is never recommended to use volatile keyword, and it is
almost outdated keyword.
Note: Volatile variable means its value keep on changing where as final
variable means its value never changes. Hence final-Volatile combination is
illegal combination for variables.
185
SCION RESEARCH AND DEVELOPMENT
Static Block in Java
• Static block is a set of statements, which will be executed by the JVM before
execution of main method.
• At the time of class loading if we want to perform any activity we have to
define that activity inside static block because this block execute at the
time of class loading.
• In a class we can take any number of static block but all these blocks will be
execute from top to bottom.
STATIC BLOCK
186
SCION RESEARCH AND DEVELOPMENT
Syntax
Static { ........
//Set of Statements ........
}
Note: In real time application static block can be used whenever we want to
execute any instructions or statements before execution of main method.
Example of Static Block
class StaticDemo {
Static {
System.out.println(
"Hello how are
u ?");
187
This is main()
} }
SCION RESEARCH AND DEVELOPMENT
}
public static void main(String args[]) {
System.out.println("This is main()");
Output
Hello how are u ?
STATIC BLOCK
STATIC BLOCK
Run java program without main method
class StaticDemo {
static {
System.out.println(
"Hello how are
u ?");
}
}
Output:
Hello how are u ?
Exception is thread
"main"
java.lang.no-
suchmethodError:
Main
188
SCION RESEARCH AND DEVELOPMENT
STATIC BLOCK
More than one static block in a program
class StaticDemo {
static
{
System.out.println(
"First static
block");
}
static
{
System.out.println(
"Second Static
block");
}
public static void
main(String
args[]) {
189
}
SCION RESEARCH AND DEVELOPMENT
Output:
First static block
Second static block
This is main()
Note: "Here static block run according to there order (sequence by) from top to
bottom
Why a static block executes before the main method ?
A class has to be loaded in main memory before we start using it. Static block is
executed during class loading. This is the reason why a static block
executes before the main method.
190
SCION RESEARCH AND DEVELOPMENT
STATIC BLOCK
INNER CLASSES
Inner Classes in Java Programming
If one class is existing within another class is known as inner class or nested
class
Syntax
class Outerclass_name {
.....
class Innerclass_name1{
.....
}
class Innerclass_name1{
.....
}
}
191
SCION RESEARCH AND DEVELOPMENT
INNER CLASSES
The main purpose of using inner class
• To provide more security by making those inner class properties specific to
only outer class but not for external classes.
• To make more than one property of classes private properties.
• Private is a keyword in java language, it is preceded by any variable that
property can be access only within the class but not outside of it (provides
more security).
• If more than one property of class wants to make as private properties than
all can capped under private inner class.
Syntax
class Outerclass_name {
private class Innerclass_name {
..... //private properties
192
} }
SCION RESEARCH AND DEVELOPMENT
Note: No outer class made as private class otherwise this is not available
for JVM at the time of execution.
Rules to access properties of inner classes
• Inner class properties can be accessed in the outer class with the object
reference but not directly.
• Outer class properties can be access directly within the inner class.
• Inner class properties can't be accessed directly or by creating directly
object.
Note: In special situation inner class property can be accessed in the external
class by creating special objects with the reference of its outer class.
193
SCION RESEARCH AND DEVELOPMENT
INNER CLASSES
//outer class
194
SCION RESEARCH AND DEVELOPMENT
Example
class A
{
void fun1() {
System.out.println("Hello fun1()");
// inner class properties should be access using
//object reference in outer class.
B ob=new B();
ob.x=10
System.out.println("x= "+ob.x);
ob.fun2();
}
INNER CLASSES
// inner class
195
}
SCION RESEARCH AND DEVELOPMENT
// inner class variable
//inner class fun2()
class B
{
int x;
void fun2()
{
System.out.println("Hello fun2()");
//outer class properties can be access directly
fun3();
}
}
INNER CLASSES
void fun3() // outer class fun3()
{
System.out.println("Hello fun3()");
}
// external class
196
} }
SCION RESEARCH AND DEVELOPMENT
class C
{
void fun3()
{
System.out.println("Hello fun3()");
}
}
class IncDemo {
public static void main(String args[])
{ A oa=new A();
oa.fun1();
C oc=new C();
oc.fun3();
Output
Hello fun1()
X=10
Hello fun2()
Hello fun3()
INNER CLASSES
Accessing inner class properties in the external class
1. If inner class in non static the object can be created with the following syntax
Syntax
class Outer_class
{ class Inner_class
{
.....
}
.....
}
class
External_class {
Outer_class.Inner_Class objectrefernce=new Outer_Class.External_Class();
}
197
SCION RESEARCH AND DEVELOPMENT
INNER CLASSES
2. If inner class is static the object reference can be created with the
following syntax
Syntax
class Outer_class { static
class Inner_Class {
.....
.....
}
}
class External_Class {
Outer_class.Inner_Class
objectrefernce=new
Outer_Class.External_Cla
ss();
}
}
198
SCION RESEARCH AND DEVELOPMENT
INNER CLASSES
//Outer class
199
void fun2()
SCION RESEARCH AND DEVELOPMENT
// non-static inner class
//inner class variable
//inner class fun1()
Example
class A
{
class B
{
int x;
void fun1()
{ System.out.println("Hello
fun1()");
}
}
static class C
{
int y=20;
//static inner class
// inner class variable
INNER CLASSES
{
System.out.println("Hello fun2()");
}
}
}
class IncDemo {
public static void main(String args[]) {
B.ob=new A().new.B();
System.out.println(ob.x);
ob.fun1();
C. oc=new A.C();
System.out.println(oc.y);
oc.fun2();
} }
SCION RESEARCH AND DEVELOPMENT
200
INNER CLASSES
Abstract class in Java
We know that every Java program must start with a concept of class that is
without the class concept there is no Java program perfect.
In Java programming we have two types of classes they are
• Concrete class
• Abstract class
Concrete class in Java
A concrete class is one which is containing fully defined methods or
implemented method.
Example
class Helloworld {
void display() {
System.out.println("Good Morning........");
201
} }
SCION RESEARCH AND DEVELOPMENT
ABSTRACT CLASS
ABSTRACT CLASS
Here Helloworld class is containing a defined method and object can be created
directly.
Create an object
Helloworld obj=new Helloworld();
obj.display();
Every concrete class has specific
features and these classes are
used for
specific requirement, but not for
common requirement.
If we use concrete classes for fulfill common requirements than such
application will get the following limitations.
• Application will take more amount of memory space (main memory).
• Application execution time is more.
• Application performance is decreased.
To overcome above limitation you can use abstract class.
202
SCION RESEARCH AND DEVELOPMENT
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class. An
abstract class is one which is containing some defined method and some
undefined method. In java programming undefined methods are known as un-
Implemented, or abstract method.
ABSTRACT CLASS
203
SCION RESEARCH AND DEVELOPMENT
Syntax
abstract class className {
}
Example
abstract class A {
}
If any class have any abstract method then that class become an abstract class.
Example
class Vechile
{ abstract void
Bike();
}
Class Vechile is
become an abstract
class because it have
abstract Bike()
204
method.
SCION RESEARCH AND DEVELOPMENT
ABSTRACT CLASS
…….
}
Abstract method
An abstract method is one which contains only declaration or prototype but it
never contains body or definition. In order to make any undefined method as
abstract whose declaration is must be predefined by abstract keyword.
Syntax
Example
abstract void sum();
abstract void diff(int, int);
ABSTRACT CLASS
Make class as abstract class
To make the class as abstract class, whose definition must be preceded by a
abstract keyword.
Example
abstract class Vechile {
205
abstract ReturnType methodName(List of formal parameter)
SCION RESEARCH AND DEVELOPMENT
// abstract method
206
Speed limit is 40 km/hr..
SCION RESEARCH AND DEVELOPMENT
//indirect object creation
Example of abstract class
abstract class Vechile
{ abstract void speed();
}
class Bike extends Vechile {
void speed() {
System.out.println("Speed
limit is 40 km/hr..");
}
public static void main(String args[])
{ Vachile obj = new Bike();
obj.speed();
} }
Output
ABSTRACT CLASS
ABSTRACT CLASS
Create an Object of abstract class
An object of abstract class cannot be created directly, but it can be created
indirectly. It means you can create an object of abstract derived class. You can see
in above example
Example - Vehicle obj = new Bike(); //indirect object creation
Abstract class of Java always contains common features.
• Every abstract class participates in inheritance.
• Abstract class definitions should not be made as final because abstract classes
always participate in inheritance classes.
• An object of abstract class cannot be created directly, but it can be created
indirectly.
• All the abstract classes of Java makes use of polymorphism along with method
overriding for business logic development and makes use of dynamic binding
207
for execution logic.
SCION RESEARCH AND DEVELOPMENT
ABSTRACT CLASS
Advantage of abstract class
• Less memory space for the application
• Less execution time
• More performance
Why abstract class have no abstract static method ?
In abstract classes we have the only abstract instance method, but not
containing abstract static methods because every instance method is created
for performing repeated operation where as static method is created for
performing a one time operations in other word every abstract method is
instance but not static.
Abstract base class
An abstract base class is one which is containing physical representation of
abstract methods which are inherited by various sub classes.
208
SCION RESEARCH AND DEVELOPMENT
Abstract derived class
• An abstract derived class is one which is containing logic representation of
abstract methods which are inherited from abstract base class with respect to
both abstract base class and abstract derived class one can not create objects
directly, but we can create their objects indirectly both abstract base class and
abstract derived class are always reusable by various sub classes. When the
derived class inherits multiple abstract method from abstract base class and if
the derived class is not defined at least one abstract method then the derived
class is known as abstract derived class and whose definition must be made as
abstract by using abstract keyword. (When the derived class becomes an
abstract derived class).
• If the derived class defined all the abstract methods which are inherited
from abstract Base class, then the derived class is known as concrete
209
derived class.
SCION RESEARCH AND DEVELOPMENT
ABSTRACT CLASS
ABSTRACT CLASS
210
SCION RESEARCH AND DEVELOPMENT
public static void main(String args[]) {
Vachile obj = new Bike();
obj.speed();
211
Speed limit is 40 km/hr..
obj.mileage(); } }
SCION RESEARCH AND DEVELOPMENT
Output
Mileage is 60 km/ltr..
ABSTRACT CLASS
Example of abstract class having method body
abstract class Vehicle
{ abstract void speed();
void mileage() {
System.out.println("Mil
eage is 60 km/ltr..");
} }
class Bike extends Vehicle
{ void speed() {
System.out.println("Speed
limit is 40 km/hr..");
}
ABSTRACT CLASS
Example of abstract class having constructor, data member, methods
abstract class Vehicle
{ int limit=40;
Vechile() {
System.out.println("co
nstructor is invoked");
}
void getDetails() { System.out.println("it
has two wheels");
}
abstract void run();
}
class Bike extends Vehicle {
void run() { 212
System.out.println("running safely..");
SCION RESEARCH AND DEVELOPMENT
}
public static void main(String args[])
{ Vachile obj = new Bike();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}
}
Output
constructor is invoked
running safely..
it has two wheels
213
40
SCION RESEARCH AND DEVELOPMENT
ABSTRACT CLASS
214
SCION RESEARCH AND DEVELOPMENT
DIFFERENCE BETWEEN ABSTRACT CLASS AND CONCRETE CLASS
Concrete class Abstract class
A Concrete class is used for specific
requirement
Abstract class is used to fulfill a common
requirement.
Object of concrete class can create directly.
Object of an abstract class can not create directly
(can create indirectly).
Concrete class containing fully defined
methods or implemented method.
Abstract class has both undefined method and
defined method.
215
SCION RESEARCH AND DEVELOPMENT
some time it can be accessed with object reference.
DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
The variable of any class are classified into two types;
• Static or class variable
• Non-static or instance variable
Static variable in Java
Memory for static variable is created only one in the program at the time of
loading of class. These variables are preceded by static keyword. static variable
can access with class reference.
Non-static variable in Java
Memory for non-static variable is created at the time of create an object of
class. These variable should not be preceded by any static keyword Example:
These variables can access with object reference.
Difference between non-static and static variable
Note: static variable not only can be access with class reference but also
216
SCION RESEARCH AND DEVELOPMENT
Non-static variable Static variable
1
These variable should not be
preceded by any static keyword
Example:
class A{int a;}
These variables are preceded by static
keyword.
Example
class A{static int b;}
2
Memory is allocated for these
variable whenever an object is
created
Memory is allocated for these variable at
the time of loading of the class.
3 Memory is allocated multiple time
whenever a new object is created.
Memory is allocated for these variable
only once in the program.
4
Non-static variable also known as
instance variable while because
memory is allocated whenever
instance is created.
Memory is allocated at the time of
loading of class so that these are also
known as class variable.
5
Non-static variable are specific to an
object
Static variable are common for every object
that means there memory location can be
sharable by every object reference or same
class.
6
Non-static variable can access with
object reference.
Syntax
obj_ref.variable_name
Static variable can access with class
reference.
Syntax
class_name.variable_name
DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
217
SCION RESEARCH AND DEVELOPMENT
Example of static and non-static variable.
class Student {
int roll_no;
float marks;
String name;
static String
College_Name
="ITM";
}
class
StaticDemo {
public static
void
main(String
args[])
{
Student s1=new Student();
s1.roll_no=100;
DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
SCION RESEARCH AND DEVELOPMENT
218
s2.roll_no=200; s2.marks=75.8f;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.marks);
System.out.println(s2.name);
System.out.println(Student.Coll
ege_Name);
} }
Output
100
65.8
abcd
ITM
200
75.8
zyx
ITM
DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
System.out.println(s1.roll_no);
System.out.println(s1.marks);
System.out.println(s1.name);
System.out.println(Student.College_Name);
//or System.out.println(s1. College_Name);
but first is use in real time.
Student s2=new Student();
219
Note: In the above example College_Name variable is commonly sharable
SCION RESEARCH AND DEVELOPMENT
by both S1 and S2 objects.
DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
220
SCION RESEARCH AND DEVELOPMENT
//will get memory when instance is created
int count=0;
Counter()
{ count++;
System.out.p
rintln(count
);
}
DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
Understand static and non-static variable using counter
Program of counter without static variable
In this example, we have created an instance variable named count which is
incremented in the constructor. Since instance variable gets the memory at
the time of object creation, each object will have the copy of the instance
variable, if it is incremented, it won't reflect to other objects. So each objects
will have the value 1 in the count variable.
Example
class Counter {
Output
1
1
1
221
SCION RESEARCH AND DEVELOPMENT
DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
//will get memory only once
3
222
} }
SCION RESEARCH AND DEVELOPMENT
static int count=0;
Counter()
{ count++;
System.out.println
(count); }
public static void main(String args[])
{ Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
Output
1
2
DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if
any object changes the value of the static variable, it will retain its value.
Example
class Counter {
Non-Static method Static method
These method never be preceded by
static keyword
Example:
void fun1()
{
......
......
}
These method always preceded by static
keyword
Example:
static
void
fun2()
{
......
......
}
223
SCION RESEARCH AND DEVELOPMENT
DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
Difference between Static and non-static method in Java
In case of non-static method memory is allocated multiple time whenever
method is calling. But memory for static method is allocated only once at the
time of class loading. Method of a class can be declared in two different ways
• Non-static methods
• Static methods
Difference between non-static and static Method
224
SCION RESEARCH AND DEVELOPMENT
Non-Static method Static method
Memory is allocated multiple time whenever
method is calling.
Memory is allocated only once at the time of class
loading.
It is specific to an object so that these are also
known as instance method.
These are common to every object so that it is also
known as member method or class method.
These methods always access with object
reference
Syntax:
Objref.methodname();
These property always access with class
reference
Syntax:
className.methodname();
If any method wants to be execute multiple
time that can be declare as non static.
If any method wants to be execute only once in
the program that can be declare as static .
Note: In some cases static methods not only can access with class reference
but also can access with object reference.
DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
225
Example of Static and non-Static Method
class A
{ void fun1()
{
System.out.p
rintln("Hello
I am Non-
Static");
}
static void fun2()
{ System.out.println("Hello I am
Static");
} }
class Person {
public static void main(String args[])
{ A oa=new A();
// non static method
// static method
oa.fun1();
A.fun2();
} }
Output
Hello I am Non-Static
SCION RESEARCH AND DEVELOPMENT
Hello I am Static
DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
226
DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
Following table represent how the static and non-static properties are
accessed in the different static or non-static method of same class or other
class.
SCION RESEARCH AND DEVELOPMENT
227
SCION RESEARCH AND DEVELOPMENT
Program to accessing static and non-static properties.
Example
class A {
int y;
void f2()
{
System.o
ut.println
("Hello
f2()");
}
}
class B
{ int z;
void f3(){
System.ou
t.println(
DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
} }
class Sdemo
{ static int x;
static void f1(){
System.out.prin
tln("Hello
f1()");
}
public static void main(String[] args)
{ x=10;
System.out.println("x="+x);
f1();
System.out.println("Hello
main");
B b1=new B();
b1.f3();
228
} }
SCION RESEARCH AND DEVELOPMENT
DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
CONSTRUCTOR IN JAVA
• constructor in Java is a special member method which will be called
implicitly (automatically) by the JVM whenever an object is created for
placing user or programmer defined values in place of default values. In a
single word constructor is a special member method which will be called
automatically whenever object is created.
• The purpose of constructor is to initialize an object called object
initialization. Constructors are mainly create for initializing the object.
Initialization is a process of assigning user defined values at the time of
allocation of memory space.
Syntax
className() {
.......
.......
229
}
SCION RESEARCH AND DEVELOPMENT
CONSTRUCTOR IN JAVA
Advantages of constructors in Java
• A constructor eliminates placing the default values.
• A constructor eliminates calling the normal or ordinary method implicitly.
How Constructor eliminate default values ?
Constructor are mainly used for eliminate default values by user defined
values, whenever we create an object of any class then its allocate memory for
all the data members and initialize there default values. To eliminate these
default values by user defined values we use constructor.
230
SCION RESEARCH AND DEVELOPMENT
231
Constructor Example in Java
class Sum {
int a,b;
Sum()
{ a=10;
b=20;
}
public static void main(String s[])
{ Sum s=new Sum();
c=a+b;
System.out.println("Sum: "+c);
} }
Output
Sum: 30
In above example when we create an
SCION RESEARCH AND DEVELOPMENT
object of "Sum" class then constructor
of this class call and initialize user
defined value in a=10 and b=20. if we
can not create constructor of Sum
class then it print " Sum: 0 " because
default values of integer is zero.
CONSTRUCTOR IN JAVA
• Constructor will be called automatically when the object is created.
• Constructor name must be similar to name of the class.
• Constructor should not return any value even void also. Because basic aim is
to place the value in the object. (if we write the return type for the
constructor then that constructor will be treated as ordinary method).
• Constructor definitions should not be static. Because constructors will be
called each and every time, whenever an object is creating.
• Constructor should not be private provided an object of one class is created in
another class (Constructor can be private provided an object of one class
created in the same class).
• Constructors will not be inherited from one class to another class (Because
every class constructor is create for initializing its own data members).
• The access specifies of the constructor may or may not be private.
232
SCION RESEARCH AND DEVELOPMENT
Rules or properties of a constructor
233
SCION RESEARCH AND DEVELOPMENT
Method Constructor
1 Method can be any user defined name Constructor must be class name
2 Method should have return type It should not have any return type (even void)
3
Method should be called explicitly either
with object reference or class reference
It will be called automatically whenever object
is created
4
Method is not provided by compiler in any
case.
The java compiler provides a default
constructor if we do not have any constructor.
CONSTRUCTOR IN JAVA
• If the access specifier of the constructor is private then an object of
corresponding class can be created in the context of the same class but not
in the context of some other classes.
• If the access specifier of the constructor is not private then an object of
corresponding class can be created both in the same class context and in
other class context.
Difference between Method and Constructor
234
SCION RESEARCH AND DEVELOPMENT
CONSTRUCTOR IN JAVA
Types of constructors
Based on creating objects in Java constructor are classified in two types. They
are
• Default or no argument Constructor
• Parameterized constructor.
Default Constructor
A constructor is said to be default constructor if and only if it never take any
parameters.
If any class does not contain at least one user defined constructor than the
system will create a default constructor at the time of compilation it is known
as system defined default constructor.
// Call default constructor
235
contain any user defined constructor.
SCION RESEARCH AND DEVELOPMENT
// Initialization
.....
clsname ()
{
Block of statements;
}
.....
}
Note: System defined default constructor is created by java compiler and does
not have any statement in the body part. This constructor will be executed
every time whenever an object is created if that class does not
CONSTRUCTOR IN JAVA
Syntax of Default Constructor
class className
{
//TestDemo.java
236
};
SCION RESEARCH AND DEVELOPMENT
Example:
class Test {
int a, b;
Test () {
System.out.println("I am from default Constructor...");
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
CONSTRUCTOR IN JAVA
Example of default constructor.
In below example, we are creating the no argument constructor in the Test
class. It will be invoked at the time of object creation.
class TestDemo {
public static void main(String [] args)
{ Test t1=new Test ();
}
};
237
SCION RESEARCH AND DEVELOPMENT
Output:
I am from default Constructor...
Value of a: 10
Value of b: 20
CONSTRUCTOR IN JAVA
Rule-1:
Whenever we create an object only with default constructor, defining the
default constructor is optional. If we are not defining default constructor of a
class, then JVM will call automatically system defined default constructor. If
we define, JVM will call user defined default constructor.
Purpose of default constructor?
Default constructor provides the default values to the object like 0, 0.0, null etc.
depending on their type (for integer 0, for string null).
Explanation: In the below class, we are not creating any constructor so
compiler provides a default constructor. Here 0, 0.0 and null values are
provided by default constructor.
238
SCION RESEARCH AND DEVELOPMENT
CONSTRUCTOR IN JAVA
239
s1.show(); } }
SCION RESEARCH AND DEVELOPMENT
} }
class TestDemo {
public static void main(String [] args) {
Student s1=new Student();
CONSTRUCTOR IN JAVA
Example of default constructor that displays the default values
class Student {
int roll;
float marks;
String name;
void show() { System.out.println("Roll:
"+roll); System.out.println("Marks:
"+marks); System.out.println("Name:
"+name);
Output
Roll: 0
Marks: 0.0
Name: null
//parameterized constructor
240
new ClassName(value1, value2,.....);
SCION RESEARCH AND DEVELOPMENT
ClassName(list of parameters) {
}
}
Syntax to call parametrized constructor
ClassName objref=new ClassName(value1, value2,.....);
OR
CONSTRUCTOR IN JAVA
parameterized constructor
If any constructor contain list of variable in its signature is known as
parameterized constructor. A parameterized constructor is one which takes
some parameters.
Syntax
class ClassName
{
CONSTRUCTOR IN JAVA
Example of Parameterized Constructor
class Test {
int a, b;
Test(int n1,
int n2) {
System.out.
println("I
am from
Parameteri
zed
Constructo
r...");
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
} };
class TestDemo1 {
241
} };
SCION RESEARCH AND DEVELOPMENT
CONSTRUCTOR IN JAVA
Important points Related to Parameterized Constructor
• Whenever we create an object using parameterized constructor, it must be
define parameterized constructor otherwise we will get compile time error.
Whenever we define the objects with respect to both parameterized
constructor and default constructor, It must be define both the constructors.
• In any class maximum one default constructor but 'n' number of
parameterized constructors.
242
SCION RESEARCH AND DEVELOPMENT
CONSTRUCTOR IN JAVA
Example of default constructor, parameterized constructor and
overloaded constructor
class Test {
int a, b;
Test () {
Syso("I am from default Constructor...");
a=1;
b=2;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (int x, int y) {
System.out.println("I am from double
Paraceterized Constructor"); 243
SCION RESEARCH AND DEVELOPMENT
a=x;
b=y;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (int x) {
System.out.println("I am from single Parameterized Constructor");
a=x;
b=x;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (Test T) { 244
System.out.println("I am from Object Parameterized Constructor...");
SCION RESEARCH AND DEVELOPMENT
CONSTRUCTOR IN JAVA
a=T.a;
b=T.b;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
} };
class TestDemo2
{
public static void main (String k [])
{
Test t1=new Test ();
245
} };
SCION RESEARCH AND DEVELOPMENT
Test t2=new Test (10, 20);
Test t3=new Test (1000);
Test t4=new Test (t1);
Note : By default the parameter passing
mechanism is call by reference.
CONSTRUCTOR IN JAVA
CONSTRUCTOR IN JAVA
Constructor Overloading
• Constructor overloading is a technique in Java in which a class can have
any number of constructors that differ in parameter lists. The compiler
differentiates these constructors by taking the number of parameters, and
their type.
• In other words whenever same constructor is existing multiple times in the
same class with different number of parameters or order of parameters or
type of parameters is known as Constructor overloading.
• In general constructor overloading can be used to initialized same or
different objects with different values.
Why overriding is not possible at constructor level.
The scope of constructor is within the class so that it is not possible to
246
achieved overriding at constructor level.
SCION RESEARCH AND DEVELOPMENT
Syntax
class ClassName
{ ClassName() {
..........
..........
}
ClassName(dataty
pe1 value1) {.......
}
ClassName(dataty
pe1 value1,
datatype2 value2)
{.......
}
ClassName(dataty
pe2 variable2) {.......
}
247
} }
SCION RESEARCH AND DEVELOPMENT
CONSTRUCTOR IN JAVA
Relationship in Java
Type of relationship always makes to understand how to reuse the feature from
one class to another class. In java programming we have three types of
relationship they are.
• Is-A Relationship
• Has-A Relationship
• Uses-A Relationship
Is-A relationship
• In Is-A relationship one class is obtaining the features of another class by
using inheritance concept with extends keywords.
• In a IS-A relationship there exists logical memory space
248
SCION RESEARCH AND DEVELOPMENT
RELATIONSHIP
Example of Is-A Relation
class Faculty {
float salary=30000;
}
class Science extends Faculty {
float bonous=2000;
public static void main(String args[])
{ Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
} }
Output
Salary is: 30000.0
249
Bonous is: 2000.0
SCION RESEARCH AND DEVELOPMENT
RELATIONSHIP
250
Output
Salary is:
SCION RESEARCH AND DEVELOPMENT
30000.0
Has-A relationship
• In Has-A relationship an object of one class is created as data member in
another class the relationship between these two classes is Has-A.
• In Has-A relationship there existed physical memory space and it is also
known as part of or kind of relationship.
Example of Has-A Relation
class Employee {
float salary=30000; }
class Developer extends Employee
{ float bonus=2000;
public static void main(String
args[]) {
Employee obj=new Employee();
System.out.println("Salary
is:"+obj.salary);
} }
RELATIONSHIP
Uses-A relationship
• A method of one class is using an
object of
relationship
class
the these
two
classes is
another
between
known as Uses-A
relationship.
• As long as the method is execution
the object space (o1) exists and once
the method execution is completed
automatically object memory space
will be destroyed.
RELATIONSHIP
251
SCION RESEARCH AND DEVELOPMENT
Example
class Employee {
float salary=30000; }
class Salary extends Employee {
void disp() {
float bonous=1000;
Employee obj=new Employee();
float Total=obj.salary+bonous;
System.out.println("Total Salary
is:"+Total);
} }
class Developer {
public static void main(String
args[]) {
Salary s=new Salary();
Total Salary is: 31000.0 252
s.disp(); } }
SCION RESEARCH AND DEVELOPMENT
RELATIONSHIP
Output
Note 1: The default relationship in java is Is-A because for each and every class
in java there exist an implicit predefined super class is java.lang.Object.
Note 2: The universal example for Has-A relationship is System.out (in
System.out statement, out is an object of printStream class created as static
data member in another system class and printStream class is known as Has-A
relationship).
Note 3: Every execution logic method (main() ) of execution logic is making
use of an object of business logic class and business logic class is known as
Uses-A relationship.
253
SCION RESEARCH AND DEVELOPMENT
RELATIONSHIP
OOP's Concept in Java
Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
OOPS CONCEPT
254
SCION RESEARCH AND DEVELOPMENT
Object
Object is the physical as well as logical entity where as class is the only logical
entity.
Class
Class is a blue print which is containing only list of variables and method and
no memory is allocated for them. A class is a group of objects that has common
properties.
Encapsulation
Encapsulation is a process of wrapping of data and methods in a single
unit is called encapsulation. Encapsulation is achieved in C++ language by
class concept. The main advantage of using of encapsulation is to secure the
data from other methods, when we make a data private then these data only
use within the class, but these data not accessible outside the class.
255
SCION RESEARCH AND DEVELOPMENT
OOPS CONCEPT
required
256
SCION RESEARCH AND DEVELOPMENT
essential
Abstraction
Abstraction is the concept of exposing only the
characteristics and behavior with respect to a context.
Hiding of data is known as data abstraction. In object oriented programming
language this is implemented automatically while writing the code in the form
of class and object.
Inheritance
The process of obtaining the data members and methods from one class to
another class is known as inheritance. It is one of the fundamental features of
object-oriented programming.
OOPS CONCEPT
Polymorphism
The process of representing one Form in multiple forms is known as
Polymorphism. Here one form represent original form or original method
always resides in base class and multiple forms represents overridden method
which resides in derived classes.
Note: All these concept I will discuss in detail later.
257
SCION RESEARCH AND DEVELOPMENT
OOPS CONCEPT
Inheritance in Java
The process of obtaining the data members and methods from one class to
another class is known as inheritance. It is one of the fundamental features of
object-oriented programming
Important points
• In the inheritance the class which is give data members and methods is
known as base or super or parent class.
• The class which is taking the data members and methods is known as sub or
derived or child class.
• The data members and methods of a class are known as features.
• The concept of inheritance is also known as re-usability or extendable
classes or sub classing or derivation.
258
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
Why use Inheritance ?
• For Method Overriding (used for Runtime Polymorphism).
• It's main uses are to enable polymorphism and to be able to reuse code for
different classes by putting it in a common super class
• For code Re-usability
Syntax of Inheritance
class Subclass-Name extends Superclass-Name
{
//methods and fields
}
Real Life Example of Inheritance in Java
The real life example of inheritance is child and parents, all the properties
INHERITANCE
259
of father are inherited by his son.
SCION RESEARCH AND DEVELOPMENT
In the above diagram data members and methods are represented in broken
line are inherited from faculty class and they are visible in student
260
class logically.
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
The following diagram use view about inheritance.
Advantage of inheritance
If we develop any application using concept of Inheritance than that
application have following advantages,
• Application development time is less.
• Application take less memory.
• Application execution time is less.
• Application performance is enhance (improved).
• Redundancy (repetition) of the code is reduced or minimized so that we get
consistence results and less storage cost.
Note: In Inheritance the scope of access modifier increasing is allow but
decreasing is not allow. Suppose in parent class method access modifier is
default then it's present in child class with default or public or protected
access modifier but not private(it decreased scope).
261
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
Types of Inheritance
Based on number of ways inheriting the feature of base class into derived
class we have five types of inheritance; they are:
• Single inheritance
• Multiple inheritance
• Hierarchical inheritance
• Multilevel inheritance
• Hybrid inheritance
262
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
Single inheritance
In single inheritance there exists single base class and single derived class.
Example of Single Inheritance
class Faculty {
float salary=30000; }
class Science extends
Faculty{ float bonus=2000;
public static void main(String args[])
{ Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonus is:"+obj.bonus);
} }
Output
INHERITANCE
263
Salary is: 30000.0 Bonus is: 2000.0
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
Multilevel inheritances in Java
In Multilevel inheritances there exists
single base class, single derived class
and multiple intermediate base classes.
Single base class + single derived
class + multiple intermediate base
classes.
Intermediate base classes
An intermediate base class is one in one
context with access derived class
and in another context same class
access base class.
264
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
Example of Multilevel Inheritance
class Faculty
{
float total_sal=0, salary=30000;
}
class HRA extends Faculty
{
float hra=3000;
}
class DA extends HRA
{
float da=2000;
}
265
SCION RESEARCH AND DEVELOPMENT
class Science extends DA
{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonous;
System.out.println("Total Salary is:"+obj.total_sal);
}
}
Output
Total Salary is: 37000.0
266
SCION RESEARCH AND DEVELOPMENT
Multiple inheritance
In multiple inheritance there exist multiple classes and single derived class.
The concept of multiple inheritance is not supported in java through
concept of classes but it can be supported through the concept of interface.
267
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
Hybrid inheritance
• Combination of any inheritance type
• In the combination if one of the combination is multiple inheritance then
the inherited combination is not supported by java through the classes
concept but it can be supported through the concept of interface.
INHERITANCE
268
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
Inheriting the feature from base class to derived class
In order to inherit the feature of base class into derived class we use the
following syntax
Syntax
class ClassName-2 extends ClasssName-1
{
variable declaration;
Method declaration;
}
Explanation
• ClassName-1 and
ClassName-2
represents name
of the base and
derived
classes
respectively.
class into derived class it improves the functionality of derived class.269
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
Important Points for Inheritance:
In java programming one derived class can extends only one base class because
java programming does not support multiple inheritance through the concept
of classes, but it can be supported through the concept of Interface. Whenever
we develop any inheritance application first create an object of bottom most
derived class but not for top most base class.
When we create an object of bottom most derived class, first we get the
memory space for the data members of top most base class, and then we get the
memory space for data member of other bottom most derived class. Bottom
most derived class contains logical appearance for the data members of all top
most base classes.
If we do not want to give the features of base class to the derived class then the
definition of the base class must be preceded by final hence final base
270
classes are not reusable or not inheritable.
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
• If we are do not want to give some of the features of base class to derived class
than such features of base class must be as private hence private features of
base class are not inheritable or accessible in derived class.
• Data members and methods of a base class can be inherited into the
derived class but constructors of base class can not be inherited because
every constructor of a class is made for initializing its own data members but
not made for initializing the data members of other classes.
• An object of base class can contain details about features of same class but an
object of base class never contains the details about special features of its
derived class (this concept is known as scope of base class object).
• For each and every class in java there exists an implicit predefined super
class called java.lang.Object. because it providers garbage collection
facilities to its sub classes for collecting un-used memory space and
271
improved the performance of java application.
SCION RESEARCH AND DEVELOPMENT
Example of Inheritance
class Faculty {
float salary=30000;
}
class Science extends Faculty {
float bonus=2000;
public static void main(String args[])
{ Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonus is:"+obj.bonus);
} }
Output
Salary is: 30000.0
272
Bonus is: 2000.0
SCION RESEARCH AND DEVELOPMENT
INHERITANCE
INHERITANCE
Why multiple inheritance is not supported in java?
Due to ambiguity problem java does not support multiple inheritance at class
level.
Example
class A
{
void disp()
{
System.out.println("Hello");
}
}
class B
{
273
void disp()
SCION RESEARCH AND DEVELOPMENT
//Now which disp() method would be invoked?
274
level.
SCION RESEARCH AND DEVELOPMENT
obj.disp();
}
}
In above code we call both class A and class B disp() method then it confusion
which class method is call. So due to this ambiguity problem in java do not use
multiple inheritance at class level, but it support at interface
INHERITANCE
System.out.println("How are you ?");
}
}
class C extends A,B { //suppose if it were
Public Static void main(String args[])
{
C obj=new C();
INHERITANCE
Difference between Java Inheritance and C++ Inheritance
The main difference between java Inheritance and C++ Inheritance is; Java
doesn’t support multiple inheritance but C++ support.
275
SCION RESEARCH AND DEVELOPMENT
METHOD OVERLOADING
Method Overloading in Java
Whenever same method name is exiting multiple times in the same class with
different number of parameter or different order of parameters or different
types of parameters is known as method overloading.
276
SCION RESEARCH AND DEVELOPMENT
METHOD OVERLOADING
Why use method Overloading in Java ?
• Suppose we have to perform addition of given number but there can be any
number of arguments, if we write method such as a(int, int)for two
arguments, b(int, int, int) for three arguments then it is very difficult for
you and other programmer to understand purpose or behaviors of method
they can not identify purpose of method.
• So we use method overloading to easily figure out the program. For example
above two methods we can write sum(int, int) and sum(int, int, int) using
method overloading concept.
Syntax
class class_Name
{
Returntype method() {
277
.........
SCION RESEARCH AND DEVELOPMENT
}
Returntype method(datatype1 variable1) {
.........
}
Returntype method(datatype1 variable1, datatype2 variable2) {
.........
}
Returntype method(datatype2 variable2) {
.........
}
Returntype method(datatype2 variable2, datatype1 variable1) {
.........
}
278
}
SCION RESEARCH AND DEVELOPMENT
METHOD OVERLOADING
By changing number of arguments
In this example, we have created two overloaded methods, first sum method
performs addition of two numbers and second sum method performs addition
of three numbers.
279
SCION RESEARCH AND DEVELOPMENT
Different ways to overload the method
There are two ways to overload the method in java
• By changing number of arguments or parameters
• By changing the data type
METHOD OVERLOADING
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
280
60
}
SCION RESEARCH AND DEVELOPMENT
Output
30
METHOD OVERLOADING
Example Method Overloading in Java
class Addition {
void sum(int a, int b)
{ System.out.println(a+b
);
}
void sum(int a, int b, int c) {
System.out.println(a+b+c);
}
public static void main(String args[])
{ Addition obj=new Addition();
METHOD OVERLOADING
By changing the data type
In this example, we have created two overloaded methods that differs in data
type. The first sum method receives two integer arguments and second sum
method receives two float arguments.
Example Method Overloading in Java
class Addition {
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
281
}
SCION RESEARCH AND DEVELOPMENT
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}
Output
30
25.25
282
SCION RESEARCH AND DEVELOPMENT
METHOD OVERLOADING
Why Method Overloading is not possible by changing the return type of
method?
In java, method overloading is not possible by changing the return type of the
method because there may occur ambiguity. Let's see how ambiguity may
occur: because there was problem:
Example of Method Overloading
class Addition
{
int sum(int a, int b)
{
System.out.println(a+b);
}
double sum(int a, int b)
283
{
SCION RESEARCH AND DEVELOPMENT
//Compile Time Error
284
SCION RESEARCH AND DEVELOPMENT
System.out.println(a+b);
}
public static void main(String args[])
{
Addition obj=new Addition();
int result=obj.sum(20,20);
}
}
Explanation of Code
Example
int result=obj.sum(20,20);
Here how can java determine which sum() method should be called
Note: The scope of overloading is within the class.
Any object reference of class can call any of overloaded method.
Can we overload main() method ?
• Yes, We can overload main() method. A Java class can have any number of
main() methods.
• But run the java program, which class should have main() method with
signature as "public static void main(String[] args).
• If you do any modification to this signature, compilation will
be
successful. But, not run the java program. 285
• we will get the run time error as main method not found.
SCION RESEARCH AND DEVELOPMENT
METHOD OVERLOADING
METHOD OVERLOADING
Example of overload main() method
public class mainclass {
public static void main(String[] args)
{ System.out.println("Execution starts from Main()");
}
void main(int args)
{ System.out.println("Override
main()");
}
double main(int i, double d)
{ System.out.println("Override
main()"); return d;
} }
Output 286
Execution starts from Main()
SCION RESEARCH AND DEVELOPMENT
METHOD OVERRIDING
Method Overriding in Java
Whenever same method name is existing in both base class and derived class
with same types of parameters or same order of parameters is known as
method Overriding. Here we will discuss about Overriding in Java.
Note: Without Inheritance method overriding is not possible.
Advantage of Java Method Overriding
• Method Overriding is used to provide specific implementation of a method
that is already provided by its super class.
• Method Overriding is used for Runtime Polymorphism
Rules for Method Overriding
• method must have same name as in the parent class.
• method must have same parameter as in the parent class.
• must be IS-A relationship (inheritance).
287
SCION RESEARCH AND DEVELOPMENT
288
that is why we use method overriding.
Output : Man walking
SCION RESEARCH AND DEVELOPMENT
Man obj = new Man();
obj.walk();
} }
Problem is that I have to providea specific
implementation of walk() method in
subclass
METHOD OVERRIDING
Understanding the problem without method overriding
Lets understand the problem that we may face in the program if we do not
use method overriding.
Example Method Overriding in Java
class Walking {
void walk(){
System.out.println("Man walking fastly");
} }
class OverridingDemo {
public static void main(String args[]) {
METHOD OVERRIDING
Example of method overriding in Java
In this example, we have defined the walk method in the subclass as defined in
the parent class but it has some specific implementation. The name and
parameter of the method is same and there is IS-A relationship between the
classes, so there is method overriding.
Example
class Walking
{
void walk()
{
System.out.println("Man walking fastly");
}
}
289
SCION RESEARCH AND DEVELOPMENT
290
}
SCION RESEARCH AND DEVELOPMENT
obj.walk();
}
METHOD OVERRIDING
class Man extends walking
{
void walk()
{
System.out.println("Man walking slowly");
}
}
class OverridingDemo
{
public static void main(String args[])
{ Man obj = new Man();
Output
Man walking slowly
METHOD OVERRIDING
Note: Whenever we are calling overridden method using derived class object
reference the highest priority is given to current class (derived class). We can
see in the above example high priority is derived class.
Note: super. (super dot) can be used to call base class overridden method
in the derived class.
291
SCION RESEARCH AND DEVELOPMENT
METHOD OVERRIDING
Accessing properties of base class with respect to derived class object
class A {
int x;
void f1()
{
x=10;
System.o
ut.printl
n(x);
}
void f4()
{ System.out.println("this is
f4()");
System.out.println("-----------------
");
} };
class B extends A {
292
void f1() {
SCION RESEARCH AND DEVELOPMENT
int y=20;
System.out.println(y);
System.out.println("this is f1()");
System.out.println("---------------");
}
};
class C extends A {
int z;
void f1() {
z=10;
System.ou
t.println(z
);
System.ou
t.println("
this is
f1()");
293
};
SCION RESEARCH AND DEVELOPMENT
METHOD OVERRIDING
class Override
{
public static void main(String[] args)
{
A a1=new B();
a1.f1();
a1.f4();
A c1=new C();
c1.f1();
c1.f4();
}
}
294
SCION RESEARCH AND DEVELOPMENT
METHOD OVERRIDING
METHOD OVERRIDING
Example of Implement overriding concept
class Person {
String name;
void
sleep(String
name) {
this.name=na
me;
System.out.pri
ntln(this.nam
e +"is
sleeping+8hr/
day");
}
void walk()
{ System.out.println("this is
walk()");
System.out.println("-----------------");
295
System.out.println("only student write the exam");
SCION RESEARCH AND DEVELOPMENT
296
SCION RESEARCH AND DEVELOPMENT
}
void sleep(String name)
{ super.name=name;
System.out.println(super.n
ame +"is sleeping
6hr/day");
System.out.println("--------
----------");
} };
class Developer extends Person
{ public void designProj() {
System.out.println("Design the
project");
}
void sleep(String name) {
super.name=name;
System.out.println(super.name +"is sleeping 4hr/day");
METHOD OVERRIDING
297
SCION RESEARCH AND DEVELOPMENT
METHOD OVERRIDING
}
};
class OverideDemo
public static void main(String[] args)
{ Student s1=new Student();
s1.writExams();
s1.sleep("student");
s1.walk();
Developer d1=new Developer();
d1.designProj();
d1.sleep("developer");
}
}
298
SCION RESEARCH AND DEVELOPMENT
Overloading Overriding
1
Whenever same method or Constructor
is existing multiple times within a class
either with different number of
parameter or with different type of
parameter or with different order of
parameter is known as Overloading.
Whenever same method name is existing
multiple time in both base and derived
class with same number of parameter or
same type of parameter or same order of
parameters is known as Overriding.
2
Arguments of method must be different
at least arguments.
Argument of method must be same
including order.
3 Method signature must be different. Method signature must be same.
4
Private, static and final methods can be
overloaded.
Private, static and final methods can not
be override.
5
Access modifiers point of view no
restriction.
Access modifiers point of view not
reduced scope of Access modifiers but
increased.
6
Also known as compile time
polymorphism or static polymorphism
or early binding.
Also known as run time polymorphism
or dynamic polymorphism or late
binding.
METHOD OVERLOADING vs. OVERRIDING
299
SCION RESEARCH AND DEVELOPMENT
Overloading Overriding
7
Overloading can be exhibited both are
method and constructor level.
Overriding can be exhibited only at
method label.
8
The scope of overloading is within the
class.
The scope of Overriding is base class
and derived class.
9
Overloading can be done at both static
and non-static methods.
Overriding can be done only at non-
static method.
10
For overloading methods return type may
or may not be same.
For overriding method return type
should be same.
Note: In overloading we have to check only methods names (must be same)
and arguments types (must be different) except these the remaining like
return type access modifiers etc. are not required to check But in overriding
every things check like method names arguments types
return types access modifiers etc.
METHOD OVERLOADING vs. OVERRIDING
INTERFACE IN JAVA
Interface is similar to class which is collection of public static final variables
(constants) and abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be
only abstract methods in the interface. It is used to achieve
fully
abstraction and multiple inheritance in Java.
Why we use Interface ?
• It is used to achieve fully abstraction.
• By using Interface, you can achieve multiple inheritance in java.
• It can be used to achieve loose coupling.
properties of Interface
• It is implicitly abstract. So we no need to use the abstract keyword when
declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract 300
keyword is not needed.
SCION RESEARCH AND DEVELOPMENT
INTERFACE IN JAVA
• Methods in an interface are implicitly public.
• All the data members of interface are implicitly public static final.
How interface is similar to class ?
Whenever we compile any Interface program it generate .class file. That
means the bytecode of an interface appears in a .class file.
How interface is different from class ?
• You can not instantiate an interface.
• It does not contain any constructors.
• All methods in an interface are abstract.
• Interface can not contain instance fields. Interface only contains public static
final variables.
• Interface is can not extended by a class; it is implemented by a class.
• Interface can extend multiple interfaces. It means interface
support 301
multiple inheritance
SCION RESEARCH AND DEVELOPMENT
In the above image when we compile any interface program, by default
compiler added public static final before any variable and public abstract
before any method. Because Interface is design for fulfill universal
302
requirements and to achieve fully abstraction.
SCION RESEARCH AND DEVELOPMENT
INTERFACE IN JAVA
Behavior of compiler with Interface program
Declaring Interfaces:
The interface keyword is used to declare an interface.
Example
interface Person {
datatype variablename=value;
//Any number of final, static fields
returntype methodname(list of parameters or no parameters)
//Any number of abstract method declarations
}
Explanations
In the above syntax Interface is a keyword interface name can be user defined
name the default signature of variable is public static final and for method is
public abstract. JVM will be added implicitly public static final
303
before data members and public abstract before method.
SCION RESEARCH AND DEVELOPMENT
INTERFACE IN JAVA
Example
public static final datatype variable name=value; ----> for data member
public abstract returntype methodname(parameters)---> for method
Implementing Interfaces:
A class uses the implements keyword to implement an interface. The
implements keyword appears in the class declaration following the extends
portion of the declaration.
Example
interface Person {
void run();
}
class Employee implements Person
{ public void run() {
304
System.out.println("Run fast"); } }
SCION RESEARCH AND DEVELOPMENT
INTERFACE IN JAVA
INTERFACE IN JAVA
When we use abstract and when Interface
• If we do not know about any things about implementation just we have
requirement specification then we should be go for Interface
• If we are talking about implementation but not completely (partially
implemented) then we should be go for abstract
Rules for implementation interface
• A class can implement more than one interface at a time.
• A class can extend only one class, but implement many interfaces.
• An interface can extend another interface, similarly to the way that a class
can extend another class.
Relationship between class and Interface
• Any class can extends another class
305
SCION RESEARCH AND DEVELOPMENT
306
• Any class can Implements another Interface
• Any Interface can not extend or Implements any class.
INTERFACE IN JAVA
• Any Interface can extends another Interface.
SCION RESEARCH AND DEVELOPMENT
307
SCION RESEARCH AND DEVELOPMENT
Abstract class Interface
1
It is collection of abstract method and
concrete methods.
It is collection of abstract method.
2
There properties can be reused
commonly in a specific application.
There properties commonly usable in
any application of java environment.
3 It does not support multiple inheritance. It support multiple inheritance.
4
Abstract class is preceded by abstract
keyword.
It is preceded by Interface keyword.
5
Which may contain either variable or
constants.
Which should contains only constants.
6
The default access specifier of abstract
class methods are default.
There default access specifies of
interface method are public.
INTERFACE IN JAVA
Difference between Abstract class and Interface
308
SCION RESEARCH AND DEVELOPMENT
Abstract class Interface
7
These class properties can be reused
in other class using extend keyword.
These properties can be reused in any
other class using implements keyword.
8
Inside abstract class we can take
constructor.
Inside interface we can not take any
constructor.
9
For the abstract class there is no
restriction like initialization of
variable at the time of variable
declaration.
For the interface it should be compulsory
to initialization of variable at the time of
variable declaration.
10
There are no any restriction for
abstract class variable.
For the interface variable can not declare
variable as private, protected, transient,
volatile.
11
There are no any restriction for
abstract class method modifier that
means we can use any modifiers.
For the interface method can not declare
method as strictfp, protected, static,
native, private, final, synchronized.
INTERFACE IN JAVA
// abstract method
309
Run fast
SCION RESEARCH AND DEVELOPMENT
Example of Interface
interface Person
{ void run();
}
class A implements Person
{ public void run()
{ System.out.println("Run
fast");
}
public static void main(String args[])
{ A obj = new A();
obj.run();
} }
Output
INTERFACE IN JAVA
INTERFACE IN JAVA
Multiple Inheritance using interface
Example
interface Developer
{ void disp();
}
interface Manager {
void show();
}
class Employee implements Developer, Manager
{ public void disp() {
System.out.println("Hello Good Morning");
}
public void show() {
310
System.out.println("How are you ?");
SCION RESEARCH AND DEVELOPMENT
}
public static void main(String args[])
{
Employee obj=new Employee();
obj.disp();
obj.show();
}
}
311
SCION RESEARCH AND DEVELOPMENT
Output
Hello Good Morning
How are you ?
INTERFACE IN JAVA
INTERFACE IN JAVA
Marker or tagged interface
An interface that have no member is known as marker or tagged interface. For
example: Serializable, Cloneable, Remote etc. They are used to provide some
essential information to the JVM so that JVM may perform some useful
operation.
Example
public interface Serializable
{
……
}
//Way of writing Serializable interface
312
SCION RESEARCH AND DEVELOPMENT
INTERFACE IN JAVA
Why interface have no constructor ?
• Because, constructor are used for eliminate the default values by user
defined values, but in case of interface all the data members are public
static final that means all are constant so no need to eliminate these values.
• Other reason because constructor is like a method and it is concrete method
and interface does not have concrete method it have only abstract methods
that's why interface have no constructor.
313
SCION RESEARCH AND DEVELOPMENT
ABSTRACTION IN JAVA
Abstraction is the concept of exposing only the required essential
characteristics and behavior with respect to a context.
Hiding of data is known as data abstraction. In object oriented
programming language this is implemented automatically while writing the
code in the form of class and object.
Real Life Example of Abstraction in Java
Abstraction shows only important things to the user and hides the internal
details, for example, when we ride a bike, we only know about how to ride bikes
but can not know about how it work? And also we do not know the internal
functionality of a bike.
31 4
SCION RESEARCH AND DEVELOPMENT
Note: Data abstraction can be used to provide security for the data from the
unauthorized methods.
Note: In Java language data abstraction can achieve using class.
ABSTRACTION IN JAVA
Another real life example of Abstraction is ATM Machine; All are performing
operations on the ATM machine like cash withdrawal, money transfer, retrieve
mini-statement…etc. but we can't know internal details about ATM.
315
SCION RESEARCH AND DEVELOPMENT
Example of Abstraction
class Customer
{ int account_no;
float balance_Amt;
String name;
int age;
String address;
void
balance_inquiry()
{
/* to perform balance inquiry only account number is required that means
remaining properties are hidden for balance inquiry method */ }
void fund_Transfer() {
/* To transfer the fund account number and balance is required and
remaining properties are hidden for fund transfer method */ }
316
SCION RESEARCH AND DEVELOPMENT
ABSTRACTION IN JAVA
ABSTRACTION IN JAVA
How to achieve Abstraction ?
There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (Achieve 100% abstraction)
Read more about Interface and Abstract class in the previous section.
Difference between Encapsulation and Abstraction
Encapsulation is not providing full security because we can access private
member of the class using reflection API, but in case of Abstraction we can't
access static, abstract data member of a class.
317
SCION RESEARCH AND DEVELOPMENT
ENCAPSULATION IN JAVA
Encapsulation is a process of wrapping of data and methods in a single unit is
called encapsulation. Encapsulation is achieved in java language by class
concept.
Combining of state and behavior in a single container is known as
encapsulation. In java language encapsulation can be achieve using class
keyword, state represents declaration of variables on attributes and behavior
represents operations in terms of method.
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other
methods, when we make a data private then these data only use within the
class, but these data not accessible outside the class.
Real life example of Encapsulation in Java
The common example of encapsulation is capsule. In capsule all medicine
318
are encapsulated in side capsule.
SCION RESEARCH AND DEVELOPMENT
Benefits of encapsulation
• Provides abstraction between an object and its clients.
• Protects an object from unwanted access by clients.
• Example: A bank application forbids (restrict) a client to change an
319
Account's balance.
SCION RESEARCH AND DEVELOPMENT
ENCAPSULATION IN JAVA
ENCAPSULATION IN JAVA
Let's see the Example of Encapsulation in java
class Employee
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
}
320
SCION RESEARCH AND DEVELOPMENT
class Demo
{
public static void main(String[] args)
{
Employee e=new Employee();
e.setName("Harry");
System.out.println(e.getName());
}
}
Output
Harry
321
SCION RESEARCH AND DEVELOPMENT
ENCAPSULATION IN JAVA
POLYMORPHISM IN JAVA
The process of representing one form in multiple forms is known as
Polymorphism.
Polymorphism is derived from 2 greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
Polymorphism is not a programming concept but it is one of the principal of
OOPs. For many objects oriented programming language polymorphism
principle is common but whose implementations are varying from one objects
oriented programming language to another object oriented programming
language.
322
SCION RESEARCH AND DEVELOPMENT
POLYMORPHISM IN JAVA
Real life example of polymorphism
Suppose if you are in class room that time you behave like a student, when you
are in market at that time you behave like a customer, when you at your home
at that time you behave like a son or daughter, Here one person present in
different-different behaviors.
323
SCION RESEARCH AND DEVELOPMENT
POLYMORPHISM IN JAVA
How to achieve Polymorphism in Java ?
In java programming the Polymorphism principal is implemented with
method overriding concept of java.
Polymorphism principal is divided into two sub principal they are:
• Static or Compile time polymorphism
• Dynamic or Runtime polymorphism
Note: Java programming does not support static polymorphism because of its
limitations and java always supports dynamic polymorphism.
Let us consider the following diagram
Here original form or original method always resides in base class and multiple
forms represents overridden method which resides in derived
classes.
324
SCION RESEARCH AND DEVELOPMENT
In the above diagram the
sum method which is present
in BC class is called original
form and the sum() method
which are present in DC1 and
DC2 are called overridden
form hence Sum() method is
originally available in only
one form
325
SCION RESEARCH AND DEVELOPMENT
and it
implemented
is
further in
multiple
forms. Hence Sum() method
is one of the polymorphism
method.
POLYMORPHISM IN JAVA
So it is known as runtime
326
}
SCION RESEARCH AND DEVELOPMENT
determined by the JVM not compiler,
polymorphism.
Example of Polymorphism in Java
class Person {
void walk() {
System.out.pri
ntln("Can
Run....");
}
POLYMORPHISM IN JAVA
Example of Runtime Polymorphism in Java
In below example we create two class Person an Employee, Employee class
extends Person class feature and override walk() method. We are calling the
walk() method by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method,
subclass method is invoked at runtime. Here method invocation is
Output
Running fast...
327
SCION RESEARCH AND DEVELOPMENT
POLYMORPHISM IN JAVA
class Employee extends Person
{ void walk() {
System.out.println("Running
Fast...");
}
public static void main(String arg[])
{ Person p=new Employee();
//upcasting p.walk();
}
}
Dynamic Binding
Dynamic binding always says create an object of base class but do not create
the object of derived classes. Dynamic binding principal is always used for
executing polymorphic applications.
The process of binding appropriate versions (overridden method) of derived
classes which are inherited from base class with base class object is known as
dynamic binding.
Advantages of dynamic binding along with polymorphism with method
overriding are.
• Less memory space
• Less execution time
• More performance
328
SCION RESEARCH AND DEVELOPMENT
POLYMORPHISM IN JAVA
Static polymorphism
The process of binding the overloaded method within object at compile time is
known as Static polymorphism due to static polymorphism utilization of
resources (main memory space) is poor because for each and every overloaded
method a memory space is created at compile time when it binds with an object.
In C++ environment the above problem can be solve by using dynamic
polymorphism by implementing with virtual and pure virtual function so most
of the C++ developer in real worlds follows only dynamic polymorphism.
Dynamic polymorphism
In dynamic polymorphism method of the program binds with an object at
runtime the advantage of dynamic polymorphism is allocating the memory
space for the method (either for overloaded method or for override method)
329
at run time.
SCION RESEARCH AND DEVELOPMENT
POLYMORPHISM IN JAVA
Conclusion
The advantage of dynamic polymorphism is effective utilization of the
resources, So Java always use dynamic polymorphism. Java does not support
static polymorphism because of its limitation.
330
SCION RESEARCH AND DEVELOPMENT
POLYMORPHISM IN JAVA
Package in Java
A package is a collection of similar types of classes, interfaces and sub-
packages.
Purpose of package
The purpose of package concept is to provide common classes and
interfaces for any program separately. In other words if we want to develop
any class or interface which is common for most of the java programs than
such common classes and interfaces must be place in a package.
PACKAGE IN JAVA
331
SCION RESEARCH AND DEVELOPMENT
PACKAGE IN JAVA
Packages in Java are the way to organize files when a project has many
modules. Same like we organized our files in Computer. For example we store all
movies in one folder and songs in other folder, here also we store same type of
files in a particular package for example in awt package have all classes and
interfaces for design GUI components.
332
SCION RESEARCH AND DEVELOPMENT
Advantage of package
Package is used to categorize the classes and interfaces so that they can be
easily maintained
• Application development time is less, because reuse the code
• Application memory space is less (main memory)
• Application execution time is less
• Application performance is enhance (improve)
• Redundancy (repetition) of code is minimized
• Package provides access protection.
• Package removes naming collision.
Type of package
Package are classified into two type which are given below.
• Predefined or built-in package
333
• User defined package
SCION RESEARCH AND DEVELOPMENT
PACKAGE IN JAVA
Predefined or built-in package
These are the package which are already designed by the Sun Microsystem
and supply as a part of java API, every predefined package is collection of
predefined classes, interfaces and sub-package.
User defined package
If any package is design by the user is known as user defined package. User
defined package are those which are developed by java programmer and supply
as a part of their project to deal with common requirement.
Rules to create user defined package
• package statement should be the first statement of any package program.
• Choose an appropriate class name or interface name and whose modifier
must be public.
• Any package program can contain only one public class or only one public
interface but it can contain any number of normal classes. 334
PACKAGE IN JAVA
• Package program should not contain any main class (that means it should
not contain any main())
• modifier of constructor of the class which is present in the package must be
public. (This is not applicable in case of interface because interface
have no constructor.)
• The modifier of method of class or interface which is present in the package
must be public (This rule is optional in case of interface because interface
methods by default public)
• Every package program should be save either with public class name or
public Interface name
335
SCION RESEARCH AND DEVELOPMENT
PACKAGE IN JAVA
PACKAGE IN JAVA
336
SCION RESEARCH AND DEVELOPMENT
Compile package programs
For compilation of package program first we save program with public
className.java and it compile using below syntax:
Syntax
javac -d . className.java
Syntax
javac -d path className.java
Explanations: In above syntax "-d" is a specific tool which is tell to java
compiler create a separate folder for the given package in given path. When we
give specific path then it create a new folder at that location and when we use .
(dot) then it crate a folder at current working directory.
Note: Any package program can be compile but can not be execute or run.
These program can be executed through user defined program which are
importing package program. 337
SCION RESEARCH AND DEVELOPMENT
PACKAGE IN JAVA
PACKAGE IN JAVA
Example of package program
Package program which is save with A.java and compile by javac -d . A.java
Example
package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}
Import above class in below program using import
packageName.className
338
SCION RESEARCH AND DEVELOPMENT
Example
import mypack.A;
public class Hello
{
public static void
main(String
arg[])
{
A a=new A();
a.show();
System.out.pr
intln("show()
class A");
}
}
Explanation
s: In the
339
import class "
A"in class Hello using "import mypack.A;" statement.
SCION RESEARCH AND DEVELOPMENT
PACKAGE IN JAVA
PACKAGE IN JAVA
Difference between Inheritance and package
• Inheritance concept always used to reuse the feature within the program
between class to class, interface to interface and interface to class but not
accessing the feature across the program.
• Package concept is to reuse the feature both within the program and across
the programs between class to class, interface to interface and interface to
class.
Difference between package keyword and import keyword
• Package keyword is always used for creating the undefined package and
placing common classes and interfaces.
• import is a keyword which is used for referring or using the classes and
interfaces of a specific package.
340
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
The process of converting system error messages into user friendly error
message is known as Exception handling. This is one of the powerful feature
of Java to handle run time error and maintain normal flow of java application.
Exception
An Exception is an event, which occurs during the execution of a program,
that disrupts the normal flow of the program's Instructions.
Why use Exception Handling
Handling the exception is nothing but converting system error generated
message into user friendly error message. Whenever an exception occurs in the
java application, JVM will create an object of appropriate exception of sub class
and generates system error message, these system generated messages are not
understandable by user so need to convert it into user
341
friendly error message.
SCION RESEARCH AND DEVELOPMENT
You can convert system error message into user friendly error message by
using exception handling feature of java.
For Example: when you divide any number by zero then system generate / by
zero
so this is not understandable by user so you can convert this message into user
friendly error message like Don't enter zero for denominator.
342
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
Hierarchy of Exception classes
343
SCION RESEARCH AND DEVELOPMENT
Type of Exception
• Checked Exception
• Un-Checked Exception
Checked Exception
Checked Exception are the exception which checked at compile-time.
These exception are directly sub-class of java.lang.Exception class.
Only for remember: Checked means checked by compiler so checked
exception are checked at compile-time.
EXCEPTION HANDLING IN JAVA
344
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Un-Checked Exception
Un-Checked Exception are the exception both identifies or raised at run time.
These exception are directly sub-class of java.lang.RuntimeException class.
Note: In real time application mostly we can handle un-checked exception.
Only for remember: Un-checked means not checked by compiler so un-
checked exception are checked at run-time not compile time.
345
SCION RESEARCH AND DEVELOPMENT
Checked Exception Un-Checked Exception
1
checked Exception are checked
at compile time
un-checked Exception are checked at run time
2
e.g. FileNotFoundException,
NumberNotFoundException etc.
e.g. ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException etc.
346
SCION RESEARCH AND DEVELOPMENT
Difference between Error and Exception
Error Exception
1 Can't be handle. Can be handle.
2
Example:
NoSuchMethodError
OutOfMemoryError
Example:
ClassNotFoundException
NumberFormateException
EXCEPTION HANDLING IN JAVA
Difference between checked Exception and un-checked Exception
EXCEPTION HANDLING IN JAVA
Handling the Exception
Handling the exception is nothing but converting system error generated
message into user friendly error message in others word whenever an
exception occurs in the java application, JVM will create an object of
appropriate exception of sub class and generates system error message, these
system generated messages are not understandable by user so need to convert
it into user-friendly error message. You can convert system error message into
user-friendly error message by using exception handling feature of java.
Use Five keywords for Handling the Exception
• try
• catch
• finally
• throws
• throw
347
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Syntax for handling the exception
Syntax
Try {
//
state
ment
s
cause
s
probl
em at
run
time
}
catch(
type of
excepti
on-1
object-
1) {
// statements which will execute compulsory
}
SCION RESEARCH AND DEVELOPMENT
348
EXCEPTION HANDLING IN JAVA
Example without Exception Handling
Syntax
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
System.out.printl
n("Denominator
not be zero");
}
}
Abnormally terminate program and give a message like below, this error
message is not understandable by user so we convert this error message
349
into user friendly error message, like "denominator not be zero".
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Example of Exception Handling
class ExceptionDemo {
public static void main(String[] args)
{ int a=10, ans=0;
Try {
ans=a/0;
}
catch (Exception e)
{ System.out.println("Denominator not be zero");
}
}
}
Output
350
Denominator not be zero
SCION RESEARCH AND DEVELOPMENT
try block
Inside try block we write the block of statements which causes executions
block always contains problematic
at run time in other words try
statements.
Important points about try block
• If any exception occurs in try block then CPU controls comes out to the try
block and executes appropriate catch block.
• After executing appropriate catch block, even through we use run time
statement, CPU control never goes to try block to execute the rest of the
statements.
• Each and every try block must be immediately followed by catch block that
is no intermediate statements are allowed between try and catch block.
EXCEPTION HANDLING IN JAVA
351
SCION RESEARCH AND DEVELOPMENT
Syntax
Try {
.....
}
/* Here no other statements are allowed
between try and catch block */
catch() {
....
}
• Each and every try block must contains at least one catch block. But it is
highly recommended to write multiple catch blocks for
generating
multiple user friendly error messages.
• One try block can contains another try block that is nested or inner try
352
block can be possible.
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Syntax
Try { .......
Try { ....... } }
catch block
• Inside catch block we write the block of statements which will generates
user friendly error messages.
• catch block important points
• catch block will execute exception occurs in try block.
• You can write multiple catch blocks for generating multiple user friendly
error messages to make your application strong. You can see below example.
• At a time only one catch block will execute out of multiple catch blocks.
• in catch block you declare an object of sub class and it will be internally
353
referenced by JVM.
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Multiple catch block
You can write multiple catch blocks for generating multiple user friendly error
messages to make your application strong. You can see below example.
Example
import java.util.*; class
ExceptionDemo {
public static void main(String[] args)
{ int a, b, ans=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter any two numbers: ");
try {
a=s.nextInt();
354
b=s.nextInt();
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
ans=a/b;
System.out.println("Result: "+ans); }
catch(ArithmeticException ae)
{ System.out.println("Denominator not be zero");
}
catch(Exception e)
{ System.out.println("Enter valid number");
}
}
}
Output
Enter any two number: 5 0
355
Denominator not be zero
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
356
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
finally Block in Exception Handling
Inside finally block we write the block of statements which will relinquish
(released or close or terminate) the resource (file or database) where data store
permanently.
finally block important points
• Finally block will execute compulsory
• Writing finally block is optional.
• You can write finally block for the entire java program
• In some of the circumstances one can also write try and catch block in finally
block.
357
SCION RESEARCH AND DEVELOPMENT
Example
class ExceptionDemo {
public static void main(String[] args)
{ int a=10, ans=0;
Try {
ans=a/0;
}
catch (Exception e)
{ System.out.println("Denominator not be zero");
}
Finally {
System.out.println("I am from finally block");
}
} }
Output
Denominator not be zero
I am from finally block
EXCEPTION HANDLING IN JAVA
358
SCION RESEARCH AND DEVELOPMENT
• ClassNotFoundException
• IOException
• InterruptedException
Un-Checked Exception Classes
• ArithmeticException
• ArrayIndexOutOfBoundsException
• StringIndexOutOfBoundsException
• NumberFormateException
• NullPointerException
• NoSuchMethodException
• NoSuchFieldException
EXCEPTION HANDLING IN JAVA
Exception Classes in Java
Exception are mainly classified into two type checked exception and un-
checked exception.
Checked Exception Classes
• FileNotFoundException
EXCEPTION HANDLING IN JAVA
FileNotFoundException
If the given filename is not available in a specific location ( in file handling
concept) then FileNotFoundException will be raised. This exception will be
thrown by the FileInputStream, FileOutputStream, and RandomAccessFile
constructors.
ClassNotFoundException
If the given class name is not existing at the time of compilation or running of
program then ClassNotFoundException will be raised. In other words this
exception is occured when an application tries to load a class but no definition
for the specified class name could be found.
359
SCION RESEARCH AND DEVELOPMENT
IOException
This is exception is raised whenever problem occurred while writing and
reading the data in the file. This exception is occurred due to following reason;
• When try to transfer more data but less data are present.
• When try to read data which is corrupted.
• When try to write on file but file is read only.
InterruptedException
This exception is raised whenever one thread is disturb the other thread. In
other words this exception is thrown when a thread is waiting, sleeping, or
otherwise occupied, and the thread is interrupted, either before or during the
activity.
369
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
ArithmeticException
This exception is raised because of problem in arithmetic operation like divide
by zero. In other words this exception is thrown when an exceptional
arithmetic condition has occurred. For example, an integer "divide by zero".
Example
class ExceptionDemo {
public static void main(String[] args)
{ int a=10, ans=0;
Try
{ ans=a/
0;
}
catch
(Exceptio
n e) {
System.o
361
} } }
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
ArrayIndexOutOfBoundsException
This exception will be raised whenever given index value of an array is out of
range. The index is either negative or greater than or equal to the size of the
array.
Example
int a[]=new int[5];
a[10]=100; //ArrayIndexOutOfBoundsException
362
SCION RESEARCH AND DEVELOPMENT
StringIndexOutOfBoundsException
This exception will be raised whenever given index value of string is out of
range. The index is either negative or greater than or equal to the size of the
array.
Example
String s="Hello";
s.charAt(3);
s.charAt(10);
// Exception raised chatAt() is a predefined method of string class used to get
the individual characters based on index value.
363
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
NumberFormateException
This exception will be raised whenever you trying to store any input value in
the un-authorized datatype.
Example: Storing string value into int datatype.
Example
int a;a="Hello";
Example
String s="hello"; int i=Integer.parseInt(s);//NumberFormatException
NoSuchMethodException
This exception will be raised whenever calling method is not existing in the
program.
364
SCION RESEARCH AND DEVELOPMENT
Example
String s=null;
System.out.println(s.length());
365
SCION RESEARCH AND DEVELOPMENT
//NullPointerException
StackOverFlowException
This exception throw when full the stack because the recursion method are
stored in stack area.
EXCEPTION HANDLING IN JAVA
NullPointerException
A NullPointerException is thrown when an application is trying to use or
access an object whose reference equals to null.
EXCEPTION HANDLING IN JAVA
Difference Between Throw and Throws Keyword
throw
throw is a keyword in java language which is used to throw any user defined
exception to the same signature of method in which the exception is raised.
Note: throw keyword always should exist within method body.
whenever method body contain throw keyword than the call method should be
followed by throws keyword.
366
SCION RESEARCH AND DEVELOPMENT
Syntax
class className
{
returntype method(...) throws Exception_class
{
throw(Exception obj)
}
}
367
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
throws
throws is a keyword in java language which is used to throw the exception
which is raised in the called method to it's calling method throws keyword
always followed by method signature.
Example
returnType methodName(parameter)throws Exception_class....
{
.....
}
368
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
throw throws
1
throw is a keyword used for hitting and
generating the exception which are
occurring as a part of method body
throws is a keyword which gives an indication
to the specific method to place the common
exception methods as a part of try and catch
block for generating user friendly error
messages
2
The place of using throw keyword is
always as a part of method body.
The place of using throws is a keyword is
always as a part of method heading
3
When we use throw keyword as a part
of method body, it is mandatory to the
java programmer to write throws
keyword as a part of method heading
When we write throws keyword as a part of
method heading, it is optional to the java
programmer to write throw keyword as a part
of method body.
369
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Difference between throw and throws
EXCEPTION HANDLING IN JAVA
Example of throw and throws
// save by DivZero.java
package pack;
public class DivZero {
public void division(int
a, int b)throws
ArithmeticException {
if(b==0) {
ArithmeticException ae=new ArithmeticException("Does not enter zero for
Denominator");
throw ae;
}
else {
int c=a/b;
System.out.println("Result: "+c);
370
} } } Compile: javac -d . DivZero.java
SCION RESEARCH AND DEVELOPMENT
Example
// save by ArthException.java
import pack.DivZero;
import java.util.*;
class ArthException
{
public static void main(String
args[])
{
System.out.println("Enter any two number: ");
Scanner s=new Scanner(System.in);
try
{
int a=s.nextInt(); 371
int b=s.nextInt();
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
DivZero dz=new DivZero();
dz.division(a, b);
}
catch(Exception e)
{
System.err.println(e);
}
}
}
372
SCION RESEARCH AND DEVELOPMENT
Steps to Compile and Run code
First you save throw-example files into you PC in any where, here i will save
this file in C:>
C:throw-example>javac -d . DivZero.java C:
throw-example>javac ArthException.java
Note: First compile DivZero.java code then compile ArthException.java3co7d3e.
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Compile: javac ArthException.java
EXCEPTION HANDLING IN JAVA
Custom Exception in Java
If any exception is design by the user known as user defined or Custom
Exception. Custom Exception is created by user.
Rules to design user defined Exception
• Create a package with valid user defined name.
• Create any user defined class.
• Make that user defined class as derived class of Exception
or RuntimeException class.
• Declare parameterized constructor with string variable.
• call super class constructor by passing string variable within the derived class
constructor.
• Save the program with public class name.java
374
SCION RESEARCH AND DEVELOPMENT
Example
// save by AgeException.java
package nage;
public class AgeException extends Exception
{ public AgeException(String s) {
super(s);
375
} }
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
Compile: javac -d . AgeException.java
Example : // save by CheckAge.java
package nage;
public class CheckAge {
public void verify(int age)throws
AgeException {
if (age>0)
{ System.err.print("valid
age");
}
Else {
AgeException ae=new AgeException("Invalid age");
throw(ae);
}
}
376
}
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Compile: javac -d . CheckAge.java
Example :
// save by VerifyAgeException
import nage.AgeException;
import nage.CheckAge;
import java.util.*;
public class VerifyAgeException
{
public static void main(String
args[])
{
int a;
System.out.println("Enter your
age");
Scanner s=new
Scanner(System.in);
377
a=s.nextInt();
SCION RESEARCH AND DEVELOPMENT
try
{
CheckAge ca=new CheckAge();
ca.verify(a);
}
catch(AgeException ae)
{
Syso("Age should not be -ve");
}
catch(Exception e)
{ System.err.println(e
);
}
} 378
}
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Steps to compile and run above program
First you save verify-age files into you PC in any where, here i will save this file in
C:>
C:verify-age>javac -d . AgeException.java
C:verify-age>javac -d . CheckAge.java
C:verify-age>javac VerifyAgeException.java
Note: First compile AgeException.java code
then CheckAge.java and at last 379
compile VerifyAgeException.java code.
SCION RESEARCH AND DEVELOPMENT
EXCEPTION HANDLING IN JAVA
Compile: javac VerifyAgeException.java
MULTITHREADING IN JAVA
Multithreading in java is a process of executing multiple threads
simultaneously. The aim of multithreading is to achieve the concurrent
execution.
Thread
Thread is a lightweight components and it is a flow of control. In other
words a flow of control is known as thread.
State or Life cycle of thread
State of a thread are classified into five types they are
• New State
• Ready State
• Running State
• Waiting State
• Halted or dead State
380
SCION RESEARCH AND DEVELOPMENT
New State
If any new thread class is created that represent new state of a thread, In new
state thread is created and about to enter into main memory. No memory is
available if the thread is in new state.
Ready State
In ready state thread will be entered into main memory, memory space is
allocated for the thread and 1st time waiting for the CPU.
Running State
381
Whenever the thread is under execution known as running state.
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
Halted or dead State
If the thread execution is stopped permanently than it comes under dead state,
no memory is available for the thread if its comes to dead state.
Note: If the thread is in new or dead state no memory is available but
sufficient memory is available if that is in ready or running or waiting state.
Achieve multithreading in java
In java language multithreading can be achieve in two different ways.
• Using thread class
• Using Runnable interface
382
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
Using thread class
• In java language multithreading program can be created by following below
rules.
• Create any user defined class and make that one as a derived class of
thread class.
class Class_Name extends Thread{........}
• Override run() method of Thread class (It contains the logic of perform any
operation)
• Create an object for user-defined thread class and attached that object to
predefined thread class object.
Class_Name obj=new Class_Name
Thread t=new Thread(obj);
• Call start() method of thread class to execute run() method.
383
• Save the program with filename.java
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
MULTITHREADING IN JAVA
384
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
Example of multithreading using Thread class
Thread based program for displaying 1 to 10 numbers after each and every
second.
// Threaddemo2.java
class Th1 extends Thread
{
public void run()
{
try
{
for(int i=1;i< =10;i++)
{
System.out.println("value of i="+i);
385
Thread.sleep(1000);
SCION RESEARCH AND DEVELOPMENT
}
}
catch(InterruptedException ie)
{
System.err.println("Problem in thread execution");
}
}
}
class Threaddemo2
{
public static void main(String args[])
{
Th1 t1=new Th1();
386
System.out.println("Execution status of t1 before start="+t1.isAlive());
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
t1.start();
System.out.println("Execution status of t1 before start="+t1.isAlive());
try
{
Thread.sleep(5000);
}
catch(InterruptedException ie)
{
System.out.println("Problem in thread execution");
}
System.out.println("Execution status of t1 during
execution="+t1.isAlive());
Try
{ 387
Thread.sleep(5001);
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
}
catch(InterruptedException ie)
{
System.out.println("problem in thread execution");
}
System.out.println("Execution status of t1 after completation="+t1.isAlive());
}
}
388
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
Output
Execution status of t1 before start=false //new state
10 Execution status of t1 after completion=false //halted state
389
SCION RESEARCH AND DEVELOPMENT
//ready state
Execution status of t1 after start=true
1
2
3
4
5
//running state
6 Execution status of t1 during execution=true 7
8
9
MULTITHREADING IN JAVA
MULTITHREADING IN JAVA
Thread class properties
Thread class contains constant data members, constructors, predefined
methods.
Constant data members
• MAX-PRIORITY
• MIN-PRIORITY
• NORM-PRIORITY
MAX-PRIORITY
Which represent the minimum priority that a thread can have whose values is
10.
Syntax: public static final int MAX-PRIORITY=10
MIN-PRIORITY
Which represents the minimum priority that a thread can have.
390
Syntax: public static final int MIN-PRIORITY=0
SCION RESEARCH AND DEVELOPMENT
NORM-PRIORITY
Which represent the default priority that is assigned to a thread.
Syntax: public static final int NORM-PRIORITY=5
Constructors of Thread class
• Thread()
• Thread(String name)
• Thread(object)
• Thread(object, String name)
Thread()
Which will be execute to set the predefined name for newly created thread,
these names are generally in the form of thread -0, thread -1,
....
Syntax to call constructor:
Syntax 391
Thread t=new Thread();
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
Thread(String name)
Which can be used to provide user defined name for newly created thread.
Syntax : Thread t=new Thread("newthread");
Thread(object)
Which can be used to provide default name for newly created user defined
thread.
Syntax : UserdefinedThreadclass obj=new UserdefinedThreadclass();
Thread t=new Thread("obj");
Thread(object, String name)
Which will be used to provide user defined name for the newly created user
defined thread.
Syntax : UserdefinedThreadclass obj=new UserdefinedThreadclass();
Thread t=new Thread(object, "secondthread");
392
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
• getPriority()
• setPriority()
• getName()
• setName()
• isDeamon()
• run()
• start()
• sleep()
393
SCION RESEARCH AND DEVELOPMENT
• suspend()
• resume()
• stop()
• isAlive()
• currentThread()
• join()
• getState()
• yield()
MULTITHREADING IN JAVA
Methods of Thread class
getPriority()
This method is used to get the current priority of thread.
Thread t=new Thread();
int x=t.getPriority();
System.out.println(x);
setPriority()
This method is used to
set the current priority
of thread.
Thread t=new Thread();
t.setPriority(any priority number between o to 10)
or
t.setPriority(Thread.MAX-PRIORITY)
394
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
getName()
This method is used to get the current executing thread name.
Thread t=new Thread();
String s=t.getName();
System.out.println(s);
setName()
This method is used to
set the userdefined
name for the thread.
Thread t=new Thread();
t.setName("mythread");
isDeamon()
Which returns true if
the current thread is
background thread
otherwise
return false.
395
boolean b=t.isDeamon();
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
run()
Which contains the main business logic that can be executed by multiple
threads simultaneously in every user defined thread class run method
should be overridden.
public Class_Name extends Thread
{
public void run() {
.....
}
}
start()
Used to convert ready state thread to running state.
Thread t=new Thread();
396
t.start();
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
sleep()
Used to change running state thread to ready state based on time period it is a
static method should be called with class reference.
public static final sleep(long milisecond)throws InterruptedException
{
try
{ Thread.sleep(3000)
;
}
catch(InterruptedEx
ception ie)
{ ........
}
}
Once the given time
period is completed
thread state
397
from waiting to running state.
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
suspend()
Used to convert running state thread to waiting state, which will never come
back to running state automatically.
Thread t=new Thread();
t.suspend();
resume()
Used to change the suspended thread state(waiting state) to ready state.
Thread t=new Thread();
t.resume();
Note: Without using
suspend() method
resume() method can
not be use.
398
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
MULTITHREADING IN JAVA
What is the difference between sleep() and suspend()
• Sleep() can be used to convert running state to waiting state and
automatically thread convert from waiting state to running state once the
given time period is completed.
• Where as suspend() can be used to convert running state thread to
waiting state but it will never return back to running state automatically.
stop()
This method is used to convert running state thread to dead state.
Thread t=new Thread();
t.stop();
isAlive()
Which is return true if
the thread is in ready or
running or waiting state
and return false if the
thread is in new or dead
state.
399
Thread t=new Thread(); t.isAlive();
SCION RESEARCH AND DEVELOPMENT
currentThread()
Used to get the current thread detail like thread name thread group name and
priority
Thread t=new Thread();
t.currentThread();
Note: The default thread name is thread-0,
(if it is a main thread default name is main)
The default thread group name is main
Default thread priority is "5" is normal
priority.
join()
Which can be used to combined more than
one thread into a single group
400
signature is public final void join()throws InterruptedException
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
try
{
t.join();
t2.join();
.....
}
getState()
This method is used to get the current state of thread.
Thread t=new Thread();
t.getState();
yield()
Which will keep the
currently executing
thread into temporarily
pass and
allows other threads to
execute
401
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
MULTITHREADING IN JAVA
Using Runnable Interface
• Runnable is one of the predefined interface in java.lang package, which is
containing only one method and whose prototype is " Public abstract void
run "
• The run() method of thread class defined with null body and run() method
of Runnable interface belongs to abstract. Industry is highly recommended
to override abstract run() method of Runnable interface but not
recommended to override null body run() method of thread class.
• In some of the circumstance if one derived class is extending some type of
predefined class along with thread class which is not possible because
java programming never supports multiple inheritance. To avoid this
multiple inheritance problem, rather than extending thread class we
402
implement Runnable interface.
SCION RESEARCH AND DEVELOPMENT
403
class Class_Name implement Runnable
{ public void run() {
........
}
}
Class_Name obj=new Class_name();
Thread t=new Thread();
MULTITHREADING IN JAVA
Rules to create the thread using Runnable interface
• Create any user defined class and implements runnable interface within
that
• Override run() method within the user defined class.
• call start() method to execute run() method of thread class
• Save the program with classname.java
Note: While implementing runnable
interface it is very mandatory to
extending Thread class.
t.start();
SCION RESEARCH AND DEVELOPMENT
attach user defined thread class
object reference to predefined
thread class object reference. It is
optional while creating thread by
MULTITHREADING IN JAVA
Thread Synchronization
Whenever multiple threads are trying to use same resource than they may be
chance to of getting wrong output, to overcome this problem thread
synchronization can be used.
Definition: Allowing only one thread at a time to utilized the same resource
out of multiple threads is known as thread synchronization or thread safe.
In java language thread synchronization can be achieve in two different ways.
• Synchronized block
• Synchronized method
Note: synchronization is a keyword (access modifier in java)
404
SCION RESEARCH AND DEVELOPMENT
Synchronized block
Whenever we want to execute one or more than one statement by a single
thread at a time(not allowing other thread until thread one execution is
completed) than those statement should be placed in side synchronized
block.
class Class_Name implement Runnable or extends Thread
{ public void run() {
synchronized(this) {
.......
.......
}
}
}
405
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
Synchronized method
Whenever we want to allow only one thread at a time among multiple thread
for execution of a method than that should be declared as synchronized
method.
class Class_Name implement Runnable or extends Thread {
public void run()
{ synchronized void fun()
{
.......
.......
}
public void run() {
fun();
.... 406
} }
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
MULTITHREADING IN JAVA
Interthread Communication
The process of execution of exchanging of the data / information between
multiple threads is known as Interthread communication or if an output of
first thread giving as an input to second thread the output of second thread
giving as an input to third thread then the communication between first
second and third thread known as Interthread communication.
In order to develop Interthread communication application we use some of the
methods of java.lang.Object class and these methods are known as Interthread
communication methods.
Interthread communication methods
• public final void wait(long msec)
• public final void wait()
• public final void notify()
407
• public final void notifyAll()
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
public final void wait(long msec)
public final void wait (long msec) is used for making the thread to wait by
specifying the waiting time in terms of milliseconds. Once the waiting time is
completed, automatically the thread will be interred into ready state from
waiting state.
This methods is not recommended to used to make next thread to wait on the
basis of time because java programmer may not be able to decide or determine
the CPU burst time of current thread and CPU burst time is decided by OS but
not by the programmer.
public final void wait()
public final void wait() is used for making the thread to wait without
specifying any waiting time this method is recommended to use to make
the next thread to wait until current thread complete its execution.
408
SCION RESEARCH AND DEVELOPMENT
MULTITHREADING IN JAVA
public final void notify()
public final void notify() is used for transferring one thread at a time from
waiting state to ready state.
public final void notifyAll()
public final void notifyAll() is used for transferring all the threads at a time
from waiting state to ready state.
Note: public final void wait (long msec) and public final void wait() throws a
predefined Exception called java.lang.InterruptedException.
409
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
String Handling in Java
• The basic aim of String Handling concept is storing the string data in the
main memory (RAM), manipulating the data of the String, retrieving the
part of the String etc.
• String Handling provides a lot of concepts that can be performed on a
string such as concatenation of string, comparison of string, find sub string
etc.
Character
It is an identifier enclosed within single quotes (' ').
Example: 'A', '$', 'p'
String:
String is a sequence of characters enclosed within double quotes (" ") is
known as String.
410
Example: "Java Programming".
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
In java programming to store the character data we have a fundamental
datatype called char. Similarly to store the string data and to perform various
operation on String data, we have three predefined classes they are:
• String
• StringBuffer
• StringBuilder
String class
• It is a predefined class in java.lang package can be used to handle the String.
String class is immutable that means whose content can not be changed at
the time of execution of program.
• String class object is immutable that means when we create an object of
String class it never changes in the existing object.
411
SCION RESEARCH AND DEVELOPMENT
Example
class StringHandling
{
public static void main(String arg[])
{
String s=new String("java");
s.concat("software");
System.out.println(s);
}
}
Output
java
Explanation: Here we can
not change the object of
String class so output is
412
only java not java software.
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
STRING HANDLING IN JAVA
Methods of String class
length()
length(): This method is
used to get the number of
character of any string.
Example
class StringHandling {
public static void main(String arg[])
{ int l;
String s=new String("Java");
l=s.length();
System.out.println("Length: "+l);
}
}
Output
413
Length: 4
SCION RESEARCH AND DEVELOPMENT
charAt(index)
charAt(): This method is used to get the character at a given index value.
Example
class StringHandling {
public static void main(String arg[])
{
char c;
String s=new String("Java");
c=s.charAt(2);
System.out.println("Character: "+c);
}
}
Output
414
Character: v
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
toUpperCase()
toUpperCase(): This method is use to convert lower case string into upper case.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java";
System.out.println("String: "+s.toUpperCase());
}
}
Output
415
String: JAVA
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
toLowerCase()
toLowerCase(): This method is used to convert lower case string into upper
case.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="JAVA";
System.out.println("String: "+s.toLowerCase());
}
}
Output
416
String: java
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
concat()
concat(): This method is used to combined two string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
System.out.println(
"Combined String:
"+s1.concat(s2));
}
}
Output
417
Combined String: HiteshRaddy
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
equals()
equals(): This method is used to compare two strings, It return true if strings
are same otherwise return false. It is case sensitive method.
Example
class StringHandling {
public static void main(String arg[])
{ String s1="Hitesh";
String s2="Raddy";
String s3="Hitesh";
System.out.println("Compare String: "+s1.equals(s2));
System.out.println("Compare String: "+s1.equals(s3)); } }
Output
Compare String: false
418
Compare String: true
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
equalsIgnoreCase()
equalsIgnoreCase(): This method is case insensitive method, It return true if
the contents of both strings are same otherwise false.
Example
class StringHandling {
public static void main(String arg[])
{ String s1="Hitesh";
String s2="HITESH";
String s3="Raddy";
System.out.println("Compare String: "+s1.equalsIgnoreCase(s2));
System.out.println("Compare String: "+s1.equalsIgnoreCase(s3)); } }
Output
Compare String: true
419
Compare String: false
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
compareTo()
compareTo(): This method is used to compare two strings by taking unicode
values, It return 0 if the string are same otherwise return +ve or - ve integer
values.
Example
class StringHandling {
public static void main(String arg[])
{ String s1="Hitesh";
System.out.println("Strings are same"); }
Else { System.out.println("Strings are not same"); } } }
SCION RESEARCH AND DEVELOPMENT
420
String s2="Raddy";
int i;
i=s1.compareTo(s2);
if(i==0) {
Output
Strings are not same
STRING HANDLING IN JAVA
String s1="Hitesh";
String s2="HITESH";
int i;
i=s1.compareToIgnoreCase(s2);
if(i==0) {
}
Else { System.out.println("Strings are not same"); } } }
SCION RESEARCH AND DEVELOPMENT
421
System.out.println("Strings are same");
Output
Strings are same
STRING HANDLING IN JAVA
compareToIgnoreCase()
compareToIgnoreCase(): This method is case insensitive method, which is used
to compare two strings similar to compareTo().
Example
class StringHandling {
public static void main(String arg[]) {
startsWith()
startsWith(): This method return true if string is start with given another
string, otherwise it returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.startsWith("Java"));
}
}
Output
422
true
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
423
SCION RESEARCH AND DEVELOPMENT
true
STRING HANDLING IN JAVA
endsWith()
endsWith(): This method return true if string is end with given another string,
otherwise it returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.endsWith("language"));
}
}
Output
subString()
subString(): This method is used to get the part of given string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8)); // 8 is starting index
}
}
Output
programming language
424
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8, 12));
}
}
Output
prog
425
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
indexOf()
indexOf(): This method is used find the index value of given string. It always
gives starting index value of first occurrence of string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.indexOf("programming"));
}
}
Output
8
SCION RESEARCH AND DEVELOPMENT
426
STRING HANDLING IN JAVA
lastIndexOf()
lastIndexOf(): This method used to return the starting index value of last
occurence of the given string.
Example
class StringHandling {
public static void main(String arg[]) { String
s1="Java is programming language";
String s2="Java is good programming language";
System.out.println(s1.lastIndexOf("programming"));
System.out.println(s2.lastIndexOf("programming"));
} }
Output
8
13
SCION RESEARCH AND DEVELOPMENT
427
STRING HANDLING IN JAVA
trim()
trim(): This method remove space which are available before starting of
string and after ending of string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s=" Java is programming language ";
System.out.println(s.trim());
}
}
Output
428
Java is programming language
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
split()
split(): This method is used to divide the given string into number of parts
based on delimiter (special symbols like @ space , ).
Example
class StringHandling {
public static void main(String arg[])
{ String s="contact@tutorial4us.com";
String[] s1=s.split("@"); // divide string based on @
for(String c:s1) // foreach loop
{
System.out.println(c); } } }
Output
contact
429
@tutorial4us.com
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
replace()
replace(): This method is used to return a duplicate string by replacing old
character with new character.
Note: In this method data of original string will never be modify.
Example
class StringHandling {
public static void main(String arg[])
{ String s1="java";
String s2=s1.replace('j', 'k');
System.out.println(s2);
}
}
Output
430
kava
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
STRING HANDLING IN JAVA
StringBuffer Class in Java
• It is a predefined class in java.lang package can be used to handle the String,
whose object is mutable that means content can be modify.
• StringBuffer class is working with thread safe mechanism that means
multiple thread are not allowed simultaneously to perform operation of
StringBuffer.
• StringBuffer class object is mutable that means when we create an object of
StringBulder class it can be change.
Explanation: Here we can changes in the existing object of StringBuffer class
so output is javasoftware.
431
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
Example StringBuffer
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java");
sb.append("software");
System.out.println(sb);
}
}
Output
javasoftware
432
SCION RESEARCH AND DEVELOPMENT
String StringBuffer
The data which enclosed within double
quote (" ") is by default treated as String
class.
The data which enclosed within double
quote (" ") is not by default treated as
StringBuffer class
String class object is immutable StringBuffer class object is mutable
When we create an object of String class
by default no additional character
memory space is created.
When we create an object of StringBuffer
class by default we get 16 additional
character memory space.
433
• We can not override the method of String and StringBuffer.
SCION RESEARCH AND DEVELOPMENT
Similarities Between String and StringBuffer
• Both of them are belongs to public final. so that they never participates
in inheritance that is is-A relationship is not possible but they can always
participates in As-A and Uses-A relationship.
STRING HANDLING IN JAVA
Difference Between String and StringBuffer
STRING HANDLING IN JAVA
Methods of StringBuffer class
reverse()
reverse(): This method is used to reverse the given string and also the new
value is replaced by the old string.
Example
class StringHandling {
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java code");
System.out.println(sb.reverse());
}
}
Output
434
edoc avaj
SCION RESEARCH AND DEVELOPMENT
insert()
insert(): This method is used to insert either string or character or integer or
real constant or boolean value at a specific index value of given string.
Example
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("this is my java code");
System.out.println(sb.insert(11, "first "));
}
}
Output
435
this is my first java code
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
append()
append(): This method is used to add the new string at the end of original
string.
Example
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java is easy");
System.out.println(sb.append(" to learn"));
}
}
Output
436
java is easy to learn
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
replace()
replace() This method is used to replace any old string with new string based
on index value.
Example
class StringHandling {
public static void main(String arg[]) {
StringBuffer sb=new StringBuffer("This is my code");
System.out.println(sb.replace(8, 10, "java"));
}
}
Output
This is java code
Explanation: In above example java string is
replaced with old string (my) 437
which is available between 8 to 10 index value.
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
deleteCharAt()
deleteCharAt(): This method is used to delete a character at given index
value.
Example
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java");
System.out.println(sb.deleteCharAt(3));
}
}
Output
438
jav
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
delete()
delete(): This method is used to delete string form given string based on index
value.
Example
class StringHandling {
public static void main(String arg[]) {
StringBuffer sb=new StringBuffer("java is easy to learn");
StringBuffer s;
s=sb.delete(8, 13);
System.out.println(sb); } }
Output
java is to learn
Explanation: In above
example string will be
deleted which is existing
439
between 8 and 13 index value.
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
toString()
toString(): This method is used to convert mutable string value into
immutable string.
Example
class StringHandling {
public static void main(String arg[])
{ StringBuffer sb=new StringBuffer("java");
String s=sb.toString();
System.out.println(s);
s.concat("code");
}
}
Output
440
java
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
• By equals() method
• By == operator
• By compreTo() method
441
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
String Compare in Java
There are three way to compare string object in java:
STRING HANDLING IN JAVA
equals() Method in Java
equals() method always used to comparing contents of both source and
destination String. It return true if both string are same in meaning and case
otherwise it returns false. It is case sensitive method.
442
SCION RESEARCH AND DEVELOPMENT
Example
class StringHandling {
public static void main(String arg[])
{ String s1="Hitesh";
String s2="Raddy";
String s3="Hitesh";
System.out.println("Compare String: "+s1.equals(s2));
System.out.println("Compare String: "+s1.equals(s3));
}
}
Output
Compare String: false
Compare String: true
443
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
STRING HANDLING IN JAVA
== or Double Equals to Operator in Java
== Operator is always used for comparing references of both source and
destination objects but not their contents.
444
SCION RESEARCH AND DEVELOPMENT
Example
class StringHandling {
public static void main(String arg[]) {
String s1=new String("java");
String s2=new String("java");
if(s1==s2) {
System.out.println("Strings are
same");
}
else {
System.out.println("Strings are
not same");
} } }
Output
445
Strings are not same
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
STRING HANDLING IN JAVA
compareTo() Method in Java
comapreTo() method can be used to compare two string by taking Unicode
values. It returns 0 if the string are same otherwise returns either +ve or - ve
integer.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
int i;
i=s1.compareTo(s2);
446
if(i==0)
SCION RESEARCH AND DEVELOPMENT
{
System.out.println("Strings are same");
}
else {
System.out.println("Strings are not same");
}
}
}
Output
Strings are not same
447
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
STRING HANDLING IN JAVA
Difference between equals() method and == operator
• equals() method always used to comparing contents of both source and
destination String.
• == Operator is always used for comparing references of both source and
destination objects but not their contents.
String Concatenation
There are two way to concat string object in java:
• By + (string concatenation) operator
• By concat() method
448
SCION RESEARCH AND DEVELOPMENT
By + operator
Using Java string concatenation operator (+) you can combined two or
more strings.
Example
class StringHandling
{
public static void main(String arg[])
{
String s= "Java" + "Code";
System.out.println(s);
}
}
Output
JavaCode
SCION RESEARCH AND DEVELOPMENT
449
STRING HANDLING IN JAVA
By concat() method
concat() method is used to combined two strings.
Example
class StringHandling {
public static void main(String arg[]) {
String s1="Java";
String s2="Code";
String s3=s1.concat(s2);
System.out.println(s3);
}
}
Output
JavaCode
SCION RESEARCH AND DEVELOPMENT
459
STRING HANDLING IN JAVA
StringBuilder
• It is a predefined class in java.lang package can be used to handle the String.
StringBuilder class is almost similar to to StringBuffer class. It is also a
mutable object.
• The main difference StringBuffer and StringBuilder class is StringBuffer is
thread safe that means only one threads allowed at a time to work on the
String where as StringBuilder is not thread safe that means multiple threads
can work on same String value.
Difference between StringBuffer and StringBuilder
All the things between StringBuffer and StringBuilder are same only
difference is StringBuffer is synchronized and StringBuilder is not
synchronized. synchronized means one thread is allow at a time so it thread
safe. Not synchronized means multiple threads are allow at a time so it not
451
thread safe.
SCION RESEARCH AND DEVELOPMENT
STRING HANDLING IN JAVA
StringBuffer StringBuilder
1 It is thread safe. It is not thread safe.
2
Its methods are synchronized and
provide thread safety.
Its methods are not synchronized and
unable to provide thread safety.
3
Relatively performance is low because
thread need to wait until previous
process is complete.
Relatively performance is high because
no need to wait any thread it allows
multiple thread at a time.
4 Introduced in 1.0 version. Introduced in 1.5 version.
452
required then we use StringBuilder
SCION RESEARCH AND DEVELOPMENT
When we use String, StringBuffer and StringBuilder
• If the content is fixed and would not change frequently then we use String.
• If content is not fixed and keep on changing but thread safety is required then
we use StringBuffer
• If content is not fixed and keep on changing and thread safety is not
STRING HANDLING IN JAVA
Suppose that we have any string like "Features of Java_Language" when we
use stringTokenizer this string is split into tokens whenever spaces and
STRINGTOKENIZER IN JAVA
StringTokenizer in Java
It is a pre defined class in java.util package can be used to split the given string
into tokens (parts) based on delimiters (any special symbols or spaces).
special symbols present. After split string are :
453
SCION RESEARCH AND DEVELOPMENT
Example
• Features
• of
• Java
• Language
Methods of StringTokenizer
• hasMoreTokens()
• nextToken()
hasMoreTokens()
It is predefined method of StringTokenizer class used to check whether given
StringTokenizer having any elements or not.
nextToken()
Which can be used to get the element from the StringTokenizer.
454
SCION RESEARCH AND DEVELOPMENT
STRINGTOKENIZER IN JAVA
System.out.println("The tokens are: ");
while(st.hasMoreTokens()) {
String one=st.nextToken();
System.out.println(one);
}
}
}
man
455
SCION RESEARCH AND DEVELOPMENT
Output
The tokens are:
He
is
a
ge
ntl
e
STRINGTOKENIZER IN JAVA
Example of StringTokenizer:
import java.util.*;
class Stringtokenizerdemo {
public static void main(String args[]) {
String str="He is a gentle man";
StringTokenizer st=new StringTokenizer(str," ");
Data Conversion
In java programming we have six data conversion technique they are:.
1 Converting numeric string type data into numerical / fundamental
type values
In order to convert numerical string into numerical or fundamental values we
use the following generalized predefined method which is present in wrapper
classes.
Example
String s1="100";
int x=Integer.parseInt(s1);
Example
String s2="100.75f";
Float y=Float.parseFloat(s2);
DATA CONVERSION IN JAVA
456
Here xxx represent any fundamental data type.
SCION RESEARCH AND DEVELOPMENT
Here XXX represent any fundamental data type values
Example
int a=10;
DATA CONVERSION IN JAVA
2 Converting numeric / fundamental type values into string type values
In order to convert numeric / fundamental type values into string values, we
use the following predefined static overloaded method.
457
SCION RESEARCH AND DEVELOPMENT
DATA CONVERSION IN JAVA
3 Converting fundamental type values into object type values:
In order to convert the fundamental data into equivalent wrapper class object
type data we use the following generalized predefined parameterized
constructor by taking fundamental data type as a parameter.
458
SCION RESEARCH AND DEVELOPMENT
DATA CONVERSION IN JAVA
in JDK 1.4 converting fundamental data type values into wrapper class object is
known as boxing. In the case of JDK 1.5 and in higher version it is optional to
the java programmer to convert fundamental data type value into equivalent
wrapper class object. That is implicitly taken care by JVM and it is known as
auto boxing.
Definition of auto boxing
The process of implicitly converting fundamental type value into equivalent
wrapper class object is known as auto boxing.
459
SCION RESEARCH AND DEVELOPMENT
DATA CONVERSION IN JAVA
4 Converting object type value into fundamental type value:
In order to convert wrapper class object data into fundamental type data, we
use the following predefined instance method present in each and every
wrapper class.
460
SCION RESEARCH AND DEVELOPMENT
DATA CONVERSION IN JAVA
In case of JDK 1.5 and in higher version it is optional to the java
programmer to convert object data into fundamental type data and this
process is known as auto un-boxing and its takes care by JVM. Definition
of auto un-boxing
In process of implicitly conversion objects type data into fundamental type
data is known as auto un-boxing.
461
SCION RESEARCH AND DEVELOPMENT
5 Converting String type data into object type data
In order to convert String type numeric data into equivalent wrapper class
object, we use the following predefined parameterized constructor by each and
every wrapper class except character class.
DATA CONVERSION IN JAVA
462
SCION RESEARCH AND DEVELOPMENT
To convert wrapper class object type data into string type data we use the
following generalized predefined instant method which is present each and
every wrapper class.
463
SCION RESEARCH AND DEVELOPMENT
DATA CONVERSION IN JAVA
6 Converting wrapper class object type data into String type data
DATA CONVERSION IN JAVA
464
SCION RESEARCH AND DEVELOPMENT
Example
int a=10;
• String is=String.valueOf(a);
• Integer io=new Integer(is);
• int x=io.intValue();
• Integer io=new Integer(n);
• String so=io.toString();
• int x=Integer.parseInt(so);
465
SCION RESEARCH AND DEVELOPMENT
DATA CONVERSION IN JAVA
BOXING AND UNBOXING IN JAVA
Boxing and Unboxing in Java
Definition of Auto Boxing
The process of implicitly converting fundamental type values into the
equivalent wrapper class object is known as auto boxing.
Converting fundamental type values into object type values:
In order to convert the fundamental data into equivalent wrapper class object
type data we use the following generalized predefined parameterized
constructor by taking fundamental data type as a parameter.
ND DEVELOPMENT
466
SCION RESEARCH A
BOXING AND UNBOXING IN JAVA
In JDK 1.4 converting fundamental data type values into wrapper class object is
known as boxing. In the case of JDK 1.5 and in higher version it is optional to
the Java programmer to convert the fundamental data type value into the
equivalent wrapper class object. That is implicitly taken care by JVM and it is
known as auto boxing.
Definition of auto Unboxing.
In process of implicitly conversion objects type data into fundamental type
data is known as auto un-boxing.
Converting object type value into fundamental type value:
In order to convert wrapper class object data into fundamental type data, we
use the following predefined instance method present in each and every
wrapper class.
467
SCION RESEARCH AND DEVELOPMENT
In case of JDK 1.5 and in higher version it is optional to the Java programmer
to convert object data into fundamental type data and this process is known
as auto un-boxing and it takes care by the JVM.
468
SCION RESEARCH AND DEVELOPMENT
BOXING AND UNBOXING IN JAVA
JAVA SCANNER CLASS IN JAVA
Java Scanner Class in Java
Scanner is one of the predefined class which is used for reading the data
dynamically from the keyboard.
Import Scanner class
Import Scanner Class in Java
java.util.Scanner
Constructor of Scanner Class
Scanner(InputStream)
This constructor create an object of Scanner class by talking an object of
InputStream class. An object of InputStream class is called in which is created
as a static data member in the System class.
Syntax of Scanner Class in Java
Scanner sc=new Scanner(System.in);
469
Here the object 'in' is use the control of keyboard
SCION RESEARCH AND DEVELOPMENT
JAVA SCANNER CLASS IN JAVA
470
SCION RESEARCH AND DEVELOPMENT
JAVA SCANNER CLASS IN JAVA
471
SCION RESEARCH AND DEVELOPMENT
Method Description
1 public byte nextByte() Used for read byte value
2 public short nextShort() Used for read short value
3 public int nextInt() Used for read integer value
4 public long nextLong() Used for read numeric value
5 public float nextLong() Used for read numeric value
6 public double nextDouble() Used for read double value
7 public char nextChar() Used for read character
8 public boolean nextBoolean() Used for read boolean value
9 public String nextLine()
Used for reading any kind of data in the form
of String data.
472
the form of String data.
SCION RESEARCH AND DEVELOPMENT
Method 1 to 8 are used for reading fundamental values from the keyboard.
Method 9 (public String nextLine() ) is used for reading any kind of data in
JAVA SCANNER CLASS IN JAVA
Instance methods of Scanner Class
JAVA SCANNER CLASS IN JAVA
For Remember all above methods
From method 1 to 8 combindly we represent as public xxx nextxxx(). Here xxx
represents any fundamental data type. These methods are used for reading the
fundamental data from keyboard.
Accept two values dynamically from the keyboard and compute sum.
Example of Scanner Class in Java
import java.util.Scanner
public class ScannerDemo
{
public static void
main(String args[])
{
Scanner s=new
Scanner(System.in);
System.out.println("Enter
first no= ");
473
int num1=s.nextInt();
SCION RESEARCH AND DEVELOPMENT
JAVA SCANNER CLASS IN JAVA
System.out.println("Enter second no= ");
int num2=s.nextInt();
System.out.println("Sum of no is= "+
(num1+num2));
}
}
474
SCION RESEARCH AND DEVELOPMENT
Output
Enter first no=4
Enter second no=5
Sum of no is=9
SCION RESEARCH AND DEVELOPMENT
475
System.out.println("Sum= "+res);
}
}
Output
Enter first number: 5
Enter second number: 6
Sum= 11
JAVA SCANNER CLASS IN JAVA
Program which is accept two number as a string and compute their
sum.
Example
import java.util.Scanner;
class Dataread {
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("Enter first number: ");
String s1=s.nextLine();
System.out.println("Enter second number: ");
String s2=s.nextLine();
int res=Integer.parseInt(s1) +
Integer.parseInt(s2);

More Related Content

Similar to JAVA PROGRAMJAVA PROGRJAVA PROGRJAVA.pptx (20)

PPTX
Introduction to java and it's opportunities
VigneshManikandan11
 
PPTX
The Java Story
David Parsons
 
PPSX
Introduction of java
Madishetty Prathibha
 
PDF
TechSearchWeb.pdf
TechSearchWeb
 
PDF
Technology Tutorial.pdf
TechSearchWeb
 
PPTX
Java (Part 2) unit 1
Dr. SURBHI SAROHA
 
PPTX
Object Oriented Programming Part 1 of Unit 1
VigneshkumarPonnusam1
 
PPT
Chapter 1 introduction to java technology
sshhzap
 
PDF
Java Training in Chandigarh
Excellence Academy
 
PDF
Java Training in Chandigarh.pdf
Excellence Technology
 
PPTX
Java Programming
Elizabeth alexander
 
PPTX
Java
seenak
 
PPTX
Module1_htryjtjhkrhdegtfhsfhrdgfhpart1.pptx
aashrithsai7dkm
 
PPTX
Java Introduction
sunmitraeducation
 
PPT
PPS Java Overview Unit I.ppt
CDSukte
 
PPT
PPS Java Overview Unit I.ppt
RajeshSukte1
 
PPTX
Java (1)
Samraiz Tejani
 
PPTX
Java Lecture 1
Qualys
 
PPT
1.Intro JAVA.ppt ( Basics of Java Programming)
BhawnaSaini45
 
Introduction to java and it's opportunities
VigneshManikandan11
 
The Java Story
David Parsons
 
Introduction of java
Madishetty Prathibha
 
TechSearchWeb.pdf
TechSearchWeb
 
Technology Tutorial.pdf
TechSearchWeb
 
Java (Part 2) unit 1
Dr. SURBHI SAROHA
 
Object Oriented Programming Part 1 of Unit 1
VigneshkumarPonnusam1
 
Chapter 1 introduction to java technology
sshhzap
 
Java Training in Chandigarh
Excellence Academy
 
Java Training in Chandigarh.pdf
Excellence Technology
 
Java Programming
Elizabeth alexander
 
Java
seenak
 
Module1_htryjtjhkrhdegtfhsfhrdgfhpart1.pptx
aashrithsai7dkm
 
Java Introduction
sunmitraeducation
 
PPS Java Overview Unit I.ppt
CDSukte
 
PPS Java Overview Unit I.ppt
RajeshSukte1
 
Java (1)
Samraiz Tejani
 
Java Lecture 1
Qualys
 
1.Intro JAVA.ppt ( Basics of Java Programming)
BhawnaSaini45
 

Recently uploaded (20)

PPT
SQL.pptkarim pfe rabatkarim pfe rabatkarim pfe rabat
Keeyvikyv
 
PPTX
A Guide for a Winning Interview July 2025
Bruce Bennett
 
PPTX
文凭复刻澳洲电子毕业证阳光海岸大学成绩单USC录取通知书
Taqyea
 
PDF
Find the Latest Government Jobs in One Click – Stay Updated with Daily Notifi...
Reeshna Prajeesh
 
PDF
Bilal Ibrar | Digital Marketing Expert | Resume | CV
Bilal Ibrar
 
PPTX
STATE OFFICERS for organization reference
conqueror3rd
 
PDF
reStartEvents July 10th TS:SCI & Above Employer Directory.pdf
Ken Fuller
 
PPTX
The Future of Sustainable Cities.ppppptx
sahatanmay391
 
PDF
Sarkari Job Alerts in Marathi & English – Majhi Naukri
Reeshna Prajeesh
 
PPTX
Plant Growth and Development-Part I, ppt.pptx
7300511143
 
DOCX
PMCF -Performance Monitoring and Coaching Form
ROSALIESOMBILON
 
PPTX
21st-Literature.pptxjsududhshsusushshsusuhsgsysh
JohnVJLBellen
 
PPTX
Web Developer Jobs in Jaipur Your Gateway to a Thriving Tech Career in Rajast...
vinay salarite
 
PDF
corporate training firms in pune.........
a25075044
 
PDF
Crafting Winning CVs Cover Letters and Mastering Job Interviews with Roman Vi...
Excellence Foundation for South Sudan
 
PPTX
The Future of Law.ppptttttttttttttttttttttttttttttttttttttttttttttttttttttttt...
sahatanmay391
 
PPTX
Adaptive Leadership Model 2025 – AI-Generated PowerPoint by Presentify.ai
presentifyai
 
PDF
The Rising Prominence of Podcasts Today
Raj Kumble
 
PDF
Find Your Dream Job with Formwalaa – Fast, Smart & Effortless Job Search
Reeshna Prajeesh
 
PPTX
Future_Proofing_Your_Career_25_Essential_Skills_for_2025.pptx
presentifyai
 
SQL.pptkarim pfe rabatkarim pfe rabatkarim pfe rabat
Keeyvikyv
 
A Guide for a Winning Interview July 2025
Bruce Bennett
 
文凭复刻澳洲电子毕业证阳光海岸大学成绩单USC录取通知书
Taqyea
 
Find the Latest Government Jobs in One Click – Stay Updated with Daily Notifi...
Reeshna Prajeesh
 
Bilal Ibrar | Digital Marketing Expert | Resume | CV
Bilal Ibrar
 
STATE OFFICERS for organization reference
conqueror3rd
 
reStartEvents July 10th TS:SCI & Above Employer Directory.pdf
Ken Fuller
 
The Future of Sustainable Cities.ppppptx
sahatanmay391
 
Sarkari Job Alerts in Marathi & English – Majhi Naukri
Reeshna Prajeesh
 
Plant Growth and Development-Part I, ppt.pptx
7300511143
 
PMCF -Performance Monitoring and Coaching Form
ROSALIESOMBILON
 
21st-Literature.pptxjsududhshsusushshsusuhsgsysh
JohnVJLBellen
 
Web Developer Jobs in Jaipur Your Gateway to a Thriving Tech Career in Rajast...
vinay salarite
 
corporate training firms in pune.........
a25075044
 
Crafting Winning CVs Cover Letters and Mastering Job Interviews with Roman Vi...
Excellence Foundation for South Sudan
 
The Future of Law.ppptttttttttttttttttttttttttttttttttttttttttttttttttttttttt...
sahatanmay391
 
Adaptive Leadership Model 2025 – AI-Generated PowerPoint by Presentify.ai
presentifyai
 
The Rising Prominence of Podcasts Today
Raj Kumble
 
Find Your Dream Job with Formwalaa – Fast, Smart & Effortless Job Search
Reeshna Prajeesh
 
Future_Proofing_Your_Career_25_Essential_Skills_for_2025.pptx
presentifyai
 
Ad

JAVA PROGRAMJAVA PROGRJAVA PROGRJAVA.pptx

  • 1. JAVA PROGRAM SCION RESEARCH AND DEVELOPMENT
  • 2. 2 SCION RESEARCH AND DEVELOPMENT language and why we use programming languages. JAVA Java Tutorial It is one of the programming language or technology used for developing web applications. Using this technology you can develop distributed application. A Java language developed at SUN Micro Systems in the year 1995 under the guidance of James Gosling and their team. In other word It is a programming language suitable for the development of web applications. It is also used for developing desktop and mobile application. Born This language was developed at SUN Microsystems in the year 1995 under the guidance of James Gosling and their team. Prerequisites Before learning of This tutorial no need to learn any programming language like C and C++. But you have knowledge of programming
  • 3. 3 Java is one of the programming language or technology used for developing web applications. Java language developed at SUN Micro Systems in the year 1995 under the guidance of James Gosling and there team. Originally SUN Micro Systems is one of the Academic university (Stanford University SCION RESEARCH AND DEVELOPMENT Network) JAV A
  • 4. JAVA Whatever the software developed in the year 1990, SUN Micro Systems has released on the name of oak, which is original name of java (scientifically oak is one of the tree name). The OAK has taken 18 months to develop. The oak is unable to fulfill all requirements of the industry. So James Gosling again reviews this oak and released with the name of java in the year 1995. Scientifically java is one of the coffee seed name. Java divided into three categories, they are J2SE (Java 2 Standard Edition) J2EE (Java 2 Enterprise Edition) J2ME (Java 2 Micro or Mobile Edition) J2SE - J2SE is used for developing client side applications. J2EE - J2EE is used for developing server side applications. J2ME - J2ME is used for developing mobile or wireless application. 4 SCION RESEARCH AND DEVELOPMENT
  • 5. All versions of java Java Version SE 7 J2SE 1.2 is called as Dolphin and it is released on 28 July, 2011. Features • Strings in switch Statement • Type Inference for Generic Instance Creation, Multiple Exception Handling • Support for Dynamic Languages • Try with Resources • Java nio Package • Binary Literals, underscore in literals • Diamond Syntax • Automatic null Handling 5 SCION RESEARCH AND DEVELOPMENT JAVA VERSIONS
  • 6. Java Version SE 6 J2SE 1.2 is called as Mustang and it is released on 11 December, 2006. Features • Scripting Language Support • JDBC 4.0 API • Java Compiler API • Pluggable Annotations • Native PKI, Java GSS, Kerberos and LDAP support. • Integrated Web Services. • Lot more enhancements. 6 SCION RESEARCH AND DEVELOPMENT JAVA VERSIONS
  • 7. J2SE Version 5.0 J2SE 1.2 is called as Tiger and it is released on 30 September, 2004. Features • Generics • Enhanced for Loop • Auto boxing/Unboxing • Type safe Enums • Varargs • Static Import • Metadata (Annotations) • Instrumentation JAVA VERSIONS 7 SCION RESEARCH AND DEVELOPMENT
  • 8. J2SE Version 1.4 J2SE 1.2 is called as Merlin and it is released on 6 February, 2002. Features • XML Processing • Java Print Service • Logging API • Java Web Start • JDBC 3.0 API, Assertions • Preferences API • Chained Exception • IPv6 Support • Regular Expressions JAVA VERSIONS • Image I/O API 8 SCION RESEARCH AND DEVELOPMENT
  • 9. J2SE Version 1.3 J2SE 1.2 is called as Kestrel and it is released on 8 May, 2000. Features • Java Sound • Jar Indexing • A huge list of enhancements in almost all the java area. JAVA VERSIONS 9 SCION RESEARCH AND DEVELOPMENT
  • 10. J2SE Version 1.2 J2SE 1.2 is called as playground and it is released on 8 December, 1998. Features • Collections framework. • Java String memory map for constants. • Just In Time (JIT) compiler. • Jar Signer for signing Java Archive (JAR) files. • Policy Tool for granting access to system resources. • Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class libraries. • Java Plug-in • Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC. 10 • Audio support in Applets. SCION RESEARCH AND DEVELOPMENT JAVA VERSIONS
  • 11. JDK Version 1.1 JDK 1.1 is released on 19 January, 1997 Features • JDBC (Java Database connectivity) • Inner Classes • Java Beans • RMI (Remote Method Invocation) • Reflection(introspection only) JDK Version 1.0 JDK 1.0 is called as OAK, and it is released on 23 January, 1996. 11 SCION RESEARCH AND DEVELOPMENT JAVA VERSIONS
  • 12. Basic Points of Java Java is a platform independent, more powerful, secure, high performance, multithreaded programming language. Here we discuss some points related to Java. Define byte Byte code is the set of optimized instructions generated during compilation phase and it is more powerful than ordinary pointer code. Define JRE The Java Runtime Environment (JRE) is part of the Java Development Kit(JDK). It contains a set of libraries and tools for developing Java application. The Java Runtime Environment provides the minimum requirements for executing a Java application 12 JAVA BASIC
  • 13. Define JVM JVM is set of programs developed by sun Micro System and supplied as a part of the JDK for reading line by line of byte code and it converts into a native understanding form of operating system. The Java language is one of the compiled and interpreted programming language. Garbage Collector The Garbage Collector is the system Java program which runs in the background along with a regular Java program to collect un-Referenced (unused) memory space for improving the performance of our applications. Note: Java programming does not support destructor concept in place of destructor, we have garbage collector program. 13 SCION RESEARCH AND DEVELOPMENT JAVA BASIC
  • 14. Define an API An API (Application Programming Interface) is a collection of packages, a package is the collection of classes, interfaces and sub-packages. A sub- package is a collection of classes, Interfaces and sub packages etc. Java programming contains user friendly syntax so that we can develop effective applications. in other words if any language is providing user friendly syntax, we can develop error free applications. Definition of JIT JIT is the set of programs developed by SUN Micro System and added as a part of JVM, to speed up the interpretation phase. 14 SCION RESEARCH AND DEVELOPMENT JAVA BASIC
  • 15. Network based application Network based application are mainly classified into two types. 1. Centralized Applications 2. Distributed Applications Centralized applications • In this scenario multiple client system depends on single server system. • The major drawback in this architecture is if any problem occurred on server system that will be reflected on every client system. 15 SCION RESEARCH AND DEVELOPMENT JAVA BASIC
  • 16. Distributed applications In this scenario multiple client system are depends on multiple server system so that even problem occurred in one server will never be reflected on any client system. Note: In this architecture same application is distributed in multiple server system. Java is a very powerful language can be used to developed both client server architecture and distributed architecture based application. 16 SCION RESEARCH AND DEVELOPMENT JAVA BASIC
  • 17. 17 • Simple • Platform Independent • Architectural Neutral • Portable • Multi Threading • Distributed • Networked • Robust • Dynamic • Secured • High Performance • Interpreted JAVA FEATURES Features of Java Features of a language are nothing but the set of services or facilities provided by the language vendors to the industry programmers. Some important features of java are; Important Features of Java • Object Oriented SCION RESEARCH AND DEVELOPMENT
  • 18. Simple It is simple because of the following factors: • It is free from pointer due to this execution time of application is improved. [Whenever we write a Java program without pointers then internally it is converted into the equivalent pointer program]. • It has Rich set of API (application protocol interface). • It has Garbage Collector which is always used to collect un-Referenced (unused) Memory location for improving performance of a Java program. It contains user friendly syntax for developing any applications. JAVA FEATURES 18 SCION RESEARCH AND DEVELOPMENT
  • 19. Platform Independent A program or technology is said to be platform independent if and only if which can run on all available operating systems with respect to its development and compilation. (Platform represents O.S). JAVA FEATURES 19 SCION RESEARCH AND DEVELOPMENT
  • 20. Architectural Neutral Architecture represents processor. A Language or Technology is said to be Architectural neutral which can run on any available processors in the real world without considering their development and compilation. JAVA FEATURES The languages like C, CPP are treated as architectural dependent. 20 SCION RESEARCH AND DEVELOPMENT
  • 21. Portable If any language supports platform independent and architectural neutral feature known as portable. The languages like C, CPP, Pascal are treated as non- portable language. It is a portable language. According to SUN microsystem. Multithreaded A flow of control is known as a thread. When any Language executes multiple thread at a time that language is known as multithreaded e. It is multithreaded. 21 SCION RESEARCH AND DEVELOPMENT JAVA FEATURES
  • 22. Distributed Using this language we can create distributed applications. RMI and EJB are used for creating distributed applications. In distributed application multiple client system depends on multiple server systems so that even problem occurred in one server will never be reflected on any client system. Note: In this architecture same 22 SCION RESEARCH AND DEVELOPMENT application is distributed in multiple server system. JAVA FEATURES
  • 23. Networked It is mainly designed for web based applications, J2EE is used for developing network based applications. Robust Simply means of Robust are strong. It is robust or strong Programming Language because of its capability to handle Run-time Error, automatic garbage collection, the lack of pointer concept, Exception Handling. All these points make It robust Language. Secure It is a more secure language compared to other language; In this language, all code is covered in byte code after compilation which is not readable by 23 human. SCION RESEARCH AND DEVELOPMENT JAVA FEATURES
  • 24. Dynamic It supports Dynamic memory allocation due to this memory wastage is reduce and improve performance of the application. The process of allocating the memory space to the input of the program at a run-time is known as dynamic memory allocation, To programming to allocate memory space by dynamically we use an operator called 'new' 'new' operator is known as dynamic memory allocation operator. Interpreted It is one of the highly interpreted programming languages. Object Oriented It supports OOP's concepts because of this it is most secure language, for 24 this topic you can read our oop's concepts in detail. SCION RESEARCH AND DEVELOPMENT JAVA FEATURES
  • 25. High performance • It have high performance because of following reasons; • This language uses Byte code which is faster than ordinary pointer code so Performance of this language is high. • Garbage collector, collect the unused memory space and improve the performance of the application. • It has no pointers so that using this language we can develop an application very easily. • It support multithreading, because of this time consuming process can be reduced to executing the program. 25 SCION RESEARCH AND DEVELOPMENT JAVA FEATURES
  • 26. SET PATH How to Set Path and Classpath in Java Setting path and classpath in Java is very simple but before do this process you need to know about path variable and classpath variable. Here I will show you how to set path and classpath in Java in very simple and easy way. Path Variable Path variable is set for providing path for all Java tools like java, javac, javap, javah, jar, applet viewer which are used in java programming. All these tools are available in bin folders so we set path up to bin folders. Classpath Variable Classpath variable is set for providing a path for predefined Java classes which is used in our application. All classes are available in lib/rt.jar so we set classpath upto lib/rt.jar. 26 SCION RESEARCH AND DEVELOPMENT
  • 27. SET PATH JDK Folder Hierarchy 27 SCION RESEARCH AND DEVELOPMENT
  • 28. Why set path ? The following programming error is generally for all Java programmers when they compile any Java program. 'javac' is not recognized as an internal or external command, operable program or batch file. When you get this type of error, then your operating system cannot find the Java compiler (javac). To solve this error you need to set the PATH variable. Javac is a tool which is available in bin folder so you must set the PATH upto bin folder. In a bin folder all tools are available like javap, javah, jar, javac, java, appletviewer etc. All these tools are used for different- different purpose. 28 SCION RESEARCH AND DEVELOPMENT SET PATH
  • 29. SET PATH 29 SCION RESEARCH AND DEVELOPMENT
  • 30. set the path and classpath Go on my computer icon and right click, after that click on properties option. SET PATH 30 SCION RESEARCH AND DEVELOPMENT
  • 31. SET PATH Now click on advance setting 31 SCION RESEARCH AND DEVELOPMENT
  • 32. Click on advance Click on Environment variables SET PATH 32 SCION RESEARCH AND DEVELOPMENT
  • 33. Now one dialog box is appear, now ignore this but do not close. SET PATH Click on new button which is below the first box. 33 SCION RESEARCH AND DEVELOPMENT
  • 34. SET PATH Now open my computer open c:/ > Programs Files > java > java1.6.0 > bin copy this path 34 SCION RESEARCH AND DEVELOPMENT
  • 35. SET PATH Now come back on previous open dilogbox and write variable name 'path' and for variable value paste all copied path up to the bin folder. Put .; at the end. It (.) selects all the tools from the bin folder. 35 SCION RESEARCH AND DEVELOPMENT
  • 36. Now open my computer open c:/ > Programs Files > java > java1.6.0 > jre > lib > rt.jar copy this path Note: rt.jar is available in lib folder this jar files contains all classes of jdk. SET PATH 36 SCION RESEARCH AND DEVELOPMENT
  • 37. Note: Finally after set classpath Restart your system, or you can re- open command prompt. 37 SCION RESEARCH AND DEVELOPMENT SET PATH Now again come back on Environment variable dilogbox and click on new. Now one box is open and write path variable as 'classpath' and for variable value paste all copied paths upto rt.jar. Put .; at the end. It (.) selects all the classes from lib folder.
  • 38. Path classpath path variable is set for providing path for all java tools like java, javac, javap, javah, jar, appletviewer classpath variable is set for provide path of all java classes which is used in our application. 38 SCION RESEARCH AND DEVELOPMENT SET PATH Difference between path and classpath in Java • Path - Path variable is set for providing path for all Java tools like java, javac, javap, javah, jar, appletviewer. In Java to run any program we use java tool and for compile Java code use javac tool. All these tools are available in bin folder so we set path upto bin folder. • Classpath - classpath variable is set for providing path of all Java classes which is used in our application. All classes are available in lib/rt.jar so we set classpath upto lib/rt.jar.
  • 39. SET PATH JDK Folder Hierarchy 39 SCION RESEARCH AND DEVELOPMENT
  • 40. All the tools are present in bin folder so we set path upto bin folder. 40 SCION RESEARCH AND DEVELOPMENT SET PATH Path variable is set for use all the tools like java, javac, javap, javah, jar, appletviewer etc. Example "C:Program FilesJavajdk1.6.0bin"
  • 41. SET PATH Classpath variable is used to set the path for all classes which is used in our program so we set classpath upto rj.jar. in rt.jar file all the .class files are present. When we decompressed rt.jar file we get all .class files. Example "C:Program FilesJavajre1.6.0jrelibrt.jar" In above rt.jar is a jar file where all the .class files are present so we set the classpath upto rt.jar. 41 SCION RESEARCH AND DEVELOPMENT
  • 42. FIRST JAVA PROGRAM First Java Program Requirements for java Program For executing any java program we need given things. • Install the JDK any version if you don't have installed it. • Set path of the jdk/bin directory. • Create the java program • Compile and run the java program Steps For compiling and executing the java program • Java is very simple programming language first we write a java program and save it with program class name. • In below program we create a java program with "First" name so we save this program with "First.java" file name. We can save our java program anywhere in our system or computer. 42 SCION RESEARCH AND DEVELOPMENT
  • 43. Create First program Example class First{ public static void main(String[] args) { System.out.println("Hello Java"); System.out.println("My First Java Program"); } } Compile and Execute Java Code To compile: javac First.java To execute: java First Output Hello Java FIRST JAVA PROGRAM 43 My First Java Program SCION RESEARCH AND DEVELOPMENT
  • 44. Save Java Program Syntax: Filename.java Example: First.java Compile Java Program Syntax: Javac Filename.java Example: Javac First.java 44 SCION RESEARCH AND DEVELOPMENT Note: Here Javac and Java are called tools or application programs or exe files developed by sun micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder. Javac is used for compile the java program and java is used for run the java program. FIRST JAVA PROGRAM
  • 45. FIRST JAVA PROGRAM During the program execution internally following steps will be occurs. • Class loader subsystem loads or transfer the specified class into main memory(RAM) from secondary memory(hard disk) • JVM takes the loaded class • JVM looks for main method because each and every java program start executing from main() method. • Since main() method of java is static in nature, JVM call the main() method with respect to loaded class (Example: First as First.main(--)) • Note: A java program can contain any number of main method but JVM start execution from that main() method which is taking array of object of String class. 45 SCION RESEARCH AND DEVELOPMENT
  • 46. The java launcher tool then runs your application with an instance of the 46 Java Virtual Machine (JVM). SCION RESEARCH AND DEVELOPMENT FIRST JAVA PROGRAM Compile and Run Java Program In the Java programming language, all source code is first written in plain text files and save with the .java extension. After compilation, .class files are generated by javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes (it is machine language of the Java Virtual Machine1 (JVM)).
  • 47. FIRST JAVA PROGRAM Steps For compile Java Program First Save Java program with same as class name with .java extension. Example: Sum.java Compile: javac Filename.java Example: javac Sum.java Note: Here javac is tools or application programs or exe files which is used for Compile the Java program. Steps For Run Java Program - For run java program use java tool. Run by: java Filename , Example: java sum Note: Here java is tools or application programs or exe files which is used 47 for run the Java program. SCION RESEARCH AND DEVELOPMENT
  • 48. FIRST JAVA PROGRAM Steps For compiling and executing the java program The following sequence of steps represented in the diagram use compiling the java program and executing the java programs. In the above diagram javac and java are called tools or application programs or exe files developed by sun micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder (starting directory of java is called java home directory). 48 SCION RESEARCH AND DEVELOPMENT
  • 49. DIFFERENCE B/W JDK,JVM, & JRE Difference between JDK, JVM and JRE JVM, JRE, JDK these all the backbone of java language. Each components have separate works. JDK and JRE physically exists but JVM are abstract machine it means it not physically exists. 49 SCION RESEARCH AND DEVELOPMENT
  • 50. JVM JVM (Java Virtual Machine) is a software. It is a specification that provides runtime environment in which java bytecode can be executed. It not physically exists. JVMs are not same for all hardware and software, for example for window os JVM is different and for Linux VJM is different. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent. JRE The Java Runtime Environment (JRE) is part of the Java Development Kit (JDK). It contains set of libraries and tools for developing java application. The Java Runtime Environment provides the minimum requirements for executing a Java application. It physically exists. It contains set of libraries + 50 other files that JVM uses at runtime. SCION RESEARCH AND DEVELOPMENT DIFFERENCE B/W JDK,JVM, & JRE
  • 51. JDK The Java Development Kit (JDK) is primary components. It physically exists. It is collection of programming tools and JRE, JVM. DIFFERENCE B/W JDK,JVM, & JRE 51 SCION RESEARCH AND DEVELOPMENT
  • 52. JVM ARCHITECTURE JVM Architecture in Java JVM (Java Virtual Machine) is a software. It is a specification that provides Runtime environment in which java bytecode can be executed. 52 SCION RESEARCH AND DEVELOPMENT
  • 53. Operation of JVM JVM mainly performs following operations. • Allocating sufficient memory space for the class properties. • Provides runtime environment in which java byte code can be executed • Converting byte code instruction into machine level instruction. • JVM is separately available for every Operating System while installing java software so that JVM is platform dependent. Note: Java is platform Independent but JVM is platform dependent because every Operating system have different-different JVM which is install along with JDK Software. Class loader subsystem: Class loader subsystem will load the .class file into java stack and later sufficient memory will be allocated for all the properties of the java 53 program into following five memory locations. SCION RESEARCH AND DEVELOPMENT JVM ARCHITECTURE
  • 54. • Heap area • Method area • Java stack • PC register • Native stack Heap area: - In which object references will be stored. Method area - In which static variables non-static and static method will be stored. Java Stack - In which all the non-static variable of class will be stored and whose address referred by object reference. Pc Register Which holds the address of next executable instruction that means that use the priority for the method in the execution process? 54 SCION RESEARCH AND DEVELOPMENT JVM ARCHITECTURE
  • 55. Native Stack Native stack holds the instruction of native code (other than java code) native stack depends on native library. Native interface will access interface between native stack and native library. Execution Engine Which contains Interpreter and JIT compiler whenever any java program is executing at the first time interpreter will comes into picture and it converts one by one byte code instruction into machine level instruction JIT compiler (just in time compiler) will comes into picture from the second time onward if the same java program is executing and it gives the machine level instruction to the process which are available in the buffer memory. Note: The main aim of JIT compiler is to speed up the execution of java program. 55 SCION RESEARCH AND DEVELOPMENT JVM ARCHITECTURE
  • 56. JVM ARCHITECTURE What is JIT and Why use JIT • JIT is the set of programs developed by SUN Micro System and added as a part of JVM, to speed up the interpretation phase. • In the older version of java compilation phase is so faster than interpretation phase. Industry has complained to the SUN Micro System saying that compilation phase is very faster and interpretation phase is very slow. • So solve this issue, SUN Micro System has developed a program called JIT (just in time compiler) and added as a part of JVM to speed up the interpretation phase. In the current version of java interpretation phase is so faster than compilation phase. Hence java is one of the highly interpreted programming languages. 56 SCION RESEARCH AND DEVELOPMENT
  • 57. Object and class in Java Object is the physical as well as logical entity where as class is the only logical entity. Class: Class is a blue print which is containing only list of variables and method and no memory is allocated for them. A class is a group of objects that has common properties. A class in java contains: • Data Member • Method • Constructor • Block • Class and Interface 57 SCION RESEARCH AND DEVELOPMENT OOPS CONCEPT
  • 58. OOPS CONCEPT Object: Object is a instance of class, object has state and behaviors. An Object in java has three characteristics: • State • Behavior • Identity State: Represents data (value) of an object. Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc. Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely. Class is also can be used to achieve user defined data types. 58 SCION RESEARCH AND DEVELOPMENT
  • 59. OOPS CONCEPT Real life example of object and class In real world many examples of object and class like dog, cat, and cow are belong to animal's class. Each object has state and behaviors. For example a dog has state:- color, name, height, age as well as behaviors:- barking, eating, and sleeping. 59 SCION RESEARCH AND DEVELOPMENT
  • 60. Vehicle class Car, bike, truck these all are belongs to vehicle class. These Objects have also different states and behaviors. For Example car has state - color, name, model, speed, Mileage. as we;; as behaviors - distance travel OOPS CONCEPT 60 SCION RESEARCH AND DEVELOPMENT
  • 61. Class Object 1 Class is a container which collection of variables and methods. object is a instance of class 2 No memory is allocated at the time of declaration Sufficient memory space will be allocated for all the variables of class at the time of declaration. 3 One class definition should exist only once in the program. For one class multiple objects can be created. 61 method; } SCION RESEARCH AND DEVELOPMENT Syntax to declare a Class class Class_Name { data member; OOPS CONCEPT Difference between Class and Object in Java
  • 62. OOPS CONCEPT Simple Example of Object and Class In this example, we have created a Employee class that have two data members eid and ename. We are creating the object of the Employee class by new keyword and printing the objects value. package sample; public class Program1 { int eid; // data member (or instance variable) String ename; // data member (or instance variable) { eid=101; ename="Hitesh"; } public static void main(String args[]){ 62 Program1 e=new Program1(); SCION RESEARCH AND DEVELOPMENT
  • 63. OOPS CONCEPT // Creating an object of class Employee System.out.println("Employee ID: "+e.eid); System.out.println("Name: "+e.ename); } } OUTPUT: Employee ID: 101 Name: Hitesh Note: A new keyword is used to allocate memory at runtime, new keyword is used for create an object of class, later we discuss all the way for create an object of class. 63 SCION RESEARCH AND DEVELOPMENT
  • 64. Data Type in Java Data type is a special keyword used to allocate sufficient memory space for the data, in other words Data type is used for representing the data in main memory (RAM) of the computer. In general every programming language is containing three categories of data types. They are • Fundamental or primitive data types • Derived data types • User defined data types. DATA TYPE IN JAVA 64 SCION RESEARCH AND DEVELOPMENT
  • 65. Primitive data types • Primitive data types are those whose variables allows us to store only one value but they never allows us to store multiple values of same type. • This is a data type whose variable can hold maximum one value at a time. Example int a; // valid a=10; // valid a=10, 20, 30; // invalid Here "a" store only one value at a time because it is primitive type variable. 65 SCION RESEARCH AND DEVELOPMENT DATA TYPE IN JAVA
  • 66. Derived data types • Derived data types are those whose variables allow us to store multiple values of same type. But they never allows to store multiple values of different types. • These are the data type whose variable can hold more than one value of similar type. In general derived data type can be achieve using array. Example int a[] = {10,20,30}; // valid int b[] = {100, 'A', "ABC"}; // invalid Here derived data type store only same type of data at a time not store integer, character and string at same time. 66 SCION RESEARCH AND DEVELOPMENT DATA TYPE IN JAVA
  • 67. User defined data types • User defined data types are those which are developed by programmers by making use of appropriate features of the language. • User defined data types related variables allows us to store multiple values either of same type or different type or both. This is a data type whose variable can hold more than one value of dissimilar type, in java it is achieved using class concept. Note: In java both derived and user defined data type combined name as reference data type. In C language, user defined data types can be developed by using struct, union, enum etc. In java programming user defined datatype can be developed by using the features of classes and interfaces. 67 SCION RESEARCH AND DEVELOPMENT DATA TYPE IN JAVA
  • 68. Example Student s = new Student(); In java we have eight data type which are organized in four groups. They are Integer category data types Character category data types Float category data types Boolean category data types 68 SCION RESEARCH AND DEVELOPMENT DATA TYPE IN JAVA
  • 69. Integer category data types SCION RESEARCH AND DEVELOPMENT These category data types are used for storing integer data in the main memory of computer by allocating sufficient amount of memory space. Integer category data types are divided into four types which are given in following table Data Type Size Range 1 Byte 1 + 127 to -128 2 Short 2 + 32767 to -32768 3 Int 4 + x to - (x+1) 4 Long 8 + y to - (y+1) Character category data types A character is an identifier which is enclosed within single quotes. In java to represent character data, we use a data type called char. This data type takes two byte since it follows Unicode character set. 69 Data Type Size(Byte) Range Char 2 232767 to -32768 DATA TYPE IN JAVA
  • 70. Data Type Size Range Number of decimal places 70 Float 4 +2147483647 to -2147483648 8 Double 8 + 9.223*1018 16 SCION RESEARCH AND DEVELOPMENT DATA TYPE IN JAVA Why Java take 2 byte of memory for store character ? Java support more than 18 international languages so java take 2 byte for characters, because for 18 international language 1 byte of memory is not sufficient for storing all characters and symbols present in 18 languages. Java supports Unicode but c support ascii code. In ascii code only English language are present, so for storing all English latter and symbols 1 byte is sufficient. Unicode character set is one which contains all the characters which are available in 18 international languages and it contains 65536 characters Float category data types Float category data type are used for representing float values. This category contains two data types, they are in the given table
  • 71. Boolean category data types Boolean category data type is used for representing or storing logical values is true or false. In java programming to represent Boolean values or logical values, we use a data type called Boolean. Why Boolean data types take zero byte of memory ? Boolean data type takes zero bytes of main memory space because Boolean data type of java implemented by Sun Micro System with a concept of flip - flop. A flip - flop is a general purpose register which stores one bit of information (one true and zero false). Note: In C, C++ (Turbo) Boolean data type is not available for representing true false values but a true value can be treated as non-zero value and false values can be represented by zero 71 SCION RESEARCH AND DEVELOPMENT DATA TYPE IN JAVA
  • 72. Data Type Default Value Default size boolean False 1 bit char 'u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte 72 SCION RESEARCH AND DEVELOPMENT DATA TYPE IN JAVA
  • 73. Syntax Variable_name = value; 73 SCION RESEARCH AND DEVELOPMENT VARIABLE DECLARATION IN JAVA Variable Declaration Rules in Java Variable is an identifier which holds data or another one variable is an identifier whose value can be changed at the execution time of program. Variable is an identifier which can be used to identify input data in a program.
  • 74. VARIABLE DECLARATION IN JAVA Rules to declare a Variable • Every variable name should start with either alphabets or underscore ( _ ) or dollar ( $ ) symbol. • No space are allowed in the variable declarations. • Except underscore ( _ ) no special symbol are allowed in the middle of variable declaration • Variable name always should exist in the left hand side of assignment operators. • Maximum length of variable is 64 characters. • No keywords should access variable name. Note: Actually a variable also can start with ¥,¢, or any other currency sign. 74 SCION RESEARCH AND DEVELOPMENT
  • 75. Example of Variable Declaration class Sum { public static void main(String[] args) { int _a, ¢b, ¥c, $d, result; _a=10; ¢b=20; ¥c=30; $d=40; result=_a+ ¢b+¥c+$d; System.out.println("S um is :" +result); } Output Sum is : 100 VARIABLE DECLARATION IN JAVA 75 } SCION RESEARCH AND DEVELOPMENT
  • 76. Variable initialization It is the process of storing user defined values at the time of allocation of memory space. VARIABLE DECLARATION IN JAVA Variable declarations In which sufficient memory will be allocated and holds default values. Syntax Datatype variable_name; byte b1; 76 SCION RESEARCH AND DEVELOPMENT
  • 77. Syntax int a= 100; int b; b = 25; // ------> direct assigned variable b = a; // ------> VARIABLE DECLARATION IN JAVA Variable assignment Value is assigned to a variable if that is already declared or initialized. Syntax Variable_Name = value int a = 100; 77 SCION RESEARCH AND DEVELOPMENT
  • 78. Operators in Java Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation. Java supports following lists of operators. • Arithmetic Operators • Relational Operators • Logical Operators • Bitwise Operators • Assignment Operators • Ternary or Conditional Operators OPERATORS IN JAVA 78 SCION RESEARCH AND DEVELOPMENT
  • 79. Arithmetic Operators Given table shows all the and B hold 3. 79 SCION RESEARCH AND DEVELOPMENT Arithmetic supported Language. operator by Java Lets suppose Operator Example (int A=8, B=3) Result + A+B 11 - A-B 5 * A*B 24 / A/B 2 % A%4 0 variable A hold 8 and B hold 3. Relational Operators Which can be used to check the Condition, it always return true or false. Lets suppose variable A hold 8 Operators Example (int A=8, B=3) Result < A<B False <= A<=10 True > A>B True >= A<=B False == A== B False != A!=(-4) True OPERATORS IN JAVA
  • 80. Logical Operator Which can be used to combine more than one Condition?. Suppose you want to combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is Logical Operator 80 SCION RESEARCH AND DEVELOPMENT Truth table of Logical Operator Operator Example (int A=8, B=3, C=-10) Result && (A<B) && (B>C) False || (B!=-C) || (A==B) True ! !(B<=-A) True C1 C2 C1 && C2 C1 || C2 !C1 !C2 T T T T F F T F F T F T F T F T T F F F F F T T OPERATORS IN JAVA
  • 81. Assignment operators Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3. 81 SCION RESEARCH AND DEVELOPMENT Operator Example (int A=8, B=3) Result += A+=B or A=A+B 11 -= A-=3 or A=A+3 5 *= A*=7 or A=A*7 56 /= A/=B or A=A/B 2 %= A%=5 or A=A%5 3 =a=b Value of b will be assigned to a Ternary operator If any operator is used on three operands or variable is known as ternary operator. It can be represented with " ?: " OPERATORS IN JAVA
  • 82. STRUCTURE OF JAVA PROGRAM Structure of Java Program • Structure of a java program is the standard format released by Language developer to the Industry programmer. • Sun Micro System has prescribed the following structure for the java programmers for developing java application. 82 SCION RESEARCH AND DEVELOPMENT
  • 83. STRUCTURE OF JAVA PROGRAM • A package is a collection of classes, interfaces and sub-packages. A sub package contains collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this package is known as default package. • Class is keyword used for developing user defined data type and every java program must start with a concept of class. "ClassName" represent a java valid variable name treated as a name of the class each and every class name in java is treated as user-defined data type. • Data member represents either instance or static they will be selected based on the name of the class. • User-defined methods represents either instance or static they are meant for performing the operations either once or each and every time. • Each and every java program starts execution from the main() method. And 83 hence main() method is known as program driver. SCION RESEARCH AND DEVELOPMENT
  • 84. STRUCTURE OF JAVA PROGRAM • Since main() method of java is not returning any value and hence its return type must be void. • Since main() method of java executes only once throughout the java program execution and hence its nature must be static. • Since main() method must be accessed by every java programmer and hence whose access specifies must be public. •Each and every main() method of java must take array of objects of String. Block of statements represents set of executable statements which are in term calling user-defined methods are containing business-logic. The file naming conversion in the java programming is that which-ever class is containing main() method, that class name must be given as a file name with an extension .java. 84 SCION RESEARCH AND DEVELOPMENT
  • 85. MAIN() METHOD IN JAVA Main() Method in Java main() method is starting execution block of a java program or any java program start their execution from main method. If any class contain main() method known as main class. Syntax of main() method: Syntax public static void main(String args[]) { ....... ....... } 85 SCION RESEARCH AND DEVELOPMENT
  • 86. Public public is a keyword in a java language whenever if it is preceded by main() method the scope is available anywhere in the java environment that means main() method can be executed from anywhere. main() method must be accessed by every java programmer and hence whose access specifier must be public. Static static is a keyword in java if it is preceded by any class properties for that memory is allocated only once in the program. Static method are executed only once in the program. main() method of java executes only once throughout the java program execution and hence it declare must be static. 86 SCION RESEARCH AND DEVELOPMENT MAIN() METHOD IN JAVA
  • 87. Void void is a special data type also known as no return type, whenever it is preceded by main() method that will be never return any value to the operating system. main() method of java is not returning any value and hence its return type must be void. String args[] String args[] is a String array used to hold command line arguments in the form of String values. In case of main() method following changes are acceptable 1. We can declare String[] in any valid form. • String[] args • String args[] • String []args 87 SCION RESEARCH AND DEVELOPMENT MAIN() METHOD IN JAVA
  • 88. 2. Instance of String[] we can take var-arg String parameter is String... Syntax main(String[] args) --> main(String... args) 3.We can change the order of modifiers i.e Instead of Syntax public static we can take static public 4. Instead of args we can take any valid java identifier. Syntax public static void main(String a[]) 88 SCION RESEARCH AND DEVELOPMENT MAIN() METHOD IN JAVA
  • 89. 89 Example of override main() method public class mainclass { public static void main(String[] args) { System.out.println("Execution starts from Main()"); } void main(int args) System.out.println("Override main()"); } double main(int i, double d) { System.out.println("Override main()"); return d; } } Output Execution starts from Main() SCION RESEARCH AND DEVELOPMENT MAIN() METHOD IN JAVA We can overload main() method ? Yes, We can overload main() method. A Java class can have any number of main() methods. But run the java program, which class should have main() method with signature as "public static void main(String[] args). If you do any modification to this signature, compilation will be successful. But, not run the java program. we will get the run time error as main method not found.
  • 90. COMMAND LINE Command Line Arguments in Java If any input value is passed through the command prompt at the time of running of the program is known as command line argument by default every command line argument will be treated as string value and those are stored in a string array of main() method. Syntax for Compile and Run CMD programs Compile By -> Javac Mainclass.java Run By -> Java Mainclass value1 value2 value3 .................... 90 SCION RESEARCH AND DEVELOPMENT
  • 91. COMMAND LINE Program Command Line Argument in Java class CommandLineExample { public static void main(String args[]) { System.out.println("Argument is: "+args[0]); } } Compile and Run above programs Compile By > Javac CommandLineExample.java Run By > Java CommandLineExample Porter Output Argument is: Porter 91 SCION RESEARCH AND DEVELOPMENT
  • 92. COMMAND LINE Example of command-line argument in java class SumDemo { public static void main(String args[]) { System.out.println("Sum: "+args[0]); } } Compile and Run above programs Compile By > Javac SumDemo.java Run By > Java SumDemo 10 20 Output 92 Sum: 30 SCION RESEARCH AND DEVELOPMENT
  • 93. COMMAND LINE • When the above statement is executing the following sequence of steps will take place. • Class loader sub-system loads SumDemo along with Command line argument(10, 20) and in main memory. • JVM takes the loaded class SumDemo along • with Command line arguments (10, 20) and place the number of values in the length variable that is 2. • JVM looks for main() that is JVM will place the Command in the main() in the form of string class that is. • Hence all the CMD line arguments of Java are sending to main() method available in the form of an array of object of String class (every CMD are available or stored in main method in the form of an array of object of String class). JVM calls the main() method with respect to load class 93 SumDemo that is SumDemo.main(). SCION RESEARCH AND DEVELOPMENT
  • 94. Accept command line arguments and display their values class CMD { public static void main(String k[]) { System.out.println("no. of arguments ="+k.length); for(int i=0;i< k.length;i++) { System.out.println(k[i]); } } } Note: Except + operator any numeric operation not allowed in command line arguments. 94 SCION RESEARCH AND DEVELOPMENT COMMAND LINE
  • 95. class squareDemo { int no, result; void square(String s) { int no=Integer.parseInt(s); result=no*no; System.out.println("Square: " +result); } } class CMD { public static void main(String args[]) { System.out.println("no of arguments: "+args.length); squareDemo obj=new squareDemo(); obj.square(args[0]); } } 95 SCION RESEARCH AND DEVELOPMENT COMMAND LINE Square of Number by reading value from command prompt.
  • 96. System.out.println() in Java In java language print() and println() are the predefined non-static method of printStream class used to display value or message either in the same line or line by line respectively. PrintStream class is having fixed object reference in the System class (existing as a static properties) so that either print() or println() method can be called with following syntax.. PRINT LINE 96 SCION RESEARCH AND DEVELOPMENT
  • 97. Syntax System.out.print("--------------"); System.out.println("------------"); /* "out" is Object reference of printStream class existing in system class as a static property. */ 97 SCION RESEARCH AND DEVELOPMENT Example class PrintStream { println() { //-----------> non-static ........ } //-----------> non-static print() { ........ } } class System { Static PrintStream out; Static PrintStream err; } PRINT LINE
  • 98. Examples of SOP Statements Example System.out.println("Hello"); // ---------> Hello int x=10, y=20; System.out.println("x"); System.out.println(x); // ---------> x // ---------> 10 System.out.println("Hello"+x); System.out.println(x+y); System.out.println(x+y+"Hello"); // ---------> Hello10 // ---------> 30 // ---------> 1020Hello Example class Hello { public static void main(String arg[]) { System.out.println("Hello word"); Output Hello Word PRINT LINE 98 } } SCION RESEARCH AND DEVELOPMENT
  • 99. DECISION MAKING STMT Decision Making Statement in Java Decision making statement statements is also called selection statement. That is depending on the condition block need to be executed or not which is decided by condition. If the condition is "true" statement block will be executed, if condition is "false" then statement block will not be executed. In java there are three types of decision making statement. • if • if-else • switch if-then Statement if-then is most basic statement of Decision making statement. It tells to program to execute a certain part of code only if particular condition is true. 99 SCION RESEARCH AND DEVELOPMENT
  • 100. Syntax if(condition) { Statement(s) } Example if statement class Hello { int a=10; public static void main(String[] args) { if(a<15) { System.out.println("Hello good morning!"); Hello good morning 100 } SCION RESEARCH AND DEVELOPMENT } } Output DECISION MAKING STMT
  • 101. if-else statement In general it can be used to execute one block of statement among two blocks, in java language if and else are the keyword in java. Syntax if(condition) { Statement(s) } else { Statement(s) }… 101 SCION RESEARCH AND DEVELOPMENT DECISION MAKING STMT
  • 102. In the above syntax whenever condition is true all the if block statement are executed, remaining statement of the program by neglecting. If the condition is false else block statement executed and neglecting if block statements. 102 SCION RESEARCH AND DEVELOPMENT DECISION MAKING STMT
  • 103. Example if else import java.util.Scanner; class Oddeven { public static void main(String[] args){ int no; Scanner s=new Scanner(System.in); System.out.println("Enter any number :"); no=s.nextInt(); if(no%2==0) { System.out.println("Even number"); } else { System.out.println("Odd number"); Output Enter any number : 10 Even number DECISION MAKING STMT 103 } } } SCION RESEARCH AND DEVELOPMENT
  • 104. Switch Statement The switch statement in java language is used to execute the code from multiple conditions or case. It is same like if else-if ladder statement. A switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and string. Syntax switch(expression/variable) { case value: //statements // any number of case statements break; //optional default: //optional //statements 104 } SCION RESEARCH AND DEVELOPMENT SWITCH STATEMENT
  • 105. Rules for apply switch statement With switch statement use only byte, short, int, char data type (float data type is not allowed). You can use any number of case statements within a switch. Value for a case must be same as the variable in switch. Limitations of switch statement Logical operators cannot be used with switch statement. For instance Example SWITCH STATEMENT 105 case k>=20: // not allowed SCION RESEARCH AND DEVELOPMENT
  • 106. Example of switch case import java.util.*; class switchCase { public static void main(String arg[]) { int ch; System.out.println("Enter any number (1 to 7) :"); Scanner s=new Scanner(System.in); ch=s.nextInt(); switch(ch) { case 1: System.out.println("Today is Monday"); break; case 2: System.out.println("Today is Tuesday"); break; 106 SCION RESEARCH AND DEVELOPMENT SWITCH STATEMENT
  • 107. Output Enter any number (1 to 7) : 5 SWITCH STATEMENT case 3: System.out.println("Today is Wednesday"); break; case 4: System.out.println("Today is Thursday"); break; case 5: System.out.println("Today is Friday"); break; case 6: System.out.println("Today is Saturday"); break; case 7: System.out.println("Today is Sunday"); default: System.out.println("Only enter value 1 to 7"); } } } Today is Friday 107 SCION RESEARCH AND DEVELOPMENT
  • 108. LOOPING STATEMENT Looping Statement in Java Looping statement are the statements execute one or more statement repeatedly several number of times. In java programming language there are three types of loops; while, for and do-while. Why use loop ? When you need to execute a block of code several number of times then you need to use looping concept in Java language. Advantage with looping statement • Reduce length of Code • Take less memory space. • Burden on the developer is reducing. • Time consuming process to execute the program is reduced. 108 SCION RESEARCH AND DEVELOPMENT
  • 109. LOOPING STATEMENT Difference between conditional and looping statement Conditional statement executes only once in the program where as looping statements executes repeatedly several number of time. While loop In while loop first check the condition if condition is true then control goes inside the loop body otherwise goes outside of the body. while loop will be repeats in clock wise direction Syntax while(condition) { Statement(s) Increment / decrements (++ or --); } 109 SCION RESEARCH AND DEVELOPMENT
  • 110. Example while loop class whileDemo { public static void main(String args[]) { int i=0; while(i<5) { System.out.println(+i ); i++; } Output 0 1 2 3 LOOPING STATEMENT 4 110 SCION RESEARCH AND DEVELOPMENT
  • 111. for loop for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts Initialization, Condition and Increment or Decrements Syntax for ( initialization; condition; increment ) { statement(s); } LOOPING STATEMENT 111 SCION RESEARCH AND DEVELOPMENT
  • 112. • Initialization: This step is execute first and this is execute only once when we are entering into the loop first time. This step is allow to declare and initialize any loop control variables. • Condition: This is next step after initialization step, if it is true, the body of the loop is executed, if it is false then the body of the loop does not execute and flow of control goes outside of the for loop. • Increment or Decrements: After completion of Initialization and Condition steps loop body code is executed and then Increment or Decrements steps is execute. This statement allows to update any loop LOOPING STATEMENT 112 control variables. SCION RESEARCH AND DEVELOPMENT
  • 113. Control flow of for loop • First initialize the variable • In second step check condition • In third step control goes inside loop body and execute. • At last increase the value of variable 113 • Same process is repeat until condition not false. SCION RESEARCH AND DEVELOPMENT LOOPING STATEMENT
  • 114. LOOPING STATEMENT Display any message exactly 5 times. Example of for loop class Hello { public static void main(String args[]) { int i; for (i=0; i<5; i++) { System.out.println("Hello Friends !"); } } } Output Hello Friends ! Hello Friends ! Hello Friends ! Hello Friends ! 114 Hello Friends ! SCION RESEARCH AND DEVELOPMENT
  • 115. do-while • A do-while loop is similar to a while loop, except that a do-while loop is execute at least one time. • A do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given condition at the end of the block (in while). Syntax do { Statement(s) increment/decrement (++ or --) } 115 while(); SCION RESEARCH AND DEVELOPMENT LOOPING STATEMENT
  • 116. LOOPING STATEMENT When use do..while loop • when we need to repeat the statement block at least one time then use do- while loop. In do-while loop post-checking process will be occur, that is after execution of the statement block condition part will be executed. • In below example you can see in this program i=20 and we check condition i is less than 10, that means condition is false but do..while loop execute once and print Hello world ! at one time. 116 SCION RESEARCH AND DEVELOPMENT
  • 117. Example do..while loop class dowhileDemo { public static void main(String args[]) { int i=20; do { System.out.println("Hello world !"); i++; } while(i<10); } } Output LOOPING STATEMENT 117 Hello world ! SCION RESEARCH AND DEVELOPMENT
  • 118. 118 Example do..while loop class dowhileDemo { public static void main(String args[]) { int i=0; do { System.out.println(+i ); i++; } while(i<5); } } Output 1 2 3 4 LOOPING STATEMENT 5 SCION RESEARCH AND DEVELOPMENT
  • 119. Wrapper classes in java For each and every fundamental data type there exist a pre-defined class, Such predefined class is known as wrapper class. The purpose of wrapper class is to convert numeric string data into numerical or fundamental data. Why use wrapper classes ? We know that in java whenever we get input form user, it is in the form of string value so here we need to convert these string values in different datatype (numerical or fundamental data), for this conversion we use wrapper classes. 119 SCION RESEARCH AND DEVELOPMENT WRAPPER CLASS
  • 120. } Output Sum before: 1020 WRAPPER CLASS Example of wrapper class class WraperDemo { public static void main(String[] args) { String s[] = {"10", "20"}; System.out.println("Sum before:"+ s[0] + s[1]); // 1020 int x=Integer.parseInt(s[0]); // convert String to Integer int y=Integer.parseInt(s[1]); // convert String to Integer int z=x+y; System.out.println("sum after: "+z); // 30 } Sum after: 30 120 SCION RESEARCH AND DEVELOPMENT
  • 121. WRAPPER CLASS Explanation: In the above example 10 and 20 are store in String array and next we convert these values in Integer using "int x=Integer.parseInt(s[0]);" and "int y=Integer.parseInt(s[1]);" statement In "System.out.println("Sum before:"+ s[0] + s[1]);" Statement normally add two string and output is 1020 because these are String numeric type not number. 121 SCION RESEARCH AND DEVELOPMENT
  • 122. Converting String data into fundamental or numerical We know that every command line argument of java program is available in the main() method in the form of array of object of string class on String data, one can not perform numerical operation. To perform numerical operation it is highly desirable to convert numeric String into fundamental numeric value. Example • "10" --> numeric String --> only numeric string convert into numeric type or value. • "10x" --> alpha-numeric type --> this is not conversion. • "ABC" --> non-numeric String no conversion. • " A" --> char String no conversion. Only ' A'is convert into ASCII value that is 65 but ' A'is not convert into numeric value because it is a String value. 122 SCION RESEARCH AND DEVELOPMENT WRAPPER CLASS
  • 123. Fundamental DataType Wrapper CalssName Conversion method from numeric string into fundamental or numeric value Byte Byte public static byte parseByte(String) Short Short public static short parseShort(String) Int Integer public static integer parseInt(String) Long Long public static long parseLong(String) float Float public static float parseFloat(String) double Double public static double parseDouble(String) char Character boolean Boolean public static boolean parseBoolean(String) 123 SCION RESEARCH AND DEVELOPMENT WRAPPER CLASS Fundamental data type and corresponding wrapper classes The following table gives fundamental data type corresponding wrapper class name and conversion method from numerical String into numerical values or fundamental value.
  • 124. WRAPPER CLASS How to use wrapper class methods All the wrapper class methods are static in nature so we need to call these method using class.methodName(). • for Integer: int x=Integer.parseInt(String); • for float: float x=Float.parseFloat(String); • for double: double x=Double.parseDouble(String); Each and every wrapper class contains the following generalized method for converting numeric String into fundamental values. 124 Here xxx represents any fundamental data type. SCION RESEARCH AND DEVELOPMENT
  • 125. NAMING CONVERSION Naming Conversion of Java Sun micro system was given following conversions by declaring class, variable, method etc. So that it is highly recommended to follow this conversion while writing real time code. Why Using naming Conversion Different Java programmers can have different styles and approaches to write program. By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does, and leaving more time to fix or modify it. 1. Every package name should exist a lower case latter. Example package student; // creating package 125 import java.lang; // import package SCION RESEARCH AND DEVELOPMENT
  • 126. NAMING CONVERSION 2.First letter of every word of class name or interface name should exists in upper case. Example class StudentDetails { ..... } interface FacultyDetail { ..... } 3.Every constant value should exists in upper case latter. It is containing more than one word than it should be separated with underscore (-). Example class Student { final String COLLEGE_NAME="abcd"; 126 .... } SCION RESEARCH AND DEVELOPMENT
  • 127. NAMING CONVERSION Note: if any variable is preceded by final keyword is known as constant value. Example class Student { Final String Student_name="abcd"; } While declaring variable name, method, object reference the first letter of first word should be exits in lower case but from the second words onward the first letter should exists in upper case. class Student { String StudentName="xyz"; void instantStudentDetails(); { .... .... } 127 Student final SCION RESEARCH AND DEVELOPMENT
  • 128. According to CamelCase if name is combined with two words, second word will start with uppercase letter always. General Example studentName, customerAccount. In term of java programming e.g. actionPerformed(), NAMING CONVERSION CamelCase in java naming conventions Java follows camelcase syntax for naming the class, interface, method and variable. 128 firstName, ActionEvent, ActionListener etc. SCION RESEARCH AND DEVELOPMENT
  • 129. Syntax import package1.package2.......*; IMPORT STATEMENT Import statements in Java Import is a keyword in java language used to import the predefined properties of java API into current working java program. 129 Used to import all the predefined properties of given package. SCION RESEARCH AND DEVELOPMENT
  • 130. Syntax import pack1.package2.............Class_Name/Interface_Name; Used to import specific class or interface in a java program. Java API is a collection of package, package is a container which is collection of predefined classes and interfaces. Note: Import statement should be the first statement of the java programs. 130 SCION RESEARCH AND DEVELOPMENT IMPORT STATEMENT
  • 131. Access Modifiers in Java Access modifiers are those which are applied before data members or methods of a class. These are used to where to access and where not to access the data members or methods. In Java programming these are classified into four types: • Private • Default (not a keyword) • Protected • Public Note: Default is not a keyword (like public, private, protected are keyword) If we are not using private, protected and public keywords, then JVM is by default taking as default access modifiers. 131 SCION RESEARCH AND DEVELOPMENT ACCESS MODIFIERS
  • 132. Note: Protected members of the class are accessible within the same class and another class of same package and also accessible in inherited class of 132 another package. SCION RESEARCH AND DEVELOPMENT ACCESS MODIFIERS Access modifiers are always used for, how to reuse the features within the package and access the package between class to class, interface to interface and interface to a class. Access modifiers provide features accessing and controlling mechanism among the classes and interfaces.
  • 133. ACCESS MODIFIERS Rules for access modifiers: The following diagram gives rules for Access modifiers. 133 SCION RESEARCH AND DEVELOPMENT
  • 134. ACCESS MODIFIERS private: Private members of class in not accessible anywhere in program these are only accessible within the class. Private are also called class level access modifiers. Example class Hello { private int a=20; private void show() { System.out.println("Hello java"); } } public class Demo { public static void main(String args[]) { Hello obj=new Hello(); System.out.println(obj.a); //Compile Time Error, you can't access private obj.show(); //Compile Time Error, you can't access private methods 134 } } SCION RESEARCH AND DEVELOPMENT
  • 135. public static void main(String args[]) { Hello obj=new Hello(); System.out.println(obj.a); Output 20 ACCESS MODIFIERS public: Public members of any class are accessible anywhere in the program in the same class and outside of class, within the same package and outside of the package. Public are also called universal access modifiers. Example class Hello { public int a=20; public void show() { System.out.println("Hello java"); } } public class Demo { 135 Hello Java obj.show(); } } SCION RESEARCH AND DEVELOPMENT
  • 136. ACCESS MODIFIERS protected: Protected members of the class are accessible within the same class and another class of the same package and also accessible in inherited class of another package. Protected are also called derived level access modifiers. In below the example we have created two packages pack1 and pack2. In pack1, class A is public so we can access this class outside of pack1 but method show is declared as a protected so it is only accessible outside of package pack1 only through inheritance. Example : // save A.java package demo; public class DEMO { protected void show() { System.out.println(" Hello Java"); 136 } } SCION RESEARCH AND DEVELOPMENT
  • 137. //save B.java package PACKAGE2; import demo.*; public class CLASS_2 extends DEMO { public static void main(String args[]) { CLASS_2 obj = new CLASS_2(); obj.show(); } } Output Hello Java ACCESS MODIFIERS 137 SCION RESEARCH AND DEVELOPMENT
  • 138. ACCESS MODIFIERS default: Default members of the class are accessible only within the same class and another class of the same package. The default are also called package level access modifiers. Example //save by A.java package demo; public class DEMO { void show() { System.out.println(" Hello Java"); } } 138 SCION RESEARCH AND DEVELOPMENT
  • 139. //save by B.java package PACKAGE2; //import demo.*; public class CLASS_2 { public static void main(String args[]) { DEMO obj = new DEMO(); //Compile Time Error, can't access outside the package obj.show(); //Compile Time Error, can't access outside the package } } Output ACCESS MODIFIERS Hello Java 139 SCION RESEARCH AND DEVELOPMENT
  • 140. ARRAY IN JAVA Array is a collection of similar type of data. It is fixed in size means that you can't increase the size of array at run time. It is a collection of homogeneous data elements. It stores the value on the basis of the index value. Advantage of Array • One variable can store multiple value: The main advantage of the array is we can represent multiple value under the same name. • Code Optimization: No, need to declare a lot of variable of same type data, We can retrieve and sort data easily. • Random access: We can retrieve any data from array with the help of the index value. 140 SCION RESEARCH AND DEVELOPMENT
  • 141. Disadvantage of Array • The main limitation of the array is Size Limit when once we declare array there is no chance to increase and decrease the size of an array according to our requirement, • Hence memory point of view array concept is not recommended to use. To overcome this limitation in Java introduce the collection concept. Types of Array There are two types of array in Java. • Single Dimensional Array • Multidimensional Array 141 SCION RESEARCH AND DEVELOPMENT ARRAY IN JAVA
  • 142. Array Declaration Single dimension array declaration. Syntax 1. int[] a; 2. int a[]; 3. int []a; Note: At the time of array declaration we cannot specify the size of the array. For Example int[5] a; this is wrong. 2D Array declaration. Syntax 1. int[][] a; 2. int a[][]; 142 6. int []a[]; 4. int[] a[]; SCION RESEARCH AND DEVELOPMENT 3. int [][]a; ARRAY IN JAVA 5. int[] []a;
  • 143. int[] arr = new int[10]; (or) int[] arr = {10,20,30,40,50}; Accessing array elements 143 SCION RESEARCH AND DEVELOPMENT Access the elements of array by using index value of an elements. Syntax - arrayname[n-1]; Access Array Elements int[] arr={10,20,30,40}; System.out.println("Elemen t at 4th place"+arr[2]); // The size of array is 10. ARRAY IN JAVA Every array in a Java is an object, Hence we can create array by using new keyword. Syntax
  • 144. Example of Array public class ArrayEx { public static void main(String []args) { int arr[] = {10,20,30}; for (int i=0; i < arr.length; i++) { System.out.println(arr[i]); } } } Output 10 20 30 ARRAY IN JAVA 144 SCION RESEARCH AND DEVELOPMENT
  • 145. Note: 1) At the time of array creation we must be specify the size of array otherwise get an compile time error. For Example • int[] a=new int[]; Invalid. • int[] a=new int[5]; Valid 2) If we specify the array size as negative int value, then we will get run- time error, NegativeArraySizeException. 3) To specify the array size the allowed data types are byte, short, int, char If we use other data type then we will get an Compile time error. 4) The maximum allowed size of array in Java is 2147483647 (It is the maximum value of int data type) 145 SCION RESEARCH AND DEVELOPMENT ARRAY IN JAVA
  • 146. ARRAY IN JAVA Difference Between Length and Length() in Java length: It is a final variable and only applicable for array. It represent size of array. Example int[] a=new int[10]; System.out.println(a.length); // 10 System.out.println(a.length()); // Compile time error length(): It is the final method applicable only for String objects. It represents the number of characters present in the String. Example String s="Java"; System.out.println(s.length()); // 4 146 System.out.println(s.length); // Compile time error SCION RESEARCH AND DEVELOPMENT
  • 147. Final keyword in java It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance. It is used at variable level, method level and class level. In java language final keyword can be used in following way. • Final at variable level • Final at method level • Final at class level FINAL KEYWORD 147 SCION RESEARCH AND DEVELOPMENT
  • 148. Final at variable level Final keyword is used to make a variable as a constant. This is similar to const in other language. A variable declared with the final keyword cannot be modified by the program after initialization. This is useful to universal constants, such as "PI". Final Keyword in java Example public class Circle { public static final double PI=3.14159; public static void main(String[] args) { System.out.println(PI); } } 148 SCION RESEARCH AND DEVELOPMENT FINAL KEYWORD
  • 149. Final at method level • It makes a method final, meaning that sub classes can not override this method. The compiler checks and gives an error if you try to override the method. • When we want to restrict overriding, then make a method as a final. Example public class A { public void fun1() { ....... } public final void fun2() { ....... } 149 } SCION RESEARCH AND DEVELOPMENT FINAL KEYWORD
  • 150. class B extends A { public void fun1() { ....... } public void fun2() { // it gives an error because we can not override final method } } 150 SCION RESEARCH AND DEVELOPMENT FINAL KEYWORD
  • 151. FINAL KEYWORD Example of final keyword at method level class Employee { final void disp() { System.out.println("Hello Good Morning"); } } class Developer extends Employee { void disp() { System.out.println("How are you ?"); } 151 } SCION RESEARCH AND DEVELOPMENT
  • 152. class FinalDemo { public static void main(String args[]) { Developer obj=new Developer(); obj.disp(); } } Output It gives an error 152 SCION RESEARCH AND DEVELOPMENT FINAL KEYWORD
  • 153. Final at class level It makes a class final, meaning that the class can not be inheriting by other classes. When we want to restrict inheritance then make class as a final. Example public final class A { ...... } public class B extends A { // it gives an error, because we can not inherit final class } 153 SCION RESEARCH AND DEVELOPMENT FINAL KEYWORD
  • 154. Developer obj=new Developer(); Developer obj=new Developer(); obj.show(); 154 } } SCION RESEARCH AND DEVELOPMENT Output: It gives an error FINAL KEYWORD Example of final keyword at class level final class Employee { int salary=10000; } class Developer extends Employee { void show() { System.out.println("H ello Good Morning"); } } class FinalDemo { public static void main(String args[]) {
  • 155. THIS KEYWORD this is a reference variable that refers to the current object. It is a keyword in java language represents current class object Usage of this keyword • It can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • It can be used to invoke current class method (implicitly) • It can be passed as an argument in the method call. • It can be passed as argument in the constructor call. • It can also be used to return the current class instance. 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 155 between formal parameter and member of the class) SCION RESEARCH AND DEVELOPMENT
  • 156. To differentiate between formal parameter and data member of the class, the data member of the class must be preceded by "this". "this" keyword can be use in two ways. 1- this . (this dot) 2 - this() (this off) this . (this dot) which can be used to differentiate variable of class and formal parameters of method or constructor. "this" keyword are used for two purpose, they are It always points to current class object. • Whenever the formal parameter and data member of the class are similar and JVM gets an ambiguity (no clarity between formal parameter and data members of the class). • To differentiate between formal parameter and data member of the class, the 156 SCION RESEARCH AND DEVELOPMENT THIS KEYWORD
  • 157. THIS KEYWORD Syntax - this.data member of current class. Note: If any variable is preceded by "this" JVM treated that variable as class variable. 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); 157 } SCION RESEARCH AND DEVELOPMENT
  • 158. THIS KEYWORD 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 158 SCION RESEARCH AND DEVELOPMENT
  • 159. THIS KEYWORD In the above example, parameter (formal arguments) and instance variables are same that is why we are using "this" keyword to distinguish between local variable and instance variable. Example of this keyword in java class Employee { int id; String name; Employee(int id,String name) { this.id = id; this.name = name; } void show() { System.out.println(id+" "+name); 159 } SCION RESEARCH AND DEVELOPMENT
  • 160. THIS KEYWORD 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 Note 1: The scope of "this" keyword is within the class. Note 2: The main purpose of using "this" keyword in real life application is to differentiate variable of class or formal parameters of methods or constructor (it is highly recommended to use the same variable name either in a class or method and constructor while working with similar 160 objects). SCION RESEARCH AND DEVELOPMENT
  • 161. THIS KEYWORD Difference between this and super keyword Super keyword is always pointing to base class (scope outside the class) features and "this" keyword is always pointing to current class (scope is within the class) features. Example when no need of this keyword class Employee { int id; String name; Employee(int i,String n) { id = i; name = n; } void show() { 161 System.out.println(id+" "+name); SCION RESEARCH AND DEVELOPMENT
  • 162. } 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 162 SCION RESEARCH AND DEVELOPMENT THIS KEYWORD
  • 163. THIS KEYWORD In the above example, no need of use this keyword because parameter (formal arguments) and instance variables are different. This keyword is only use when parameter (formal arguments) and instance variables are same. this () which can be used to call one constructor within the another constructor without creation of objects multiple time for the same class. Syntax this(); // call no parameterized or default constructor this(value1,value2,.....) //call parameterize constructor this keyword used to invoke current class method (implicitly) By using this keyword you can invoke the method of the current class. If you do not use the this keyword, compiler automatically adds this keyword 163 at time of invoking of the method. SCION RESEARCH AND DEVELOPMENT
  • 165. Example of this keyword class Student { void show() { System.out.prin tln("You got A+"); } void marks() { 165 } SCION RESEARCH AND DEVELOPMENT //no need to use this here because compiler does it. this.show(); } void display() { show(); //compiler act marks() as this.marks() THIS KEYWORD
  • 166. Syntax You got A+ 166 SCION RESEARCH AND DEVELOPMENT THIS KEYWORD public static void main(String args[]) { Student s = new Student(); s.display(); } }
  • 167. Rules to use this() this() always should be the first statement of the constructor. One constructor can call only other single constructor at a time by using this(). THIS KEYWORD 167 SCION RESEARCH AND DEVELOPMENT
  • 168. Super keyword in java Super keyword in java is a reference variable that is used to refer parent class object. Super is an implicit keyword create by JVM and supply each and every java program for performing important role in three places. • At variable level • At method level • At constructor level Need of super keyword: Whenever the derived class is inherits the base class features, there is a possibility that base class features are similar to derived class features and JVM gets an ambiguity. In order to differentiate between base class features and derived class features must be preceded by super keyword. Syntax 168 super.baseclass features. SCION RESEARCH AND DEVELOPMENT SUPER KEYWORD
  • 169. Super at variable level: Whenever the derived class inherit base class data members there is a possibility that base class data member are similar to derived class data member and JVM gets an ambiguity. In order to differentiate between the data member of base class and derived class, in the context of derived class the base class data members must be preceded by super keyword. Syntax super.baseclass datamember name if we are not writing super keyword before the base class data member name than it will be referred as current class data member name and base class data member are hidden in the context of derived class. 169 SCION RESEARCH AND DEVELOPMENT SUPER KEYWORD
  • 170. HR obj=new HR(); obj.display(); 170 Salary: 20000.0 } } SCION RESEARCH AND DEVELOPMENT Output SUPER KEYWORD Program without using super keyword class Employee { float salary=10000; } class HR extends Employee { float salary=20000; void display() { System.out.println(" Salary: "+salary);//print current class salary } } class Supervarible { public static void main(String[] args)
  • 171. HR obj=new HR(); obj.display(); 171 Salary: 10000.0 } } SCION RESEARCH AND DEVELOPMENT Output SUPER KEYWORD Program using super keyword al variable level class Employee{ float salary=10000; } class HR extends Employee { float salary=20000; void display() { System.out.println(" Salary: "+super.salary);//pr int base class salary } } class Supervarible { public static void main(String[] args)
  • 172. Super at method level • The super keyword can also be used to invoke or call parent class method. It should be use in case of method overriding. In other word super keyword use when base class method name and derived class method name have same name. • In the below example Student and Faculty both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority of local is high. • In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method. 172 SCION RESEARCH AND DEVELOPMENT SUPER KEYWORD
  • 173. SUPER KEYWORD Example of super keyword at method level class Student { void message() { System.out.printl n("Good Morning Sir"); } } class Faculty extends Student { void message() System.out.println("Good Morning Students"); } void display() { message();//will invoke or call current class message() 173 } SCION RESEARCH AND DEVELOPMENT
  • 174. Output Good Morning Students Good Morning Sir 174 SCION RESEARCH AND DEVELOPMENT SUPER KEYWORD public static void main(String args[]) { Student s=new Student(); s.display(); } }
  • 175. s.display(); } 175 Good Morning Sir } SCION RESEARCH AND DEVELOPMENT Output SUPER KEYWORD Program where super is not required class Student { void message() { System.out.printl n("Good Morning Sir"); } } class Faculty extends Student { void display() { message();//will invoke or call parent class message() method } public static void main(String args[]) { Student s=new Student();
  • 176. SUPER KEYWORD Super at constructor level The super keyword can also be used to invoke or call the parent class constructor. Constructor are calling from bottom to top and executing from top to bottom. To establish the connection between base class constructor and derived class constructors JVM provides two implicit methods they are: Super() Super(...) Super() Super() It is used for calling super class 176 SCION RESEARCH AND DEVELOPMENT
  • 177. SUPER KEYWORD Super keyword used to call base class constructor Syntax class Employee { Employee() { System.out.println("Employee class Constructor"); } } class HR extends Employee { HR() { super(); //will invoke or call parent class constructor System.out.println("HR class Constructor"); } } 177 SCION RESEARCH AND DEVELOPMENT
  • 178. class Supercons { public static void main(String[] args) { HR obj=new HR(); } } Output Employee class Constructor HR class Constructor Note: super() is added in each class constructor automatically by compiler 178 SCION RESEARCH AND DEVELOPMENT SUPER KEYWORD
  • 179. In constructor, default constructor is provided by compiler automatically but it also adds super() before the first statement of constructor. If you are creating your own constructor and you do not have either this() or super() as the first statement, compiler will provide super() as the first statement 179 of the constructor. SCION RESEARCH AND DEVELOPMENT SUPER KEYWORD
  • 180. Super(...) Super(...) It is used for calling super class parameterize constructor from the context of derived class constructor. Important rules Whenever we are using either super() or super(...) in the derived class constructors the super always must be as a first executable statement in the body of derived class constructor otherwise we get a compile time error. Rule 1 and Rule 3 Whenever the derived class constructor want to call default constructor of base class, in the context of derived class constructors we write super(). Which is optional to write because every base class constructor contains single form of default constructor? 180 SCION RESEARCH AND DEVELOPMENT SUPER KEYWORD
  • 181. Rule 2 and Rule 4 Whenever the derived class constructor wants to call parameterized constructor of base class in the context of derived class constructor we must write super(...). which is mandatory to write because a base class may contain multiple forms of parameterized constructors. The following diagram use possibilities of using super() and super(........) 181 SCION RESEARCH AND DEVELOPMENT SUPER KEYWORD
  • 182. Synchronized is a Modifier which is applicable for the method or block, we SYNCHRONIZED KEYWORD Synchronized Keyword in Java Synchronized Keyword is used for when we want to allowed only one thread at a time then use Synchronized modifier. If a method or block declared as a Synchronized then at a time only one thread is allowed to operate on the given object. 182 can not declare class or variable with this modifier. SCION RESEARCH AND DEVELOPMENT
  • 183. SYNCHRONIZED KEYWORD Advantage of Synchronized The main advantage of Synchronized keyword is we can resolve data inconsistency problem. Dis-Advantage of Synchronized The main dis-advantage of Synchronized keyword is it increased the waiting time of thread and effect performance of the system, Hence if there is no specific requirement it is never recommended to use synchronized keyword. 183 SCION RESEARCH AND DEVELOPMENT
  • 184. VOLATILE KEYWORD Volatile Keyword in Java • If the variable keep on changing such type of variables we have to declare with volatile modifier. • Volatile is a modifier applicable only for variables but not for method and class. • If a variable declared as volatile then for every thread a separate local copy will be created. • Every intermediate modification performed by that thread will takes place in local copy instead of master copy. • Once the value got finalized just before terminating the thread the master copy value will be updated with local stable value. Advantage of Volatile The main advantage of Volatile keyword is we can resolve data 184 inconsistency problems. SCION RESEARCH AND DEVELOPMENT
  • 185. VOLATILE KEYWORD Dis-Advantage of Volatile The main dis-advantage of Volatile keyword is, crating and maintaining a separate copy for every thread, increases complexity of the programming and effects performance of the system. Hence if there is no specific requirement it is never recommended to use volatile keyword, and it is almost outdated keyword. Note: Volatile variable means its value keep on changing where as final variable means its value never changes. Hence final-Volatile combination is illegal combination for variables. 185 SCION RESEARCH AND DEVELOPMENT
  • 186. Static Block in Java • Static block is a set of statements, which will be executed by the JVM before execution of main method. • At the time of class loading if we want to perform any activity we have to define that activity inside static block because this block execute at the time of class loading. • In a class we can take any number of static block but all these blocks will be execute from top to bottom. STATIC BLOCK 186 SCION RESEARCH AND DEVELOPMENT
  • 187. Syntax Static { ........ //Set of Statements ........ } Note: In real time application static block can be used whenever we want to execute any instructions or statements before execution of main method. Example of Static Block class StaticDemo { Static { System.out.println( "Hello how are u ?"); 187 This is main() } } SCION RESEARCH AND DEVELOPMENT } public static void main(String args[]) { System.out.println("This is main()"); Output Hello how are u ? STATIC BLOCK
  • 188. STATIC BLOCK Run java program without main method class StaticDemo { static { System.out.println( "Hello how are u ?"); } } Output: Hello how are u ? Exception is thread "main" java.lang.no- suchmethodError: Main 188 SCION RESEARCH AND DEVELOPMENT
  • 189. STATIC BLOCK More than one static block in a program class StaticDemo { static { System.out.println( "First static block"); } static { System.out.println( "Second Static block"); } public static void main(String args[]) { 189 } SCION RESEARCH AND DEVELOPMENT
  • 190. Output: First static block Second static block This is main() Note: "Here static block run according to there order (sequence by) from top to bottom Why a static block executes before the main method ? A class has to be loaded in main memory before we start using it. Static block is executed during class loading. This is the reason why a static block executes before the main method. 190 SCION RESEARCH AND DEVELOPMENT STATIC BLOCK
  • 191. INNER CLASSES Inner Classes in Java Programming If one class is existing within another class is known as inner class or nested class Syntax class Outerclass_name { ..... class Innerclass_name1{ ..... } class Innerclass_name1{ ..... } } 191 SCION RESEARCH AND DEVELOPMENT
  • 192. INNER CLASSES The main purpose of using inner class • To provide more security by making those inner class properties specific to only outer class but not for external classes. • To make more than one property of classes private properties. • Private is a keyword in java language, it is preceded by any variable that property can be access only within the class but not outside of it (provides more security). • If more than one property of class wants to make as private properties than all can capped under private inner class. Syntax class Outerclass_name { private class Innerclass_name { ..... //private properties 192 } } SCION RESEARCH AND DEVELOPMENT
  • 193. Note: No outer class made as private class otherwise this is not available for JVM at the time of execution. Rules to access properties of inner classes • Inner class properties can be accessed in the outer class with the object reference but not directly. • Outer class properties can be access directly within the inner class. • Inner class properties can't be accessed directly or by creating directly object. Note: In special situation inner class property can be accessed in the external class by creating special objects with the reference of its outer class. 193 SCION RESEARCH AND DEVELOPMENT INNER CLASSES
  • 194. //outer class 194 SCION RESEARCH AND DEVELOPMENT Example class A { void fun1() { System.out.println("Hello fun1()"); // inner class properties should be access using //object reference in outer class. B ob=new B(); ob.x=10 System.out.println("x= "+ob.x); ob.fun2(); } INNER CLASSES
  • 195. // inner class 195 } SCION RESEARCH AND DEVELOPMENT // inner class variable //inner class fun2() class B { int x; void fun2() { System.out.println("Hello fun2()"); //outer class properties can be access directly fun3(); } } INNER CLASSES void fun3() // outer class fun3() { System.out.println("Hello fun3()"); }
  • 196. // external class 196 } } SCION RESEARCH AND DEVELOPMENT class C { void fun3() { System.out.println("Hello fun3()"); } } class IncDemo { public static void main(String args[]) { A oa=new A(); oa.fun1(); C oc=new C(); oc.fun3(); Output Hello fun1() X=10 Hello fun2() Hello fun3() INNER CLASSES
  • 197. Accessing inner class properties in the external class 1. If inner class in non static the object can be created with the following syntax Syntax class Outer_class { class Inner_class { ..... } ..... } class External_class { Outer_class.Inner_Class objectrefernce=new Outer_Class.External_Class(); } 197 SCION RESEARCH AND DEVELOPMENT INNER CLASSES
  • 198. 2. If inner class is static the object reference can be created with the following syntax Syntax class Outer_class { static class Inner_Class { ..... ..... } } class External_Class { Outer_class.Inner_Class objectrefernce=new Outer_Class.External_Cla ss(); } } 198 SCION RESEARCH AND DEVELOPMENT INNER CLASSES
  • 199. //Outer class 199 void fun2() SCION RESEARCH AND DEVELOPMENT // non-static inner class //inner class variable //inner class fun1() Example class A { class B { int x; void fun1() { System.out.println("Hello fun1()"); } } static class C { int y=20; //static inner class // inner class variable INNER CLASSES
  • 200. { System.out.println("Hello fun2()"); } } } class IncDemo { public static void main(String args[]) { B.ob=new A().new.B(); System.out.println(ob.x); ob.fun1(); C. oc=new A.C(); System.out.println(oc.y); oc.fun2(); } } SCION RESEARCH AND DEVELOPMENT 200 INNER CLASSES
  • 201. Abstract class in Java We know that every Java program must start with a concept of class that is without the class concept there is no Java program perfect. In Java programming we have two types of classes they are • Concrete class • Abstract class Concrete class in Java A concrete class is one which is containing fully defined methods or implemented method. Example class Helloworld { void display() { System.out.println("Good Morning........"); 201 } } SCION RESEARCH AND DEVELOPMENT ABSTRACT CLASS
  • 202. ABSTRACT CLASS Here Helloworld class is containing a defined method and object can be created directly. Create an object Helloworld obj=new Helloworld(); obj.display(); Every concrete class has specific features and these classes are used for specific requirement, but not for common requirement. If we use concrete classes for fulfill common requirements than such application will get the following limitations. • Application will take more amount of memory space (main memory). • Application execution time is more. • Application performance is decreased. To overcome above limitation you can use abstract class. 202 SCION RESEARCH AND DEVELOPMENT
  • 203. Abstract class in Java A class that is declared with abstract keyword, is known as abstract class. An abstract class is one which is containing some defined method and some undefined method. In java programming undefined methods are known as un- Implemented, or abstract method. ABSTRACT CLASS 203 SCION RESEARCH AND DEVELOPMENT
  • 204. Syntax abstract class className { } Example abstract class A { } If any class have any abstract method then that class become an abstract class. Example class Vechile { abstract void Bike(); } Class Vechile is become an abstract class because it have abstract Bike() 204 method. SCION RESEARCH AND DEVELOPMENT ABSTRACT CLASS
  • 205. ……. } Abstract method An abstract method is one which contains only declaration or prototype but it never contains body or definition. In order to make any undefined method as abstract whose declaration is must be predefined by abstract keyword. Syntax Example abstract void sum(); abstract void diff(int, int); ABSTRACT CLASS Make class as abstract class To make the class as abstract class, whose definition must be preceded by a abstract keyword. Example abstract class Vechile { 205 abstract ReturnType methodName(List of formal parameter) SCION RESEARCH AND DEVELOPMENT
  • 206. // abstract method 206 Speed limit is 40 km/hr.. SCION RESEARCH AND DEVELOPMENT //indirect object creation Example of abstract class abstract class Vechile { abstract void speed(); } class Bike extends Vechile { void speed() { System.out.println("Speed limit is 40 km/hr.."); } public static void main(String args[]) { Vachile obj = new Bike(); obj.speed(); } } Output ABSTRACT CLASS
  • 207. ABSTRACT CLASS Create an Object of abstract class An object of abstract class cannot be created directly, but it can be created indirectly. It means you can create an object of abstract derived class. You can see in above example Example - Vehicle obj = new Bike(); //indirect object creation Abstract class of Java always contains common features. • Every abstract class participates in inheritance. • Abstract class definitions should not be made as final because abstract classes always participate in inheritance classes. • An object of abstract class cannot be created directly, but it can be created indirectly. • All the abstract classes of Java makes use of polymorphism along with method overriding for business logic development and makes use of dynamic binding 207 for execution logic. SCION RESEARCH AND DEVELOPMENT
  • 208. ABSTRACT CLASS Advantage of abstract class • Less memory space for the application • Less execution time • More performance Why abstract class have no abstract static method ? In abstract classes we have the only abstract instance method, but not containing abstract static methods because every instance method is created for performing repeated operation where as static method is created for performing a one time operations in other word every abstract method is instance but not static. Abstract base class An abstract base class is one which is containing physical representation of abstract methods which are inherited by various sub classes. 208 SCION RESEARCH AND DEVELOPMENT
  • 209. Abstract derived class • An abstract derived class is one which is containing logic representation of abstract methods which are inherited from abstract base class with respect to both abstract base class and abstract derived class one can not create objects directly, but we can create their objects indirectly both abstract base class and abstract derived class are always reusable by various sub classes. When the derived class inherits multiple abstract method from abstract base class and if the derived class is not defined at least one abstract method then the derived class is known as abstract derived class and whose definition must be made as abstract by using abstract keyword. (When the derived class becomes an abstract derived class). • If the derived class defined all the abstract methods which are inherited from abstract Base class, then the derived class is known as concrete 209 derived class. SCION RESEARCH AND DEVELOPMENT ABSTRACT CLASS
  • 211. public static void main(String args[]) { Vachile obj = new Bike(); obj.speed(); 211 Speed limit is 40 km/hr.. obj.mileage(); } } SCION RESEARCH AND DEVELOPMENT Output Mileage is 60 km/ltr.. ABSTRACT CLASS Example of abstract class having method body abstract class Vehicle { abstract void speed(); void mileage() { System.out.println("Mil eage is 60 km/ltr.."); } } class Bike extends Vehicle { void speed() { System.out.println("Speed limit is 40 km/hr.."); }
  • 212. ABSTRACT CLASS Example of abstract class having constructor, data member, methods abstract class Vehicle { int limit=40; Vechile() { System.out.println("co nstructor is invoked"); } void getDetails() { System.out.println("it has two wheels"); } abstract void run(); } class Bike extends Vehicle { void run() { 212 System.out.println("running safely.."); SCION RESEARCH AND DEVELOPMENT
  • 213. } public static void main(String args[]) { Vachile obj = new Bike(); obj.run(); obj.getDetails(); System.out.println(obj.limit); } } Output constructor is invoked running safely.. it has two wheels 213 40 SCION RESEARCH AND DEVELOPMENT ABSTRACT CLASS
  • 214. 214 SCION RESEARCH AND DEVELOPMENT DIFFERENCE BETWEEN ABSTRACT CLASS AND CONCRETE CLASS Concrete class Abstract class A Concrete class is used for specific requirement Abstract class is used to fulfill a common requirement. Object of concrete class can create directly. Object of an abstract class can not create directly (can create indirectly). Concrete class containing fully defined methods or implemented method. Abstract class has both undefined method and defined method.
  • 215. 215 SCION RESEARCH AND DEVELOPMENT some time it can be accessed with object reference. DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA The variable of any class are classified into two types; • Static or class variable • Non-static or instance variable Static variable in Java Memory for static variable is created only one in the program at the time of loading of class. These variables are preceded by static keyword. static variable can access with class reference. Non-static variable in Java Memory for non-static variable is created at the time of create an object of class. These variable should not be preceded by any static keyword Example: These variables can access with object reference. Difference between non-static and static variable Note: static variable not only can be access with class reference but also
  • 216. 216 SCION RESEARCH AND DEVELOPMENT Non-static variable Static variable 1 These variable should not be preceded by any static keyword Example: class A{int a;} These variables are preceded by static keyword. Example class A{static int b;} 2 Memory is allocated for these variable whenever an object is created Memory is allocated for these variable at the time of loading of the class. 3 Memory is allocated multiple time whenever a new object is created. Memory is allocated for these variable only once in the program. 4 Non-static variable also known as instance variable while because memory is allocated whenever instance is created. Memory is allocated at the time of loading of class so that these are also known as class variable. 5 Non-static variable are specific to an object Static variable are common for every object that means there memory location can be sharable by every object reference or same class. 6 Non-static variable can access with object reference. Syntax obj_ref.variable_name Static variable can access with class reference. Syntax class_name.variable_name DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
  • 217. 217 SCION RESEARCH AND DEVELOPMENT Example of static and non-static variable. class Student { int roll_no; float marks; String name; static String College_Name ="ITM"; } class StaticDemo { public static void main(String args[]) { Student s1=new Student(); s1.roll_no=100; DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
  • 218. SCION RESEARCH AND DEVELOPMENT 218 s2.roll_no=200; s2.marks=75.8f; s2.name="zyx"; System.out.println(s2.roll_no); System.out.println(s2.marks); System.out.println(s2.name); System.out.println(Student.Coll ege_Name); } } Output 100 65.8 abcd ITM 200 75.8 zyx ITM DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA System.out.println(s1.roll_no); System.out.println(s1.marks); System.out.println(s1.name); System.out.println(Student.College_Name); //or System.out.println(s1. College_Name); but first is use in real time. Student s2=new Student();
  • 219. 219 Note: In the above example College_Name variable is commonly sharable SCION RESEARCH AND DEVELOPMENT by both S1 and S2 objects. DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA
  • 220. 220 SCION RESEARCH AND DEVELOPMENT //will get memory when instance is created int count=0; Counter() { count++; System.out.p rintln(count ); } DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA Understand static and non-static variable using counter Program of counter without static variable In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable. Example class Counter {
  • 221. Output 1 1 1 221 SCION RESEARCH AND DEVELOPMENT DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA public static void main(String args[]) { Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } }
  • 222. //will get memory only once 3 222 } } SCION RESEARCH AND DEVELOPMENT static int count=0; Counter() { count++; System.out.println (count); } public static void main(String args[]) { Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); Output 1 2 DIFFERENCE BETWEEN STATIC AND NON-STATIC VARIABLE IN JAVA Program of counter by static variable As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value. Example class Counter {
  • 223. Non-Static method Static method These method never be preceded by static keyword Example: void fun1() { ...... ...... } These method always preceded by static keyword Example: static void fun2() { ...... ...... } 223 SCION RESEARCH AND DEVELOPMENT DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA Difference between Static and non-static method in Java In case of non-static method memory is allocated multiple time whenever method is calling. But memory for static method is allocated only once at the time of class loading. Method of a class can be declared in two different ways • Non-static methods • Static methods Difference between non-static and static Method
  • 224. 224 SCION RESEARCH AND DEVELOPMENT Non-Static method Static method Memory is allocated multiple time whenever method is calling. Memory is allocated only once at the time of class loading. It is specific to an object so that these are also known as instance method. These are common to every object so that it is also known as member method or class method. These methods always access with object reference Syntax: Objref.methodname(); These property always access with class reference Syntax: className.methodname(); If any method wants to be execute multiple time that can be declare as non static. If any method wants to be execute only once in the program that can be declare as static . Note: In some cases static methods not only can access with class reference but also can access with object reference. DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
  • 225. 225 Example of Static and non-Static Method class A { void fun1() { System.out.p rintln("Hello I am Non- Static"); } static void fun2() { System.out.println("Hello I am Static"); } } class Person { public static void main(String args[]) { A oa=new A(); // non static method // static method oa.fun1(); A.fun2(); } } Output Hello I am Non-Static SCION RESEARCH AND DEVELOPMENT Hello I am Static DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
  • 226. 226 DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA Following table represent how the static and non-static properties are accessed in the different static or non-static method of same class or other class. SCION RESEARCH AND DEVELOPMENT
  • 227. 227 SCION RESEARCH AND DEVELOPMENT Program to accessing static and non-static properties. Example class A { int y; void f2() { System.o ut.println ("Hello f2()"); } } class B { int z; void f3(){ System.ou t.println( DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
  • 228. } } class Sdemo { static int x; static void f1(){ System.out.prin tln("Hello f1()"); } public static void main(String[] args) { x=10; System.out.println("x="+x); f1(); System.out.println("Hello main"); B b1=new B(); b1.f3(); 228 } } SCION RESEARCH AND DEVELOPMENT DIFFERENCE BETWEEN STATIC AND NON-STATIC METHOD IN JAVA
  • 229. CONSTRUCTOR IN JAVA • constructor in Java is a special member method which will be called implicitly (automatically) by the JVM whenever an object is created for placing user or programmer defined values in place of default values. In a single word constructor is a special member method which will be called automatically whenever object is created. • The purpose of constructor is to initialize an object called object initialization. Constructors are mainly create for initializing the object. Initialization is a process of assigning user defined values at the time of allocation of memory space. Syntax className() { ....... ....... 229 } SCION RESEARCH AND DEVELOPMENT
  • 230. CONSTRUCTOR IN JAVA Advantages of constructors in Java • A constructor eliminates placing the default values. • A constructor eliminates calling the normal or ordinary method implicitly. How Constructor eliminate default values ? Constructor are mainly used for eliminate default values by user defined values, whenever we create an object of any class then its allocate memory for all the data members and initialize there default values. To eliminate these default values by user defined values we use constructor. 230 SCION RESEARCH AND DEVELOPMENT
  • 231. 231 Constructor Example in Java class Sum { int a,b; Sum() { a=10; b=20; } public static void main(String s[]) { Sum s=new Sum(); c=a+b; System.out.println("Sum: "+c); } } Output Sum: 30 In above example when we create an SCION RESEARCH AND DEVELOPMENT object of "Sum" class then constructor of this class call and initialize user defined value in a=10 and b=20. if we can not create constructor of Sum class then it print " Sum: 0 " because default values of integer is zero. CONSTRUCTOR IN JAVA
  • 232. • Constructor will be called automatically when the object is created. • Constructor name must be similar to name of the class. • Constructor should not return any value even void also. Because basic aim is to place the value in the object. (if we write the return type for the constructor then that constructor will be treated as ordinary method). • Constructor definitions should not be static. Because constructors will be called each and every time, whenever an object is creating. • Constructor should not be private provided an object of one class is created in another class (Constructor can be private provided an object of one class created in the same class). • Constructors will not be inherited from one class to another class (Because every class constructor is create for initializing its own data members). • The access specifies of the constructor may or may not be private. 232 SCION RESEARCH AND DEVELOPMENT Rules or properties of a constructor
  • 233. 233 SCION RESEARCH AND DEVELOPMENT Method Constructor 1 Method can be any user defined name Constructor must be class name 2 Method should have return type It should not have any return type (even void) 3 Method should be called explicitly either with object reference or class reference It will be called automatically whenever object is created 4 Method is not provided by compiler in any case. The java compiler provides a default constructor if we do not have any constructor. CONSTRUCTOR IN JAVA • If the access specifier of the constructor is private then an object of corresponding class can be created in the context of the same class but not in the context of some other classes. • If the access specifier of the constructor is not private then an object of corresponding class can be created both in the same class context and in other class context. Difference between Method and Constructor
  • 234. 234 SCION RESEARCH AND DEVELOPMENT CONSTRUCTOR IN JAVA Types of constructors Based on creating objects in Java constructor are classified in two types. They are • Default or no argument Constructor • Parameterized constructor. Default Constructor A constructor is said to be default constructor if and only if it never take any parameters. If any class does not contain at least one user defined constructor than the system will create a default constructor at the time of compilation it is known as system defined default constructor.
  • 235. // Call default constructor 235 contain any user defined constructor. SCION RESEARCH AND DEVELOPMENT // Initialization ..... clsname () { Block of statements; } ..... } Note: System defined default constructor is created by java compiler and does not have any statement in the body part. This constructor will be executed every time whenever an object is created if that class does not CONSTRUCTOR IN JAVA Syntax of Default Constructor class className {
  • 236. //TestDemo.java 236 }; SCION RESEARCH AND DEVELOPMENT Example: class Test { int a, b; Test () { System.out.println("I am from default Constructor..."); a=10; b=20; System.out.println("Value of a: "+a); System.out.println("Value of b: "+b); } CONSTRUCTOR IN JAVA Example of default constructor. In below example, we are creating the no argument constructor in the Test class. It will be invoked at the time of object creation.
  • 237. class TestDemo { public static void main(String [] args) { Test t1=new Test (); } }; 237 SCION RESEARCH AND DEVELOPMENT Output: I am from default Constructor... Value of a: 10 Value of b: 20 CONSTRUCTOR IN JAVA
  • 238. Rule-1: Whenever we create an object only with default constructor, defining the default constructor is optional. If we are not defining default constructor of a class, then JVM will call automatically system defined default constructor. If we define, JVM will call user defined default constructor. Purpose of default constructor? Default constructor provides the default values to the object like 0, 0.0, null etc. depending on their type (for integer 0, for string null). Explanation: In the below class, we are not creating any constructor so compiler provides a default constructor. Here 0, 0.0 and null values are provided by default constructor. 238 SCION RESEARCH AND DEVELOPMENT CONSTRUCTOR IN JAVA
  • 239. 239 s1.show(); } } SCION RESEARCH AND DEVELOPMENT } } class TestDemo { public static void main(String [] args) { Student s1=new Student(); CONSTRUCTOR IN JAVA Example of default constructor that displays the default values class Student { int roll; float marks; String name; void show() { System.out.println("Roll: "+roll); System.out.println("Marks: "+marks); System.out.println("Name: "+name); Output Roll: 0 Marks: 0.0 Name: null
  • 240. //parameterized constructor 240 new ClassName(value1, value2,.....); SCION RESEARCH AND DEVELOPMENT ClassName(list of parameters) { } } Syntax to call parametrized constructor ClassName objref=new ClassName(value1, value2,.....); OR CONSTRUCTOR IN JAVA parameterized constructor If any constructor contain list of variable in its signature is known as parameterized constructor. A parameterized constructor is one which takes some parameters. Syntax class ClassName {
  • 241. CONSTRUCTOR IN JAVA Example of Parameterized Constructor class Test { int a, b; Test(int n1, int n2) { System.out. println("I am from Parameteri zed Constructo r..."); a=n1; b=n2; System.out.println("Value of a = "+a); System.out.println("Value of b = "+b); } }; class TestDemo1 { 241 } }; SCION RESEARCH AND DEVELOPMENT
  • 242. CONSTRUCTOR IN JAVA Important points Related to Parameterized Constructor • Whenever we create an object using parameterized constructor, it must be define parameterized constructor otherwise we will get compile time error. Whenever we define the objects with respect to both parameterized constructor and default constructor, It must be define both the constructors. • In any class maximum one default constructor but 'n' number of parameterized constructors. 242 SCION RESEARCH AND DEVELOPMENT
  • 243. CONSTRUCTOR IN JAVA Example of default constructor, parameterized constructor and overloaded constructor class Test { int a, b; Test () { Syso("I am from default Constructor..."); a=1; b=2; System.out.println("Value of a ="+a); System.out.println("Value of b ="+b); } Test (int x, int y) { System.out.println("I am from double Paraceterized Constructor"); 243 SCION RESEARCH AND DEVELOPMENT
  • 244. a=x; b=y; System.out.println("Value of a ="+a); System.out.println("Value of b ="+b); } Test (int x) { System.out.println("I am from single Parameterized Constructor"); a=x; b=x; System.out.println("Value of a ="+a); System.out.println("Value of b ="+b); } Test (Test T) { 244 System.out.println("I am from Object Parameterized Constructor..."); SCION RESEARCH AND DEVELOPMENT CONSTRUCTOR IN JAVA
  • 245. a=T.a; b=T.b; System.out.println("Value of a ="+a); System.out.println("Value of b ="+b); } }; class TestDemo2 { public static void main (String k []) { Test t1=new Test (); 245 } }; SCION RESEARCH AND DEVELOPMENT Test t2=new Test (10, 20); Test t3=new Test (1000); Test t4=new Test (t1); Note : By default the parameter passing mechanism is call by reference. CONSTRUCTOR IN JAVA
  • 246. CONSTRUCTOR IN JAVA Constructor Overloading • Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by taking the number of parameters, and their type. • In other words whenever same constructor is existing multiple times in the same class with different number of parameters or order of parameters or type of parameters is known as Constructor overloading. • In general constructor overloading can be used to initialized same or different objects with different values. Why overriding is not possible at constructor level. The scope of constructor is within the class so that it is not possible to 246 achieved overriding at constructor level. SCION RESEARCH AND DEVELOPMENT
  • 247. Syntax class ClassName { ClassName() { .......... .......... } ClassName(dataty pe1 value1) {....... } ClassName(dataty pe1 value1, datatype2 value2) {....... } ClassName(dataty pe2 variable2) {....... } 247 } } SCION RESEARCH AND DEVELOPMENT CONSTRUCTOR IN JAVA
  • 248. Relationship in Java Type of relationship always makes to understand how to reuse the feature from one class to another class. In java programming we have three types of relationship they are. • Is-A Relationship • Has-A Relationship • Uses-A Relationship Is-A relationship • In Is-A relationship one class is obtaining the features of another class by using inheritance concept with extends keywords. • In a IS-A relationship there exists logical memory space 248 SCION RESEARCH AND DEVELOPMENT RELATIONSHIP
  • 249. Example of Is-A Relation class Faculty { float salary=30000; } class Science extends Faculty { float bonous=2000; public static void main(String args[]) { Science obj=new Science(); System.out.println("Salary is:"+obj.salary); System.out.println("Bonous is:"+obj.bonous); } } Output Salary is: 30000.0 249 Bonous is: 2000.0 SCION RESEARCH AND DEVELOPMENT RELATIONSHIP
  • 250. 250 Output Salary is: SCION RESEARCH AND DEVELOPMENT 30000.0 Has-A relationship • In Has-A relationship an object of one class is created as data member in another class the relationship between these two classes is Has-A. • In Has-A relationship there existed physical memory space and it is also known as part of or kind of relationship. Example of Has-A Relation class Employee { float salary=30000; } class Developer extends Employee { float bonus=2000; public static void main(String args[]) { Employee obj=new Employee(); System.out.println("Salary is:"+obj.salary); } } RELATIONSHIP
  • 251. Uses-A relationship • A method of one class is using an object of relationship class the these two classes is another between known as Uses-A relationship. • As long as the method is execution the object space (o1) exists and once the method execution is completed automatically object memory space will be destroyed. RELATIONSHIP 251 SCION RESEARCH AND DEVELOPMENT
  • 252. Example class Employee { float salary=30000; } class Salary extends Employee { void disp() { float bonous=1000; Employee obj=new Employee(); float Total=obj.salary+bonous; System.out.println("Total Salary is:"+Total); } } class Developer { public static void main(String args[]) { Salary s=new Salary(); Total Salary is: 31000.0 252 s.disp(); } } SCION RESEARCH AND DEVELOPMENT RELATIONSHIP Output
  • 253. Note 1: The default relationship in java is Is-A because for each and every class in java there exist an implicit predefined super class is java.lang.Object. Note 2: The universal example for Has-A relationship is System.out (in System.out statement, out is an object of printStream class created as static data member in another system class and printStream class is known as Has-A relationship). Note 3: Every execution logic method (main() ) of execution logic is making use of an object of business logic class and business logic class is known as Uses-A relationship. 253 SCION RESEARCH AND DEVELOPMENT RELATIONSHIP
  • 254. OOP's Concept in Java Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. • Object • Class • Inheritance • Polymorphism • Abstraction • Encapsulation OOPS CONCEPT 254 SCION RESEARCH AND DEVELOPMENT
  • 255. Object Object is the physical as well as logical entity where as class is the only logical entity. Class Class is a blue print which is containing only list of variables and method and no memory is allocated for them. A class is a group of objects that has common properties. Encapsulation Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation. Encapsulation is achieved in C++ language by class concept. The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class. 255 SCION RESEARCH AND DEVELOPMENT OOPS CONCEPT
  • 256. required 256 SCION RESEARCH AND DEVELOPMENT essential Abstraction Abstraction is the concept of exposing only the characteristics and behavior with respect to a context. Hiding of data is known as data abstraction. In object oriented programming language this is implemented automatically while writing the code in the form of class and object. Inheritance The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming. OOPS CONCEPT
  • 257. Polymorphism The process of representing one Form in multiple forms is known as Polymorphism. Here one form represent original form or original method always resides in base class and multiple forms represents overridden method which resides in derived classes. Note: All these concept I will discuss in detail later. 257 SCION RESEARCH AND DEVELOPMENT OOPS CONCEPT
  • 258. Inheritance in Java The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming Important points • In the inheritance the class which is give data members and methods is known as base or super or parent class. • The class which is taking the data members and methods is known as sub or derived or child class. • The data members and methods of a class are known as features. • The concept of inheritance is also known as re-usability or extendable classes or sub classing or derivation. 258 SCION RESEARCH AND DEVELOPMENT INHERITANCE
  • 259. Why use Inheritance ? • For Method Overriding (used for Runtime Polymorphism). • It's main uses are to enable polymorphism and to be able to reuse code for different classes by putting it in a common super class • For code Re-usability Syntax of Inheritance class Subclass-Name extends Superclass-Name { //methods and fields } Real Life Example of Inheritance in Java The real life example of inheritance is child and parents, all the properties INHERITANCE 259 of father are inherited by his son. SCION RESEARCH AND DEVELOPMENT
  • 260. In the above diagram data members and methods are represented in broken line are inherited from faculty class and they are visible in student 260 class logically. SCION RESEARCH AND DEVELOPMENT INHERITANCE The following diagram use view about inheritance.
  • 261. Advantage of inheritance If we develop any application using concept of Inheritance than that application have following advantages, • Application development time is less. • Application take less memory. • Application execution time is less. • Application performance is enhance (improved). • Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and less storage cost. Note: In Inheritance the scope of access modifier increasing is allow but decreasing is not allow. Suppose in parent class method access modifier is default then it's present in child class with default or public or protected access modifier but not private(it decreased scope). 261 SCION RESEARCH AND DEVELOPMENT INHERITANCE
  • 262. Types of Inheritance Based on number of ways inheriting the feature of base class into derived class we have five types of inheritance; they are: • Single inheritance • Multiple inheritance • Hierarchical inheritance • Multilevel inheritance • Hybrid inheritance 262 SCION RESEARCH AND DEVELOPMENT INHERITANCE
  • 263. Single inheritance In single inheritance there exists single base class and single derived class. Example of Single Inheritance class Faculty { float salary=30000; } class Science extends Faculty{ float bonus=2000; public static void main(String args[]) { Science obj=new Science(); System.out.println("Salary is:"+obj.salary); System.out.println("Bonus is:"+obj.bonus); } } Output INHERITANCE 263 Salary is: 30000.0 Bonus is: 2000.0 SCION RESEARCH AND DEVELOPMENT
  • 264. INHERITANCE Multilevel inheritances in Java In Multilevel inheritances there exists single base class, single derived class and multiple intermediate base classes. Single base class + single derived class + multiple intermediate base classes. Intermediate base classes An intermediate base class is one in one context with access derived class and in another context same class access base class. 264 SCION RESEARCH AND DEVELOPMENT
  • 265. INHERITANCE Example of Multilevel Inheritance class Faculty { float total_sal=0, salary=30000; } class HRA extends Faculty { float hra=3000; } class DA extends HRA { float da=2000; } 265 SCION RESEARCH AND DEVELOPMENT
  • 266. class Science extends DA { float bonous=2000; public static void main(String args[]) { Science obj=new Science(); obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonous; System.out.println("Total Salary is:"+obj.total_sal); } } Output Total Salary is: 37000.0 266 SCION RESEARCH AND DEVELOPMENT
  • 267. Multiple inheritance In multiple inheritance there exist multiple classes and single derived class. The concept of multiple inheritance is not supported in java through concept of classes but it can be supported through the concept of interface. 267 SCION RESEARCH AND DEVELOPMENT INHERITANCE
  • 268. Hybrid inheritance • Combination of any inheritance type • In the combination if one of the combination is multiple inheritance then the inherited combination is not supported by java through the classes concept but it can be supported through the concept of interface. INHERITANCE 268 SCION RESEARCH AND DEVELOPMENT
  • 269. INHERITANCE Inheriting the feature from base class to derived class In order to inherit the feature of base class into derived class we use the following syntax Syntax class ClassName-2 extends ClasssName-1 { variable declaration; Method declaration; } Explanation • ClassName-1 and ClassName-2 represents name of the base and derived classes respectively. class into derived class it improves the functionality of derived class.269 SCION RESEARCH AND DEVELOPMENT
  • 270. INHERITANCE Important Points for Inheritance: In java programming one derived class can extends only one base class because java programming does not support multiple inheritance through the concept of classes, but it can be supported through the concept of Interface. Whenever we develop any inheritance application first create an object of bottom most derived class but not for top most base class. When we create an object of bottom most derived class, first we get the memory space for the data members of top most base class, and then we get the memory space for data member of other bottom most derived class. Bottom most derived class contains logical appearance for the data members of all top most base classes. If we do not want to give the features of base class to the derived class then the definition of the base class must be preceded by final hence final base 270 classes are not reusable or not inheritable. SCION RESEARCH AND DEVELOPMENT
  • 271. INHERITANCE • If we are do not want to give some of the features of base class to derived class than such features of base class must be as private hence private features of base class are not inheritable or accessible in derived class. • Data members and methods of a base class can be inherited into the derived class but constructors of base class can not be inherited because every constructor of a class is made for initializing its own data members but not made for initializing the data members of other classes. • An object of base class can contain details about features of same class but an object of base class never contains the details about special features of its derived class (this concept is known as scope of base class object). • For each and every class in java there exists an implicit predefined super class called java.lang.Object. because it providers garbage collection facilities to its sub classes for collecting un-used memory space and 271 improved the performance of java application. SCION RESEARCH AND DEVELOPMENT
  • 272. Example of Inheritance class Faculty { float salary=30000; } class Science extends Faculty { float bonus=2000; public static void main(String args[]) { Science obj=new Science(); System.out.println("Salary is:"+obj.salary); System.out.println("Bonus is:"+obj.bonus); } } Output Salary is: 30000.0 272 Bonus is: 2000.0 SCION RESEARCH AND DEVELOPMENT INHERITANCE
  • 273. INHERITANCE Why multiple inheritance is not supported in java? Due to ambiguity problem java does not support multiple inheritance at class level. Example class A { void disp() { System.out.println("Hello"); } } class B { 273 void disp() SCION RESEARCH AND DEVELOPMENT
  • 274. //Now which disp() method would be invoked? 274 level. SCION RESEARCH AND DEVELOPMENT obj.disp(); } } In above code we call both class A and class B disp() method then it confusion which class method is call. So due to this ambiguity problem in java do not use multiple inheritance at class level, but it support at interface INHERITANCE System.out.println("How are you ?"); } } class C extends A,B { //suppose if it were Public Static void main(String args[]) { C obj=new C();
  • 275. INHERITANCE Difference between Java Inheritance and C++ Inheritance The main difference between java Inheritance and C++ Inheritance is; Java doesn’t support multiple inheritance but C++ support. 275 SCION RESEARCH AND DEVELOPMENT
  • 276. METHOD OVERLOADING Method Overloading in Java Whenever same method name is exiting multiple times in the same class with different number of parameter or different order of parameters or different types of parameters is known as method overloading. 276 SCION RESEARCH AND DEVELOPMENT
  • 277. METHOD OVERLOADING Why use method Overloading in Java ? • Suppose we have to perform addition of given number but there can be any number of arguments, if we write method such as a(int, int)for two arguments, b(int, int, int) for three arguments then it is very difficult for you and other programmer to understand purpose or behaviors of method they can not identify purpose of method. • So we use method overloading to easily figure out the program. For example above two methods we can write sum(int, int) and sum(int, int, int) using method overloading concept. Syntax class class_Name { Returntype method() { 277 ......... SCION RESEARCH AND DEVELOPMENT
  • 278. } Returntype method(datatype1 variable1) { ......... } Returntype method(datatype1 variable1, datatype2 variable2) { ......... } Returntype method(datatype2 variable2) { ......... } Returntype method(datatype2 variable2, datatype1 variable1) { ......... } 278 } SCION RESEARCH AND DEVELOPMENT METHOD OVERLOADING
  • 279. By changing number of arguments In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers. 279 SCION RESEARCH AND DEVELOPMENT Different ways to overload the method There are two ways to overload the method in java • By changing number of arguments or parameters • By changing the data type METHOD OVERLOADING
  • 280. obj.sum(10, 20); obj.sum(10, 20, 30); } 280 60 } SCION RESEARCH AND DEVELOPMENT Output 30 METHOD OVERLOADING Example Method Overloading in Java class Addition { void sum(int a, int b) { System.out.println(a+b ); } void sum(int a, int b, int c) { System.out.println(a+b+c); } public static void main(String args[]) { Addition obj=new Addition();
  • 281. METHOD OVERLOADING By changing the data type In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two float arguments. Example Method Overloading in Java class Addition { void sum(int a, int b) { System.out.println(a+b); } void sum(float a, float b) { System.out.println(a+b); 281 } SCION RESEARCH AND DEVELOPMENT
  • 282. public static void main(String args[]) { Addition obj=new Addition(); obj.sum(10, 20); obj.sum(10.05, 15.20); } } Output 30 25.25 282 SCION RESEARCH AND DEVELOPMENT
  • 283. METHOD OVERLOADING Why Method Overloading is not possible by changing the return type of method? In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur: because there was problem: Example of Method Overloading class Addition { int sum(int a, int b) { System.out.println(a+b); } double sum(int a, int b) 283 { SCION RESEARCH AND DEVELOPMENT
  • 284. //Compile Time Error 284 SCION RESEARCH AND DEVELOPMENT System.out.println(a+b); } public static void main(String args[]) { Addition obj=new Addition(); int result=obj.sum(20,20); } }
  • 285. Explanation of Code Example int result=obj.sum(20,20); Here how can java determine which sum() method should be called Note: The scope of overloading is within the class. Any object reference of class can call any of overloaded method. Can we overload main() method ? • Yes, We can overload main() method. A Java class can have any number of main() methods. • But run the java program, which class should have main() method with signature as "public static void main(String[] args). • If you do any modification to this signature, compilation will be successful. But, not run the java program. 285 • we will get the run time error as main method not found. SCION RESEARCH AND DEVELOPMENT METHOD OVERLOADING
  • 286. METHOD OVERLOADING Example of overload main() method public class mainclass { public static void main(String[] args) { System.out.println("Execution starts from Main()"); } void main(int args) { System.out.println("Override main()"); } double main(int i, double d) { System.out.println("Override main()"); return d; } } Output 286 Execution starts from Main() SCION RESEARCH AND DEVELOPMENT
  • 287. METHOD OVERRIDING Method Overriding in Java Whenever same method name is existing in both base class and derived class with same types of parameters or same order of parameters is known as method Overriding. Here we will discuss about Overriding in Java. Note: Without Inheritance method overriding is not possible. Advantage of Java Method Overriding • Method Overriding is used to provide specific implementation of a method that is already provided by its super class. • Method Overriding is used for Runtime Polymorphism Rules for Method Overriding • method must have same name as in the parent class. • method must have same parameter as in the parent class. • must be IS-A relationship (inheritance). 287 SCION RESEARCH AND DEVELOPMENT
  • 288. 288 that is why we use method overriding. Output : Man walking SCION RESEARCH AND DEVELOPMENT Man obj = new Man(); obj.walk(); } } Problem is that I have to providea specific implementation of walk() method in subclass METHOD OVERRIDING Understanding the problem without method overriding Lets understand the problem that we may face in the program if we do not use method overriding. Example Method Overriding in Java class Walking { void walk(){ System.out.println("Man walking fastly"); } } class OverridingDemo { public static void main(String args[]) {
  • 289. METHOD OVERRIDING Example of method overriding in Java In this example, we have defined the walk method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding. Example class Walking { void walk() { System.out.println("Man walking fastly"); } } 289 SCION RESEARCH AND DEVELOPMENT
  • 290. 290 } SCION RESEARCH AND DEVELOPMENT obj.walk(); } METHOD OVERRIDING class Man extends walking { void walk() { System.out.println("Man walking slowly"); } } class OverridingDemo { public static void main(String args[]) { Man obj = new Man(); Output Man walking slowly
  • 291. METHOD OVERRIDING Note: Whenever we are calling overridden method using derived class object reference the highest priority is given to current class (derived class). We can see in the above example high priority is derived class. Note: super. (super dot) can be used to call base class overridden method in the derived class. 291 SCION RESEARCH AND DEVELOPMENT
  • 292. METHOD OVERRIDING Accessing properties of base class with respect to derived class object class A { int x; void f1() { x=10; System.o ut.printl n(x); } void f4() { System.out.println("this is f4()"); System.out.println("----------------- "); } }; class B extends A { 292 void f1() { SCION RESEARCH AND DEVELOPMENT
  • 293. int y=20; System.out.println(y); System.out.println("this is f1()"); System.out.println("---------------"); } }; class C extends A { int z; void f1() { z=10; System.ou t.println(z ); System.ou t.println(" this is f1()"); 293 }; SCION RESEARCH AND DEVELOPMENT METHOD OVERRIDING
  • 294. class Override { public static void main(String[] args) { A a1=new B(); a1.f1(); a1.f4(); A c1=new C(); c1.f1(); c1.f4(); } } 294 SCION RESEARCH AND DEVELOPMENT METHOD OVERRIDING
  • 295. METHOD OVERRIDING Example of Implement overriding concept class Person { String name; void sleep(String name) { this.name=na me; System.out.pri ntln(this.nam e +"is sleeping+8hr/ day"); } void walk() { System.out.println("this is walk()"); System.out.println("-----------------"); 295 System.out.println("only student write the exam"); SCION RESEARCH AND DEVELOPMENT
  • 296. 296 SCION RESEARCH AND DEVELOPMENT } void sleep(String name) { super.name=name; System.out.println(super.n ame +"is sleeping 6hr/day"); System.out.println("-------- ----------"); } }; class Developer extends Person { public void designProj() { System.out.println("Design the project"); } void sleep(String name) { super.name=name; System.out.println(super.name +"is sleeping 4hr/day"); METHOD OVERRIDING
  • 297. 297 SCION RESEARCH AND DEVELOPMENT METHOD OVERRIDING } }; class OverideDemo public static void main(String[] args) { Student s1=new Student(); s1.writExams(); s1.sleep("student"); s1.walk(); Developer d1=new Developer(); d1.designProj(); d1.sleep("developer"); } }
  • 298. 298 SCION RESEARCH AND DEVELOPMENT Overloading Overriding 1 Whenever same method or Constructor is existing multiple times within a class either with different number of parameter or with different type of parameter or with different order of parameter is known as Overloading. Whenever same method name is existing multiple time in both base and derived class with same number of parameter or same type of parameter or same order of parameters is known as Overriding. 2 Arguments of method must be different at least arguments. Argument of method must be same including order. 3 Method signature must be different. Method signature must be same. 4 Private, static and final methods can be overloaded. Private, static and final methods can not be override. 5 Access modifiers point of view no restriction. Access modifiers point of view not reduced scope of Access modifiers but increased. 6 Also known as compile time polymorphism or static polymorphism or early binding. Also known as run time polymorphism or dynamic polymorphism or late binding. METHOD OVERLOADING vs. OVERRIDING
  • 299. 299 SCION RESEARCH AND DEVELOPMENT Overloading Overriding 7 Overloading can be exhibited both are method and constructor level. Overriding can be exhibited only at method label. 8 The scope of overloading is within the class. The scope of Overriding is base class and derived class. 9 Overloading can be done at both static and non-static methods. Overriding can be done only at non- static method. 10 For overloading methods return type may or may not be same. For overriding method return type should be same. Note: In overloading we have to check only methods names (must be same) and arguments types (must be different) except these the remaining like return type access modifiers etc. are not required to check But in overriding every things check like method names arguments types return types access modifiers etc. METHOD OVERLOADING vs. OVERRIDING
  • 300. INTERFACE IN JAVA Interface is similar to class which is collection of public static final variables (constants) and abstract methods. The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java. Why we use Interface ? • It is used to achieve fully abstraction. • By using Interface, you can achieve multiple inheritance in java. • It can be used to achieve loose coupling. properties of Interface • It is implicitly abstract. So we no need to use the abstract keyword when declaring an interface. • Each method in an interface is also implicitly abstract, so the abstract 300 keyword is not needed. SCION RESEARCH AND DEVELOPMENT
  • 301. INTERFACE IN JAVA • Methods in an interface are implicitly public. • All the data members of interface are implicitly public static final. How interface is similar to class ? Whenever we compile any Interface program it generate .class file. That means the bytecode of an interface appears in a .class file. How interface is different from class ? • You can not instantiate an interface. • It does not contain any constructors. • All methods in an interface are abstract. • Interface can not contain instance fields. Interface only contains public static final variables. • Interface is can not extended by a class; it is implemented by a class. • Interface can extend multiple interfaces. It means interface support 301 multiple inheritance SCION RESEARCH AND DEVELOPMENT
  • 302. In the above image when we compile any interface program, by default compiler added public static final before any variable and public abstract before any method. Because Interface is design for fulfill universal 302 requirements and to achieve fully abstraction. SCION RESEARCH AND DEVELOPMENT INTERFACE IN JAVA Behavior of compiler with Interface program
  • 303. Declaring Interfaces: The interface keyword is used to declare an interface. Example interface Person { datatype variablename=value; //Any number of final, static fields returntype methodname(list of parameters or no parameters) //Any number of abstract method declarations } Explanations In the above syntax Interface is a keyword interface name can be user defined name the default signature of variable is public static final and for method is public abstract. JVM will be added implicitly public static final 303 before data members and public abstract before method. SCION RESEARCH AND DEVELOPMENT INTERFACE IN JAVA
  • 304. Example public static final datatype variable name=value; ----> for data member public abstract returntype methodname(parameters)---> for method Implementing Interfaces: A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. Example interface Person { void run(); } class Employee implements Person { public void run() { 304 System.out.println("Run fast"); } } SCION RESEARCH AND DEVELOPMENT INTERFACE IN JAVA
  • 305. INTERFACE IN JAVA When we use abstract and when Interface • If we do not know about any things about implementation just we have requirement specification then we should be go for Interface • If we are talking about implementation but not completely (partially implemented) then we should be go for abstract Rules for implementation interface • A class can implement more than one interface at a time. • A class can extend only one class, but implement many interfaces. • An interface can extend another interface, similarly to the way that a class can extend another class. Relationship between class and Interface • Any class can extends another class 305 SCION RESEARCH AND DEVELOPMENT
  • 306. 306 • Any class can Implements another Interface • Any Interface can not extend or Implements any class. INTERFACE IN JAVA • Any Interface can extends another Interface. SCION RESEARCH AND DEVELOPMENT
  • 307. 307 SCION RESEARCH AND DEVELOPMENT Abstract class Interface 1 It is collection of abstract method and concrete methods. It is collection of abstract method. 2 There properties can be reused commonly in a specific application. There properties commonly usable in any application of java environment. 3 It does not support multiple inheritance. It support multiple inheritance. 4 Abstract class is preceded by abstract keyword. It is preceded by Interface keyword. 5 Which may contain either variable or constants. Which should contains only constants. 6 The default access specifier of abstract class methods are default. There default access specifies of interface method are public. INTERFACE IN JAVA Difference between Abstract class and Interface
  • 308. 308 SCION RESEARCH AND DEVELOPMENT Abstract class Interface 7 These class properties can be reused in other class using extend keyword. These properties can be reused in any other class using implements keyword. 8 Inside abstract class we can take constructor. Inside interface we can not take any constructor. 9 For the abstract class there is no restriction like initialization of variable at the time of variable declaration. For the interface it should be compulsory to initialization of variable at the time of variable declaration. 10 There are no any restriction for abstract class variable. For the interface variable can not declare variable as private, protected, transient, volatile. 11 There are no any restriction for abstract class method modifier that means we can use any modifiers. For the interface method can not declare method as strictfp, protected, static, native, private, final, synchronized. INTERFACE IN JAVA
  • 309. // abstract method 309 Run fast SCION RESEARCH AND DEVELOPMENT Example of Interface interface Person { void run(); } class A implements Person { public void run() { System.out.println("Run fast"); } public static void main(String args[]) { A obj = new A(); obj.run(); } } Output INTERFACE IN JAVA
  • 310. INTERFACE IN JAVA Multiple Inheritance using interface Example interface Developer { void disp(); } interface Manager { void show(); } class Employee implements Developer, Manager { public void disp() { System.out.println("Hello Good Morning"); } public void show() { 310 System.out.println("How are you ?"); SCION RESEARCH AND DEVELOPMENT
  • 311. } public static void main(String args[]) { Employee obj=new Employee(); obj.disp(); obj.show(); } } 311 SCION RESEARCH AND DEVELOPMENT Output Hello Good Morning How are you ? INTERFACE IN JAVA
  • 312. INTERFACE IN JAVA Marker or tagged interface An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation. Example public interface Serializable { …… } //Way of writing Serializable interface 312 SCION RESEARCH AND DEVELOPMENT
  • 313. INTERFACE IN JAVA Why interface have no constructor ? • Because, constructor are used for eliminate the default values by user defined values, but in case of interface all the data members are public static final that means all are constant so no need to eliminate these values. • Other reason because constructor is like a method and it is concrete method and interface does not have concrete method it have only abstract methods that's why interface have no constructor. 313 SCION RESEARCH AND DEVELOPMENT
  • 314. ABSTRACTION IN JAVA Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a context. Hiding of data is known as data abstraction. In object oriented programming language this is implemented automatically while writing the code in the form of class and object. Real Life Example of Abstraction in Java Abstraction shows only important things to the user and hides the internal details, for example, when we ride a bike, we only know about how to ride bikes but can not know about how it work? And also we do not know the internal functionality of a bike. 31 4 SCION RESEARCH AND DEVELOPMENT
  • 315. Note: Data abstraction can be used to provide security for the data from the unauthorized methods. Note: In Java language data abstraction can achieve using class. ABSTRACTION IN JAVA Another real life example of Abstraction is ATM Machine; All are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about ATM. 315 SCION RESEARCH AND DEVELOPMENT
  • 316. Example of Abstraction class Customer { int account_no; float balance_Amt; String name; int age; String address; void balance_inquiry() { /* to perform balance inquiry only account number is required that means remaining properties are hidden for balance inquiry method */ } void fund_Transfer() { /* To transfer the fund account number and balance is required and remaining properties are hidden for fund transfer method */ } 316 SCION RESEARCH AND DEVELOPMENT ABSTRACTION IN JAVA
  • 317. ABSTRACTION IN JAVA How to achieve Abstraction ? There are two ways to achieve abstraction in java • Abstract class (0 to 100%) • Interface (Achieve 100% abstraction) Read more about Interface and Abstract class in the previous section. Difference between Encapsulation and Abstraction Encapsulation is not providing full security because we can access private member of the class using reflection API, but in case of Abstraction we can't access static, abstract data member of a class. 317 SCION RESEARCH AND DEVELOPMENT
  • 318. ENCAPSULATION IN JAVA Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation. Encapsulation is achieved in java language by class concept. Combining of state and behavior in a single container is known as encapsulation. In java language encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and behavior represents operations in terms of method. Advantage of Encapsulation The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class. Real life example of Encapsulation in Java The common example of encapsulation is capsule. In capsule all medicine 318 are encapsulated in side capsule. SCION RESEARCH AND DEVELOPMENT
  • 319. Benefits of encapsulation • Provides abstraction between an object and its clients. • Protects an object from unwanted access by clients. • Example: A bank application forbids (restrict) a client to change an 319 Account's balance. SCION RESEARCH AND DEVELOPMENT ENCAPSULATION IN JAVA
  • 320. ENCAPSULATION IN JAVA Let's see the Example of Encapsulation in java class Employee { private String name; public String getName() { return name; } public void setName(String name) { this.name=name; } } 320 SCION RESEARCH AND DEVELOPMENT
  • 321. class Demo { public static void main(String[] args) { Employee e=new Employee(); e.setName("Harry"); System.out.println(e.getName()); } } Output Harry 321 SCION RESEARCH AND DEVELOPMENT ENCAPSULATION IN JAVA
  • 322. POLYMORPHISM IN JAVA The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. Polymorphism is not a programming concept but it is one of the principal of OOPs. For many objects oriented programming language polymorphism principle is common but whose implementations are varying from one objects oriented programming language to another object oriented programming language. 322 SCION RESEARCH AND DEVELOPMENT
  • 323. POLYMORPHISM IN JAVA Real life example of polymorphism Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person present in different-different behaviors. 323 SCION RESEARCH AND DEVELOPMENT
  • 324. POLYMORPHISM IN JAVA How to achieve Polymorphism in Java ? In java programming the Polymorphism principal is implemented with method overriding concept of java. Polymorphism principal is divided into two sub principal they are: • Static or Compile time polymorphism • Dynamic or Runtime polymorphism Note: Java programming does not support static polymorphism because of its limitations and java always supports dynamic polymorphism. Let us consider the following diagram Here original form or original method always resides in base class and multiple forms represents overridden method which resides in derived classes. 324 SCION RESEARCH AND DEVELOPMENT
  • 325. In the above diagram the sum method which is present in BC class is called original form and the sum() method which are present in DC1 and DC2 are called overridden form hence Sum() method is originally available in only one form 325 SCION RESEARCH AND DEVELOPMENT and it implemented is further in multiple forms. Hence Sum() method is one of the polymorphism method. POLYMORPHISM IN JAVA
  • 326. So it is known as runtime 326 } SCION RESEARCH AND DEVELOPMENT determined by the JVM not compiler, polymorphism. Example of Polymorphism in Java class Person { void walk() { System.out.pri ntln("Can Run...."); } POLYMORPHISM IN JAVA Example of Runtime Polymorphism in Java In below example we create two class Person an Employee, Employee class extends Person class feature and override walk() method. We are calling the walk() method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Here method invocation is
  • 327. Output Running fast... 327 SCION RESEARCH AND DEVELOPMENT POLYMORPHISM IN JAVA class Employee extends Person { void walk() { System.out.println("Running Fast..."); } public static void main(String arg[]) { Person p=new Employee(); //upcasting p.walk(); } }
  • 328. Dynamic Binding Dynamic binding always says create an object of base class but do not create the object of derived classes. Dynamic binding principal is always used for executing polymorphic applications. The process of binding appropriate versions (overridden method) of derived classes which are inherited from base class with base class object is known as dynamic binding. Advantages of dynamic binding along with polymorphism with method overriding are. • Less memory space • Less execution time • More performance 328 SCION RESEARCH AND DEVELOPMENT POLYMORPHISM IN JAVA
  • 329. Static polymorphism The process of binding the overloaded method within object at compile time is known as Static polymorphism due to static polymorphism utilization of resources (main memory space) is poor because for each and every overloaded method a memory space is created at compile time when it binds with an object. In C++ environment the above problem can be solve by using dynamic polymorphism by implementing with virtual and pure virtual function so most of the C++ developer in real worlds follows only dynamic polymorphism. Dynamic polymorphism In dynamic polymorphism method of the program binds with an object at runtime the advantage of dynamic polymorphism is allocating the memory space for the method (either for overloaded method or for override method) 329 at run time. SCION RESEARCH AND DEVELOPMENT POLYMORPHISM IN JAVA
  • 330. Conclusion The advantage of dynamic polymorphism is effective utilization of the resources, So Java always use dynamic polymorphism. Java does not support static polymorphism because of its limitation. 330 SCION RESEARCH AND DEVELOPMENT POLYMORPHISM IN JAVA
  • 331. Package in Java A package is a collection of similar types of classes, interfaces and sub- packages. Purpose of package The purpose of package concept is to provide common classes and interfaces for any program separately. In other words if we want to develop any class or interface which is common for most of the java programs than such common classes and interfaces must be place in a package. PACKAGE IN JAVA 331 SCION RESEARCH AND DEVELOPMENT
  • 332. PACKAGE IN JAVA Packages in Java are the way to organize files when a project has many modules. Same like we organized our files in Computer. For example we store all movies in one folder and songs in other folder, here also we store same type of files in a particular package for example in awt package have all classes and interfaces for design GUI components. 332 SCION RESEARCH AND DEVELOPMENT
  • 333. Advantage of package Package is used to categorize the classes and interfaces so that they can be easily maintained • Application development time is less, because reuse the code • Application memory space is less (main memory) • Application execution time is less • Application performance is enhance (improve) • Redundancy (repetition) of code is minimized • Package provides access protection. • Package removes naming collision. Type of package Package are classified into two type which are given below. • Predefined or built-in package 333 • User defined package SCION RESEARCH AND DEVELOPMENT PACKAGE IN JAVA
  • 334. Predefined or built-in package These are the package which are already designed by the Sun Microsystem and supply as a part of java API, every predefined package is collection of predefined classes, interfaces and sub-package. User defined package If any package is design by the user is known as user defined package. User defined package are those which are developed by java programmer and supply as a part of their project to deal with common requirement. Rules to create user defined package • package statement should be the first statement of any package program. • Choose an appropriate class name or interface name and whose modifier must be public. • Any package program can contain only one public class or only one public interface but it can contain any number of normal classes. 334 PACKAGE IN JAVA
  • 335. • Package program should not contain any main class (that means it should not contain any main()) • modifier of constructor of the class which is present in the package must be public. (This is not applicable in case of interface because interface have no constructor.) • The modifier of method of class or interface which is present in the package must be public (This rule is optional in case of interface because interface methods by default public) • Every package program should be save either with public class name or public Interface name 335 SCION RESEARCH AND DEVELOPMENT PACKAGE IN JAVA
  • 336. PACKAGE IN JAVA 336 SCION RESEARCH AND DEVELOPMENT
  • 337. Compile package programs For compilation of package program first we save program with public className.java and it compile using below syntax: Syntax javac -d . className.java Syntax javac -d path className.java Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a separate folder for the given package in given path. When we give specific path then it create a new folder at that location and when we use . (dot) then it crate a folder at current working directory. Note: Any package program can be compile but can not be execute or run. These program can be executed through user defined program which are importing package program. 337 SCION RESEARCH AND DEVELOPMENT PACKAGE IN JAVA
  • 338. PACKAGE IN JAVA Example of package program Package program which is save with A.java and compile by javac -d . A.java Example package mypack; public class A { public void show() { System.out.println("Sum method"); } } Import above class in below program using import packageName.className 338 SCION RESEARCH AND DEVELOPMENT
  • 339. Example import mypack.A; public class Hello { public static void main(String arg[]) { A a=new A(); a.show(); System.out.pr intln("show() class A"); } } Explanation s: In the 339 import class " A"in class Hello using "import mypack.A;" statement. SCION RESEARCH AND DEVELOPMENT PACKAGE IN JAVA
  • 340. PACKAGE IN JAVA Difference between Inheritance and package • Inheritance concept always used to reuse the feature within the program between class to class, interface to interface and interface to class but not accessing the feature across the program. • Package concept is to reuse the feature both within the program and across the programs between class to class, interface to interface and interface to class. Difference between package keyword and import keyword • Package keyword is always used for creating the undefined package and placing common classes and interfaces. • import is a keyword which is used for referring or using the classes and interfaces of a specific package. 340 SCION RESEARCH AND DEVELOPMENT
  • 341. EXCEPTION HANDLING IN JAVA The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful feature of Java to handle run time error and maintain normal flow of java application. Exception An Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's Instructions. Why use Exception Handling Handling the exception is nothing but converting system error generated message into user friendly error message. Whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user 341 friendly error message. SCION RESEARCH AND DEVELOPMENT
  • 342. You can convert system error message into user friendly error message by using exception handling feature of java. For Example: when you divide any number by zero then system generate / by zero so this is not understandable by user so you can convert this message into user friendly error message like Don't enter zero for denominator. 342 SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 343. EXCEPTION HANDLING IN JAVA Hierarchy of Exception classes 343 SCION RESEARCH AND DEVELOPMENT
  • 344. Type of Exception • Checked Exception • Un-Checked Exception Checked Exception Checked Exception are the exception which checked at compile-time. These exception are directly sub-class of java.lang.Exception class. Only for remember: Checked means checked by compiler so checked exception are checked at compile-time. EXCEPTION HANDLING IN JAVA 344 SCION RESEARCH AND DEVELOPMENT
  • 345. EXCEPTION HANDLING IN JAVA Un-Checked Exception Un-Checked Exception are the exception both identifies or raised at run time. These exception are directly sub-class of java.lang.RuntimeException class. Note: In real time application mostly we can handle un-checked exception. Only for remember: Un-checked means not checked by compiler so un- checked exception are checked at run-time not compile time. 345 SCION RESEARCH AND DEVELOPMENT
  • 346. Checked Exception Un-Checked Exception 1 checked Exception are checked at compile time un-checked Exception are checked at run time 2 e.g. FileNotFoundException, NumberNotFoundException etc. e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. 346 SCION RESEARCH AND DEVELOPMENT Difference between Error and Exception Error Exception 1 Can't be handle. Can be handle. 2 Example: NoSuchMethodError OutOfMemoryError Example: ClassNotFoundException NumberFormateException EXCEPTION HANDLING IN JAVA Difference between checked Exception and un-checked Exception
  • 347. EXCEPTION HANDLING IN JAVA Handling the Exception Handling the exception is nothing but converting system error generated message into user friendly error message in others word whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user-friendly error message. You can convert system error message into user-friendly error message by using exception handling feature of java. Use Five keywords for Handling the Exception • try • catch • finally • throws • throw 347 SCION RESEARCH AND DEVELOPMENT
  • 348. EXCEPTION HANDLING IN JAVA Syntax for handling the exception Syntax Try { // state ment s cause s probl em at run time } catch( type of excepti on-1 object- 1) { // statements which will execute compulsory } SCION RESEARCH AND DEVELOPMENT 348
  • 349. EXCEPTION HANDLING IN JAVA Example without Exception Handling Syntax class ExceptionDemo { public static void main(String[] args) { int a=10, ans=0; ans=a/0; System.out.printl n("Denominator not be zero"); } } Abnormally terminate program and give a message like below, this error message is not understandable by user so we convert this error message 349 into user friendly error message, like "denominator not be zero". SCION RESEARCH AND DEVELOPMENT
  • 350. EXCEPTION HANDLING IN JAVA Example of Exception Handling class ExceptionDemo { public static void main(String[] args) { int a=10, ans=0; Try { ans=a/0; } catch (Exception e) { System.out.println("Denominator not be zero"); } } } Output 350 Denominator not be zero SCION RESEARCH AND DEVELOPMENT
  • 351. try block Inside try block we write the block of statements which causes executions block always contains problematic at run time in other words try statements. Important points about try block • If any exception occurs in try block then CPU controls comes out to the try block and executes appropriate catch block. • After executing appropriate catch block, even through we use run time statement, CPU control never goes to try block to execute the rest of the statements. • Each and every try block must be immediately followed by catch block that is no intermediate statements are allowed between try and catch block. EXCEPTION HANDLING IN JAVA 351 SCION RESEARCH AND DEVELOPMENT
  • 352. Syntax Try { ..... } /* Here no other statements are allowed between try and catch block */ catch() { .... } • Each and every try block must contains at least one catch block. But it is highly recommended to write multiple catch blocks for generating multiple user friendly error messages. • One try block can contains another try block that is nested or inner try 352 block can be possible. SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 353. Syntax Try { ....... Try { ....... } } catch block • Inside catch block we write the block of statements which will generates user friendly error messages. • catch block important points • catch block will execute exception occurs in try block. • You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong. You can see below example. • At a time only one catch block will execute out of multiple catch blocks. • in catch block you declare an object of sub class and it will be internally 353 referenced by JVM. SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 354. Multiple catch block You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong. You can see below example. Example import java.util.*; class ExceptionDemo { public static void main(String[] args) { int a, b, ans=0; Scanner s=new Scanner(System.in); System.out.println("Enter any two numbers: "); try { a=s.nextInt(); 354 b=s.nextInt(); SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 355. ans=a/b; System.out.println("Result: "+ans); } catch(ArithmeticException ae) { System.out.println("Denominator not be zero"); } catch(Exception e) { System.out.println("Enter valid number"); } } } Output Enter any two number: 5 0 355 Denominator not be zero SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 356. 356 SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA finally Block in Exception Handling Inside finally block we write the block of statements which will relinquish (released or close or terminate) the resource (file or database) where data store permanently. finally block important points • Finally block will execute compulsory • Writing finally block is optional. • You can write finally block for the entire java program • In some of the circumstances one can also write try and catch block in finally block.
  • 357. 357 SCION RESEARCH AND DEVELOPMENT Example class ExceptionDemo { public static void main(String[] args) { int a=10, ans=0; Try { ans=a/0; } catch (Exception e) { System.out.println("Denominator not be zero"); } Finally { System.out.println("I am from finally block"); } } } Output Denominator not be zero I am from finally block EXCEPTION HANDLING IN JAVA
  • 358. 358 SCION RESEARCH AND DEVELOPMENT • ClassNotFoundException • IOException • InterruptedException Un-Checked Exception Classes • ArithmeticException • ArrayIndexOutOfBoundsException • StringIndexOutOfBoundsException • NumberFormateException • NullPointerException • NoSuchMethodException • NoSuchFieldException EXCEPTION HANDLING IN JAVA Exception Classes in Java Exception are mainly classified into two type checked exception and un- checked exception. Checked Exception Classes • FileNotFoundException
  • 359. EXCEPTION HANDLING IN JAVA FileNotFoundException If the given filename is not available in a specific location ( in file handling concept) then FileNotFoundException will be raised. This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors. ClassNotFoundException If the given class name is not existing at the time of compilation or running of program then ClassNotFoundException will be raised. In other words this exception is occured when an application tries to load a class but no definition for the specified class name could be found. 359 SCION RESEARCH AND DEVELOPMENT
  • 360. IOException This is exception is raised whenever problem occurred while writing and reading the data in the file. This exception is occurred due to following reason; • When try to transfer more data but less data are present. • When try to read data which is corrupted. • When try to write on file but file is read only. InterruptedException This exception is raised whenever one thread is disturb the other thread. In other words this exception is thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. 369 SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 361. ArithmeticException This exception is raised because of problem in arithmetic operation like divide by zero. In other words this exception is thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero". Example class ExceptionDemo { public static void main(String[] args) { int a=10, ans=0; Try { ans=a/ 0; } catch (Exceptio n e) { System.o 361 } } } SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 362. ArrayIndexOutOfBoundsException This exception will be raised whenever given index value of an array is out of range. The index is either negative or greater than or equal to the size of the array. Example int a[]=new int[5]; a[10]=100; //ArrayIndexOutOfBoundsException 362 SCION RESEARCH AND DEVELOPMENT
  • 363. StringIndexOutOfBoundsException This exception will be raised whenever given index value of string is out of range. The index is either negative or greater than or equal to the size of the array. Example String s="Hello"; s.charAt(3); s.charAt(10); // Exception raised chatAt() is a predefined method of string class used to get the individual characters based on index value. 363 SCION RESEARCH AND DEVELOPMENT
  • 364. EXCEPTION HANDLING IN JAVA NumberFormateException This exception will be raised whenever you trying to store any input value in the un-authorized datatype. Example: Storing string value into int datatype. Example int a;a="Hello"; Example String s="hello"; int i=Integer.parseInt(s);//NumberFormatException NoSuchMethodException This exception will be raised whenever calling method is not existing in the program. 364 SCION RESEARCH AND DEVELOPMENT
  • 365. Example String s=null; System.out.println(s.length()); 365 SCION RESEARCH AND DEVELOPMENT //NullPointerException StackOverFlowException This exception throw when full the stack because the recursion method are stored in stack area. EXCEPTION HANDLING IN JAVA NullPointerException A NullPointerException is thrown when an application is trying to use or access an object whose reference equals to null.
  • 366. EXCEPTION HANDLING IN JAVA Difference Between Throw and Throws Keyword throw throw is a keyword in java language which is used to throw any user defined exception to the same signature of method in which the exception is raised. Note: throw keyword always should exist within method body. whenever method body contain throw keyword than the call method should be followed by throws keyword. 366 SCION RESEARCH AND DEVELOPMENT
  • 367. Syntax class className { returntype method(...) throws Exception_class { throw(Exception obj) } } 367 SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 368. throws throws is a keyword in java language which is used to throw the exception which is raised in the called method to it's calling method throws keyword always followed by method signature. Example returnType methodName(parameter)throws Exception_class.... { ..... } 368 SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 369. throw throws 1 throw is a keyword used for hitting and generating the exception which are occurring as a part of method body throws is a keyword which gives an indication to the specific method to place the common exception methods as a part of try and catch block for generating user friendly error messages 2 The place of using throw keyword is always as a part of method body. The place of using throws is a keyword is always as a part of method heading 3 When we use throw keyword as a part of method body, it is mandatory to the java programmer to write throws keyword as a part of method heading When we write throws keyword as a part of method heading, it is optional to the java programmer to write throw keyword as a part of method body. 369 SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA Difference between throw and throws
  • 370. EXCEPTION HANDLING IN JAVA Example of throw and throws // save by DivZero.java package pack; public class DivZero { public void division(int a, int b)throws ArithmeticException { if(b==0) { ArithmeticException ae=new ArithmeticException("Does not enter zero for Denominator"); throw ae; } else { int c=a/b; System.out.println("Result: "+c); 370 } } } Compile: javac -d . DivZero.java SCION RESEARCH AND DEVELOPMENT
  • 371. Example // save by ArthException.java import pack.DivZero; import java.util.*; class ArthException { public static void main(String args[]) { System.out.println("Enter any two number: "); Scanner s=new Scanner(System.in); try { int a=s.nextInt(); 371 int b=s.nextInt(); SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 372. DivZero dz=new DivZero(); dz.division(a, b); } catch(Exception e) { System.err.println(e); } } } 372 SCION RESEARCH AND DEVELOPMENT
  • 373. Steps to Compile and Run code First you save throw-example files into you PC in any where, here i will save this file in C:> C:throw-example>javac -d . DivZero.java C: throw-example>javac ArthException.java Note: First compile DivZero.java code then compile ArthException.java3co7d3e. SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA Compile: javac ArthException.java
  • 374. EXCEPTION HANDLING IN JAVA Custom Exception in Java If any exception is design by the user known as user defined or Custom Exception. Custom Exception is created by user. Rules to design user defined Exception • Create a package with valid user defined name. • Create any user defined class. • Make that user defined class as derived class of Exception or RuntimeException class. • Declare parameterized constructor with string variable. • call super class constructor by passing string variable within the derived class constructor. • Save the program with public class name.java 374 SCION RESEARCH AND DEVELOPMENT
  • 375. Example // save by AgeException.java package nage; public class AgeException extends Exception { public AgeException(String s) { super(s); 375 } } SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 376. EXCEPTION HANDLING IN JAVA Compile: javac -d . AgeException.java Example : // save by CheckAge.java package nage; public class CheckAge { public void verify(int age)throws AgeException { if (age>0) { System.err.print("valid age"); } Else { AgeException ae=new AgeException("Invalid age"); throw(ae); } } 376 } SCION RESEARCH AND DEVELOPMENT
  • 377. EXCEPTION HANDLING IN JAVA Compile: javac -d . CheckAge.java Example : // save by VerifyAgeException import nage.AgeException; import nage.CheckAge; import java.util.*; public class VerifyAgeException { public static void main(String args[]) { int a; System.out.println("Enter your age"); Scanner s=new Scanner(System.in); 377 a=s.nextInt(); SCION RESEARCH AND DEVELOPMENT
  • 378. try { CheckAge ca=new CheckAge(); ca.verify(a); } catch(AgeException ae) { Syso("Age should not be -ve"); } catch(Exception e) { System.err.println(e ); } } 378 } SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA
  • 379. Steps to compile and run above program First you save verify-age files into you PC in any where, here i will save this file in C:> C:verify-age>javac -d . AgeException.java C:verify-age>javac -d . CheckAge.java C:verify-age>javac VerifyAgeException.java Note: First compile AgeException.java code then CheckAge.java and at last 379 compile VerifyAgeException.java code. SCION RESEARCH AND DEVELOPMENT EXCEPTION HANDLING IN JAVA Compile: javac VerifyAgeException.java
  • 380. MULTITHREADING IN JAVA Multithreading in java is a process of executing multiple threads simultaneously. The aim of multithreading is to achieve the concurrent execution. Thread Thread is a lightweight components and it is a flow of control. In other words a flow of control is known as thread. State or Life cycle of thread State of a thread are classified into five types they are • New State • Ready State • Running State • Waiting State • Halted or dead State 380 SCION RESEARCH AND DEVELOPMENT
  • 381. New State If any new thread class is created that represent new state of a thread, In new state thread is created and about to enter into main memory. No memory is available if the thread is in new state. Ready State In ready state thread will be entered into main memory, memory space is allocated for the thread and 1st time waiting for the CPU. Running State 381 Whenever the thread is under execution known as running state. SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 382. Halted or dead State If the thread execution is stopped permanently than it comes under dead state, no memory is available for the thread if its comes to dead state. Note: If the thread is in new or dead state no memory is available but sufficient memory is available if that is in ready or running or waiting state. Achieve multithreading in java In java language multithreading can be achieve in two different ways. • Using thread class • Using Runnable interface 382 SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 383. Using thread class • In java language multithreading program can be created by following below rules. • Create any user defined class and make that one as a derived class of thread class. class Class_Name extends Thread{........} • Override run() method of Thread class (It contains the logic of perform any operation) • Create an object for user-defined thread class and attached that object to predefined thread class object. Class_Name obj=new Class_Name Thread t=new Thread(obj); • Call start() method of thread class to execute run() method. 383 • Save the program with filename.java SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 384. MULTITHREADING IN JAVA 384 SCION RESEARCH AND DEVELOPMENT
  • 385. MULTITHREADING IN JAVA Example of multithreading using Thread class Thread based program for displaying 1 to 10 numbers after each and every second. // Threaddemo2.java class Th1 extends Thread { public void run() { try { for(int i=1;i< =10;i++) { System.out.println("value of i="+i); 385 Thread.sleep(1000); SCION RESEARCH AND DEVELOPMENT
  • 386. } } catch(InterruptedException ie) { System.err.println("Problem in thread execution"); } } } class Threaddemo2 { public static void main(String args[]) { Th1 t1=new Th1(); 386 System.out.println("Execution status of t1 before start="+t1.isAlive()); SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 387. t1.start(); System.out.println("Execution status of t1 before start="+t1.isAlive()); try { Thread.sleep(5000); } catch(InterruptedException ie) { System.out.println("Problem in thread execution"); } System.out.println("Execution status of t1 during execution="+t1.isAlive()); Try { 387 Thread.sleep(5001); SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 388. } catch(InterruptedException ie) { System.out.println("problem in thread execution"); } System.out.println("Execution status of t1 after completation="+t1.isAlive()); } } 388 SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 389. Output Execution status of t1 before start=false //new state 10 Execution status of t1 after completion=false //halted state 389 SCION RESEARCH AND DEVELOPMENT //ready state Execution status of t1 after start=true 1 2 3 4 5 //running state 6 Execution status of t1 during execution=true 7 8 9 MULTITHREADING IN JAVA
  • 390. MULTITHREADING IN JAVA Thread class properties Thread class contains constant data members, constructors, predefined methods. Constant data members • MAX-PRIORITY • MIN-PRIORITY • NORM-PRIORITY MAX-PRIORITY Which represent the minimum priority that a thread can have whose values is 10. Syntax: public static final int MAX-PRIORITY=10 MIN-PRIORITY Which represents the minimum priority that a thread can have. 390 Syntax: public static final int MIN-PRIORITY=0 SCION RESEARCH AND DEVELOPMENT
  • 391. NORM-PRIORITY Which represent the default priority that is assigned to a thread. Syntax: public static final int NORM-PRIORITY=5 Constructors of Thread class • Thread() • Thread(String name) • Thread(object) • Thread(object, String name) Thread() Which will be execute to set the predefined name for newly created thread, these names are generally in the form of thread -0, thread -1, .... Syntax to call constructor: Syntax 391 Thread t=new Thread(); SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 392. Thread(String name) Which can be used to provide user defined name for newly created thread. Syntax : Thread t=new Thread("newthread"); Thread(object) Which can be used to provide default name for newly created user defined thread. Syntax : UserdefinedThreadclass obj=new UserdefinedThreadclass(); Thread t=new Thread("obj"); Thread(object, String name) Which will be used to provide user defined name for the newly created user defined thread. Syntax : UserdefinedThreadclass obj=new UserdefinedThreadclass(); Thread t=new Thread(object, "secondthread"); 392 SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 393. • getPriority() • setPriority() • getName() • setName() • isDeamon() • run() • start() • sleep() 393 SCION RESEARCH AND DEVELOPMENT • suspend() • resume() • stop() • isAlive() • currentThread() • join() • getState() • yield() MULTITHREADING IN JAVA Methods of Thread class
  • 394. getPriority() This method is used to get the current priority of thread. Thread t=new Thread(); int x=t.getPriority(); System.out.println(x); setPriority() This method is used to set the current priority of thread. Thread t=new Thread(); t.setPriority(any priority number between o to 10) or t.setPriority(Thread.MAX-PRIORITY) 394 SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 395. getName() This method is used to get the current executing thread name. Thread t=new Thread(); String s=t.getName(); System.out.println(s); setName() This method is used to set the userdefined name for the thread. Thread t=new Thread(); t.setName("mythread"); isDeamon() Which returns true if the current thread is background thread otherwise return false. 395 boolean b=t.isDeamon(); SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 396. run() Which contains the main business logic that can be executed by multiple threads simultaneously in every user defined thread class run method should be overridden. public Class_Name extends Thread { public void run() { ..... } } start() Used to convert ready state thread to running state. Thread t=new Thread(); 396 t.start(); SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 397. sleep() Used to change running state thread to ready state based on time period it is a static method should be called with class reference. public static final sleep(long milisecond)throws InterruptedException { try { Thread.sleep(3000) ; } catch(InterruptedEx ception ie) { ........ } } Once the given time period is completed thread state 397 from waiting to running state. SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 398. suspend() Used to convert running state thread to waiting state, which will never come back to running state automatically. Thread t=new Thread(); t.suspend(); resume() Used to change the suspended thread state(waiting state) to ready state. Thread t=new Thread(); t.resume(); Note: Without using suspend() method resume() method can not be use. 398 SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 399. MULTITHREADING IN JAVA What is the difference between sleep() and suspend() • Sleep() can be used to convert running state to waiting state and automatically thread convert from waiting state to running state once the given time period is completed. • Where as suspend() can be used to convert running state thread to waiting state but it will never return back to running state automatically. stop() This method is used to convert running state thread to dead state. Thread t=new Thread(); t.stop(); isAlive() Which is return true if the thread is in ready or running or waiting state and return false if the thread is in new or dead state. 399 Thread t=new Thread(); t.isAlive(); SCION RESEARCH AND DEVELOPMENT
  • 400. currentThread() Used to get the current thread detail like thread name thread group name and priority Thread t=new Thread(); t.currentThread(); Note: The default thread name is thread-0, (if it is a main thread default name is main) The default thread group name is main Default thread priority is "5" is normal priority. join() Which can be used to combined more than one thread into a single group 400 signature is public final void join()throws InterruptedException SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 401. try { t.join(); t2.join(); ..... } getState() This method is used to get the current state of thread. Thread t=new Thread(); t.getState(); yield() Which will keep the currently executing thread into temporarily pass and allows other threads to execute 401 SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 402. MULTITHREADING IN JAVA Using Runnable Interface • Runnable is one of the predefined interface in java.lang package, which is containing only one method and whose prototype is " Public abstract void run " • The run() method of thread class defined with null body and run() method of Runnable interface belongs to abstract. Industry is highly recommended to override abstract run() method of Runnable interface but not recommended to override null body run() method of thread class. • In some of the circumstance if one derived class is extending some type of predefined class along with thread class which is not possible because java programming never supports multiple inheritance. To avoid this multiple inheritance problem, rather than extending thread class we 402 implement Runnable interface. SCION RESEARCH AND DEVELOPMENT
  • 403. 403 class Class_Name implement Runnable { public void run() { ........ } } Class_Name obj=new Class_name(); Thread t=new Thread(); MULTITHREADING IN JAVA Rules to create the thread using Runnable interface • Create any user defined class and implements runnable interface within that • Override run() method within the user defined class. • call start() method to execute run() method of thread class • Save the program with classname.java Note: While implementing runnable interface it is very mandatory to extending Thread class. t.start(); SCION RESEARCH AND DEVELOPMENT attach user defined thread class object reference to predefined thread class object reference. It is optional while creating thread by
  • 404. MULTITHREADING IN JAVA Thread Synchronization Whenever multiple threads are trying to use same resource than they may be chance to of getting wrong output, to overcome this problem thread synchronization can be used. Definition: Allowing only one thread at a time to utilized the same resource out of multiple threads is known as thread synchronization or thread safe. In java language thread synchronization can be achieve in two different ways. • Synchronized block • Synchronized method Note: synchronization is a keyword (access modifier in java) 404 SCION RESEARCH AND DEVELOPMENT
  • 405. Synchronized block Whenever we want to execute one or more than one statement by a single thread at a time(not allowing other thread until thread one execution is completed) than those statement should be placed in side synchronized block. class Class_Name implement Runnable or extends Thread { public void run() { synchronized(this) { ....... ....... } } } 405 SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 406. Synchronized method Whenever we want to allow only one thread at a time among multiple thread for execution of a method than that should be declared as synchronized method. class Class_Name implement Runnable or extends Thread { public void run() { synchronized void fun() { ....... ....... } public void run() { fun(); .... 406 } } SCION RESEARCH AND DEVELOPMENT MULTITHREADING IN JAVA
  • 407. MULTITHREADING IN JAVA Interthread Communication The process of execution of exchanging of the data / information between multiple threads is known as Interthread communication or if an output of first thread giving as an input to second thread the output of second thread giving as an input to third thread then the communication between first second and third thread known as Interthread communication. In order to develop Interthread communication application we use some of the methods of java.lang.Object class and these methods are known as Interthread communication methods. Interthread communication methods • public final void wait(long msec) • public final void wait() • public final void notify() 407 • public final void notifyAll() SCION RESEARCH AND DEVELOPMENT
  • 408. MULTITHREADING IN JAVA public final void wait(long msec) public final void wait (long msec) is used for making the thread to wait by specifying the waiting time in terms of milliseconds. Once the waiting time is completed, automatically the thread will be interred into ready state from waiting state. This methods is not recommended to used to make next thread to wait on the basis of time because java programmer may not be able to decide or determine the CPU burst time of current thread and CPU burst time is decided by OS but not by the programmer. public final void wait() public final void wait() is used for making the thread to wait without specifying any waiting time this method is recommended to use to make the next thread to wait until current thread complete its execution. 408 SCION RESEARCH AND DEVELOPMENT
  • 409. MULTITHREADING IN JAVA public final void notify() public final void notify() is used for transferring one thread at a time from waiting state to ready state. public final void notifyAll() public final void notifyAll() is used for transferring all the threads at a time from waiting state to ready state. Note: public final void wait (long msec) and public final void wait() throws a predefined Exception called java.lang.InterruptedException. 409 SCION RESEARCH AND DEVELOPMENT
  • 410. STRING HANDLING IN JAVA String Handling in Java • The basic aim of String Handling concept is storing the string data in the main memory (RAM), manipulating the data of the String, retrieving the part of the String etc. • String Handling provides a lot of concepts that can be performed on a string such as concatenation of string, comparison of string, find sub string etc. Character It is an identifier enclosed within single quotes (' '). Example: 'A', '$', 'p' String: String is a sequence of characters enclosed within double quotes (" ") is known as String. 410 Example: "Java Programming". SCION RESEARCH AND DEVELOPMENT
  • 411. STRING HANDLING IN JAVA In java programming to store the character data we have a fundamental datatype called char. Similarly to store the string data and to perform various operation on String data, we have three predefined classes they are: • String • StringBuffer • StringBuilder String class • It is a predefined class in java.lang package can be used to handle the String. String class is immutable that means whose content can not be changed at the time of execution of program. • String class object is immutable that means when we create an object of String class it never changes in the existing object. 411 SCION RESEARCH AND DEVELOPMENT
  • 412. Example class StringHandling { public static void main(String arg[]) { String s=new String("java"); s.concat("software"); System.out.println(s); } } Output java Explanation: Here we can not change the object of String class so output is 412 only java not java software. SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 413. STRING HANDLING IN JAVA Methods of String class length() length(): This method is used to get the number of character of any string. Example class StringHandling { public static void main(String arg[]) { int l; String s=new String("Java"); l=s.length(); System.out.println("Length: "+l); } } Output 413 Length: 4 SCION RESEARCH AND DEVELOPMENT
  • 414. charAt(index) charAt(): This method is used to get the character at a given index value. Example class StringHandling { public static void main(String arg[]) { char c; String s=new String("Java"); c=s.charAt(2); System.out.println("Character: "+c); } } Output 414 Character: v SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 415. toUpperCase() toUpperCase(): This method is use to convert lower case string into upper case. Example class StringHandling { public static void main(String arg[]) { String s="Java"; System.out.println("String: "+s.toUpperCase()); } } Output 415 String: JAVA SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 416. toLowerCase() toLowerCase(): This method is used to convert lower case string into upper case. Example class StringHandling { public static void main(String arg[]) { String s="JAVA"; System.out.println("String: "+s.toLowerCase()); } } Output 416 String: java SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 417. concat() concat(): This method is used to combined two string. Example class StringHandling { public static void main(String arg[]) { String s1="Hitesh"; String s2="Raddy"; System.out.println( "Combined String: "+s1.concat(s2)); } } Output 417 Combined String: HiteshRaddy SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 418. equals() equals(): This method is used to compare two strings, It return true if strings are same otherwise return false. It is case sensitive method. Example class StringHandling { public static void main(String arg[]) { String s1="Hitesh"; String s2="Raddy"; String s3="Hitesh"; System.out.println("Compare String: "+s1.equals(s2)); System.out.println("Compare String: "+s1.equals(s3)); } } Output Compare String: false 418 Compare String: true SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 419. equalsIgnoreCase() equalsIgnoreCase(): This method is case insensitive method, It return true if the contents of both strings are same otherwise false. Example class StringHandling { public static void main(String arg[]) { String s1="Hitesh"; String s2="HITESH"; String s3="Raddy"; System.out.println("Compare String: "+s1.equalsIgnoreCase(s2)); System.out.println("Compare String: "+s1.equalsIgnoreCase(s3)); } } Output Compare String: true 419 Compare String: false SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 420. compareTo() compareTo(): This method is used to compare two strings by taking unicode values, It return 0 if the string are same otherwise return +ve or - ve integer values. Example class StringHandling { public static void main(String arg[]) { String s1="Hitesh"; System.out.println("Strings are same"); } Else { System.out.println("Strings are not same"); } } } SCION RESEARCH AND DEVELOPMENT 420 String s2="Raddy"; int i; i=s1.compareTo(s2); if(i==0) { Output Strings are not same STRING HANDLING IN JAVA
  • 421. String s1="Hitesh"; String s2="HITESH"; int i; i=s1.compareToIgnoreCase(s2); if(i==0) { } Else { System.out.println("Strings are not same"); } } } SCION RESEARCH AND DEVELOPMENT 421 System.out.println("Strings are same"); Output Strings are same STRING HANDLING IN JAVA compareToIgnoreCase() compareToIgnoreCase(): This method is case insensitive method, which is used to compare two strings similar to compareTo(). Example class StringHandling { public static void main(String arg[]) {
  • 422. startsWith() startsWith(): This method return true if string is start with given another string, otherwise it returns false. Example class StringHandling { public static void main(String arg[]) { String s="Java is programming language"; System.out.println(s.startsWith("Java")); } } Output 422 true SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 423. 423 SCION RESEARCH AND DEVELOPMENT true STRING HANDLING IN JAVA endsWith() endsWith(): This method return true if string is end with given another string, otherwise it returns false. Example class StringHandling { public static void main(String arg[]) { String s="Java is programming language"; System.out.println(s.endsWith("language")); } } Output
  • 424. subString() subString(): This method is used to get the part of given string. Example class StringHandling { public static void main(String arg[]) { String s="Java is programming language"; System.out.println(s.substring(8)); // 8 is starting index } } Output programming language 424 SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 425. Example class StringHandling { public static void main(String arg[]) { String s="Java is programming language"; System.out.println(s.substring(8, 12)); } } Output prog 425 SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 426. indexOf() indexOf(): This method is used find the index value of given string. It always gives starting index value of first occurrence of string. Example class StringHandling { public static void main(String arg[]) { String s="Java is programming language"; System.out.println(s.indexOf("programming")); } } Output 8 SCION RESEARCH AND DEVELOPMENT 426 STRING HANDLING IN JAVA
  • 427. lastIndexOf() lastIndexOf(): This method used to return the starting index value of last occurence of the given string. Example class StringHandling { public static void main(String arg[]) { String s1="Java is programming language"; String s2="Java is good programming language"; System.out.println(s1.lastIndexOf("programming")); System.out.println(s2.lastIndexOf("programming")); } } Output 8 13 SCION RESEARCH AND DEVELOPMENT 427 STRING HANDLING IN JAVA
  • 428. trim() trim(): This method remove space which are available before starting of string and after ending of string. Example class StringHandling { public static void main(String arg[]) { String s=" Java is programming language "; System.out.println(s.trim()); } } Output 428 Java is programming language SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 429. split() split(): This method is used to divide the given string into number of parts based on delimiter (special symbols like @ space , ). Example class StringHandling { public static void main(String arg[]) { String s="[email protected]"; String[] s1=s.split("@"); // divide string based on @ for(String c:s1) // foreach loop { System.out.println(c); } } } Output contact 429 @tutorial4us.com SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 430. replace() replace(): This method is used to return a duplicate string by replacing old character with new character. Note: In this method data of original string will never be modify. Example class StringHandling { public static void main(String arg[]) { String s1="java"; String s2=s1.replace('j', 'k'); System.out.println(s2); } } Output 430 kava SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 431. STRING HANDLING IN JAVA StringBuffer Class in Java • It is a predefined class in java.lang package can be used to handle the String, whose object is mutable that means content can be modify. • StringBuffer class is working with thread safe mechanism that means multiple thread are not allowed simultaneously to perform operation of StringBuffer. • StringBuffer class object is mutable that means when we create an object of StringBulder class it can be change. Explanation: Here we can changes in the existing object of StringBuffer class so output is javasoftware. 431 SCION RESEARCH AND DEVELOPMENT
  • 432. STRING HANDLING IN JAVA Example StringBuffer class StringHandling { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("java"); sb.append("software"); System.out.println(sb); } } Output javasoftware 432 SCION RESEARCH AND DEVELOPMENT
  • 433. String StringBuffer The data which enclosed within double quote (" ") is by default treated as String class. The data which enclosed within double quote (" ") is not by default treated as StringBuffer class String class object is immutable StringBuffer class object is mutable When we create an object of String class by default no additional character memory space is created. When we create an object of StringBuffer class by default we get 16 additional character memory space. 433 • We can not override the method of String and StringBuffer. SCION RESEARCH AND DEVELOPMENT Similarities Between String and StringBuffer • Both of them are belongs to public final. so that they never participates in inheritance that is is-A relationship is not possible but they can always participates in As-A and Uses-A relationship. STRING HANDLING IN JAVA Difference Between String and StringBuffer
  • 434. STRING HANDLING IN JAVA Methods of StringBuffer class reverse() reverse(): This method is used to reverse the given string and also the new value is replaced by the old string. Example class StringHandling { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("java code"); System.out.println(sb.reverse()); } } Output 434 edoc avaj SCION RESEARCH AND DEVELOPMENT
  • 435. insert() insert(): This method is used to insert either string or character or integer or real constant or boolean value at a specific index value of given string. Example class StringHandling { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("this is my java code"); System.out.println(sb.insert(11, "first ")); } } Output 435 this is my first java code SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 436. append() append(): This method is used to add the new string at the end of original string. Example class StringHandling { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("java is easy"); System.out.println(sb.append(" to learn")); } } Output 436 java is easy to learn SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 437. replace() replace() This method is used to replace any old string with new string based on index value. Example class StringHandling { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("This is my code"); System.out.println(sb.replace(8, 10, "java")); } } Output This is java code Explanation: In above example java string is replaced with old string (my) 437 which is available between 8 to 10 index value. SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 438. deleteCharAt() deleteCharAt(): This method is used to delete a character at given index value. Example class StringHandling { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("java"); System.out.println(sb.deleteCharAt(3)); } } Output 438 jav SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 439. delete() delete(): This method is used to delete string form given string based on index value. Example class StringHandling { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("java is easy to learn"); StringBuffer s; s=sb.delete(8, 13); System.out.println(sb); } } Output java is to learn Explanation: In above example string will be deleted which is existing 439 between 8 and 13 index value. SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 440. toString() toString(): This method is used to convert mutable string value into immutable string. Example class StringHandling { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("java"); String s=sb.toString(); System.out.println(s); s.concat("code"); } } Output 440 java SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 441. • By equals() method • By == operator • By compreTo() method 441 SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA String Compare in Java There are three way to compare string object in java:
  • 442. STRING HANDLING IN JAVA equals() Method in Java equals() method always used to comparing contents of both source and destination String. It return true if both string are same in meaning and case otherwise it returns false. It is case sensitive method. 442 SCION RESEARCH AND DEVELOPMENT
  • 443. Example class StringHandling { public static void main(String arg[]) { String s1="Hitesh"; String s2="Raddy"; String s3="Hitesh"; System.out.println("Compare String: "+s1.equals(s2)); System.out.println("Compare String: "+s1.equals(s3)); } } Output Compare String: false Compare String: true 443 SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 444. STRING HANDLING IN JAVA == or Double Equals to Operator in Java == Operator is always used for comparing references of both source and destination objects but not their contents. 444 SCION RESEARCH AND DEVELOPMENT
  • 445. Example class StringHandling { public static void main(String arg[]) { String s1=new String("java"); String s2=new String("java"); if(s1==s2) { System.out.println("Strings are same"); } else { System.out.println("Strings are not same"); } } } Output 445 Strings are not same SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 446. STRING HANDLING IN JAVA compareTo() Method in Java comapreTo() method can be used to compare two string by taking Unicode values. It returns 0 if the string are same otherwise returns either +ve or - ve integer. Example class StringHandling { public static void main(String arg[]) { String s1="Hitesh"; String s2="Raddy"; int i; i=s1.compareTo(s2); 446 if(i==0) SCION RESEARCH AND DEVELOPMENT
  • 447. { System.out.println("Strings are same"); } else { System.out.println("Strings are not same"); } } } Output Strings are not same 447 SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 448. STRING HANDLING IN JAVA Difference between equals() method and == operator • equals() method always used to comparing contents of both source and destination String. • == Operator is always used for comparing references of both source and destination objects but not their contents. String Concatenation There are two way to concat string object in java: • By + (string concatenation) operator • By concat() method 448 SCION RESEARCH AND DEVELOPMENT
  • 449. By + operator Using Java string concatenation operator (+) you can combined two or more strings. Example class StringHandling { public static void main(String arg[]) { String s= "Java" + "Code"; System.out.println(s); } } Output JavaCode SCION RESEARCH AND DEVELOPMENT 449 STRING HANDLING IN JAVA
  • 450. By concat() method concat() method is used to combined two strings. Example class StringHandling { public static void main(String arg[]) { String s1="Java"; String s2="Code"; String s3=s1.concat(s2); System.out.println(s3); } } Output JavaCode SCION RESEARCH AND DEVELOPMENT 459 STRING HANDLING IN JAVA
  • 451. StringBuilder • It is a predefined class in java.lang package can be used to handle the String. StringBuilder class is almost similar to to StringBuffer class. It is also a mutable object. • The main difference StringBuffer and StringBuilder class is StringBuffer is thread safe that means only one threads allowed at a time to work on the String where as StringBuilder is not thread safe that means multiple threads can work on same String value. Difference between StringBuffer and StringBuilder All the things between StringBuffer and StringBuilder are same only difference is StringBuffer is synchronized and StringBuilder is not synchronized. synchronized means one thread is allow at a time so it thread safe. Not synchronized means multiple threads are allow at a time so it not 451 thread safe. SCION RESEARCH AND DEVELOPMENT STRING HANDLING IN JAVA
  • 452. StringBuffer StringBuilder 1 It is thread safe. It is not thread safe. 2 Its methods are synchronized and provide thread safety. Its methods are not synchronized and unable to provide thread safety. 3 Relatively performance is low because thread need to wait until previous process is complete. Relatively performance is high because no need to wait any thread it allows multiple thread at a time. 4 Introduced in 1.0 version. Introduced in 1.5 version. 452 required then we use StringBuilder SCION RESEARCH AND DEVELOPMENT When we use String, StringBuffer and StringBuilder • If the content is fixed and would not change frequently then we use String. • If content is not fixed and keep on changing but thread safety is required then we use StringBuffer • If content is not fixed and keep on changing and thread safety is not STRING HANDLING IN JAVA
  • 453. Suppose that we have any string like "Features of Java_Language" when we use stringTokenizer this string is split into tokens whenever spaces and STRINGTOKENIZER IN JAVA StringTokenizer in Java It is a pre defined class in java.util package can be used to split the given string into tokens (parts) based on delimiters (any special symbols or spaces). special symbols present. After split string are : 453 SCION RESEARCH AND DEVELOPMENT
  • 454. Example • Features • of • Java • Language Methods of StringTokenizer • hasMoreTokens() • nextToken() hasMoreTokens() It is predefined method of StringTokenizer class used to check whether given StringTokenizer having any elements or not. nextToken() Which can be used to get the element from the StringTokenizer. 454 SCION RESEARCH AND DEVELOPMENT STRINGTOKENIZER IN JAVA
  • 455. System.out.println("The tokens are: "); while(st.hasMoreTokens()) { String one=st.nextToken(); System.out.println(one); } } } man 455 SCION RESEARCH AND DEVELOPMENT Output The tokens are: He is a ge ntl e STRINGTOKENIZER IN JAVA Example of StringTokenizer: import java.util.*; class Stringtokenizerdemo { public static void main(String args[]) { String str="He is a gentle man"; StringTokenizer st=new StringTokenizer(str," ");
  • 456. Data Conversion In java programming we have six data conversion technique they are:. 1 Converting numeric string type data into numerical / fundamental type values In order to convert numerical string into numerical or fundamental values we use the following generalized predefined method which is present in wrapper classes. Example String s1="100"; int x=Integer.parseInt(s1); Example String s2="100.75f"; Float y=Float.parseFloat(s2); DATA CONVERSION IN JAVA 456 Here xxx represent any fundamental data type. SCION RESEARCH AND DEVELOPMENT
  • 457. Here XXX represent any fundamental data type values Example int a=10; DATA CONVERSION IN JAVA 2 Converting numeric / fundamental type values into string type values In order to convert numeric / fundamental type values into string values, we use the following predefined static overloaded method. 457 SCION RESEARCH AND DEVELOPMENT
  • 458. DATA CONVERSION IN JAVA 3 Converting fundamental type values into object type values: In order to convert the fundamental data into equivalent wrapper class object type data we use the following generalized predefined parameterized constructor by taking fundamental data type as a parameter. 458 SCION RESEARCH AND DEVELOPMENT
  • 459. DATA CONVERSION IN JAVA in JDK 1.4 converting fundamental data type values into wrapper class object is known as boxing. In the case of JDK 1.5 and in higher version it is optional to the java programmer to convert fundamental data type value into equivalent wrapper class object. That is implicitly taken care by JVM and it is known as auto boxing. Definition of auto boxing The process of implicitly converting fundamental type value into equivalent wrapper class object is known as auto boxing. 459 SCION RESEARCH AND DEVELOPMENT
  • 460. DATA CONVERSION IN JAVA 4 Converting object type value into fundamental type value: In order to convert wrapper class object data into fundamental type data, we use the following predefined instance method present in each and every wrapper class. 460 SCION RESEARCH AND DEVELOPMENT
  • 461. DATA CONVERSION IN JAVA In case of JDK 1.5 and in higher version it is optional to the java programmer to convert object data into fundamental type data and this process is known as auto un-boxing and its takes care by JVM. Definition of auto un-boxing In process of implicitly conversion objects type data into fundamental type data is known as auto un-boxing. 461 SCION RESEARCH AND DEVELOPMENT
  • 462. 5 Converting String type data into object type data In order to convert String type numeric data into equivalent wrapper class object, we use the following predefined parameterized constructor by each and every wrapper class except character class. DATA CONVERSION IN JAVA 462 SCION RESEARCH AND DEVELOPMENT
  • 463. To convert wrapper class object type data into string type data we use the following generalized predefined instant method which is present each and every wrapper class. 463 SCION RESEARCH AND DEVELOPMENT DATA CONVERSION IN JAVA 6 Converting wrapper class object type data into String type data
  • 464. DATA CONVERSION IN JAVA 464 SCION RESEARCH AND DEVELOPMENT
  • 465. Example int a=10; • String is=String.valueOf(a); • Integer io=new Integer(is); • int x=io.intValue(); • Integer io=new Integer(n); • String so=io.toString(); • int x=Integer.parseInt(so); 465 SCION RESEARCH AND DEVELOPMENT DATA CONVERSION IN JAVA
  • 466. BOXING AND UNBOXING IN JAVA Boxing and Unboxing in Java Definition of Auto Boxing The process of implicitly converting fundamental type values into the equivalent wrapper class object is known as auto boxing. Converting fundamental type values into object type values: In order to convert the fundamental data into equivalent wrapper class object type data we use the following generalized predefined parameterized constructor by taking fundamental data type as a parameter. ND DEVELOPMENT 466 SCION RESEARCH A
  • 467. BOXING AND UNBOXING IN JAVA In JDK 1.4 converting fundamental data type values into wrapper class object is known as boxing. In the case of JDK 1.5 and in higher version it is optional to the Java programmer to convert the fundamental data type value into the equivalent wrapper class object. That is implicitly taken care by JVM and it is known as auto boxing. Definition of auto Unboxing. In process of implicitly conversion objects type data into fundamental type data is known as auto un-boxing. Converting object type value into fundamental type value: In order to convert wrapper class object data into fundamental type data, we use the following predefined instance method present in each and every wrapper class. 467 SCION RESEARCH AND DEVELOPMENT
  • 468. In case of JDK 1.5 and in higher version it is optional to the Java programmer to convert object data into fundamental type data and this process is known as auto un-boxing and it takes care by the JVM. 468 SCION RESEARCH AND DEVELOPMENT BOXING AND UNBOXING IN JAVA
  • 469. JAVA SCANNER CLASS IN JAVA Java Scanner Class in Java Scanner is one of the predefined class which is used for reading the data dynamically from the keyboard. Import Scanner class Import Scanner Class in Java java.util.Scanner Constructor of Scanner Class Scanner(InputStream) This constructor create an object of Scanner class by talking an object of InputStream class. An object of InputStream class is called in which is created as a static data member in the System class. Syntax of Scanner Class in Java Scanner sc=new Scanner(System.in); 469 Here the object 'in' is use the control of keyboard SCION RESEARCH AND DEVELOPMENT
  • 470. JAVA SCANNER CLASS IN JAVA 470 SCION RESEARCH AND DEVELOPMENT
  • 471. JAVA SCANNER CLASS IN JAVA 471 SCION RESEARCH AND DEVELOPMENT
  • 472. Method Description 1 public byte nextByte() Used for read byte value 2 public short nextShort() Used for read short value 3 public int nextInt() Used for read integer value 4 public long nextLong() Used for read numeric value 5 public float nextLong() Used for read numeric value 6 public double nextDouble() Used for read double value 7 public char nextChar() Used for read character 8 public boolean nextBoolean() Used for read boolean value 9 public String nextLine() Used for reading any kind of data in the form of String data. 472 the form of String data. SCION RESEARCH AND DEVELOPMENT Method 1 to 8 are used for reading fundamental values from the keyboard. Method 9 (public String nextLine() ) is used for reading any kind of data in JAVA SCANNER CLASS IN JAVA Instance methods of Scanner Class
  • 473. JAVA SCANNER CLASS IN JAVA For Remember all above methods From method 1 to 8 combindly we represent as public xxx nextxxx(). Here xxx represents any fundamental data type. These methods are used for reading the fundamental data from keyboard. Accept two values dynamically from the keyboard and compute sum. Example of Scanner Class in Java import java.util.Scanner public class ScannerDemo { public static void main(String args[]) { Scanner s=new Scanner(System.in); System.out.println("Enter first no= "); 473 int num1=s.nextInt(); SCION RESEARCH AND DEVELOPMENT
  • 474. JAVA SCANNER CLASS IN JAVA System.out.println("Enter second no= "); int num2=s.nextInt(); System.out.println("Sum of no is= "+ (num1+num2)); } } 474 SCION RESEARCH AND DEVELOPMENT Output Enter first no=4 Enter second no=5 Sum of no is=9
  • 475. SCION RESEARCH AND DEVELOPMENT 475 System.out.println("Sum= "+res); } } Output Enter first number: 5 Enter second number: 6 Sum= 11 JAVA SCANNER CLASS IN JAVA Program which is accept two number as a string and compute their sum. Example import java.util.Scanner; class Dataread { public static void main(String[] args) { Scanner s=new Scanner(System.in); System.out.println("Enter first number: "); String s1=s.nextLine(); System.out.println("Enter second number: "); String s2=s.nextLine(); int res=Integer.parseInt(s1) + Integer.parseInt(s2);