SlideShare a Scribd company logo
1 of 95
UNIT I
chapter 2 : Java Evolution
1. Java History
2. Java Features
3. How Java differs from C and C++
4. Java and Internet
5. Java and World Wide Web
6. Web Browsers
1. Java History
• Java is a general-purpose, OOP language developed by Sun Microsystems of USA in 1991.
• Originally called Oak by James Gosling
• Java was originally designed for the development of Software for Consumer electronic devices like TVs, VCRs…
Goal : Make the language simple, portable and highly reliable.
• Java team included the existing languages like C & C++.
• But it had limitations in terms of both reliability and portability.
• They modeled their new language Java on C & C++
• But removed number of features of C & C++
• And made Java a really simple, reliable, portable and powerful language.
2. Java Features
• The inventors of Java wanted to design a language which could offer solutions to some of the problems encounte
modern programming
•The Java not only reliable, portable and distributed but also simple, compact and interactive.
(Table diagram)
b) Platform-Independent and Portable
•The most significant features of Java is its portability.
•Java programs can be easily moved from one computer system to another, anywhere and anytime.
•Changes and upgrades in Oss, Processors and System resources will not force any changes in Java programs.
•This is the reason java has become a popular language for programming on Internet which interconnects different k
systems worldwide.
•We can download a Java applet from a remote computer onto our local system via internet and execute it locally.
b) Platform-Independent and Portable
• The most significant features of Java is its portability.
• Java programs can be easily moved from one computer system to another, anywhere and anytime.
• Changes and upgrades in Oss, Processors and System resources will not force any changes in Java programs
• This is the reason java has become a popular language for programming on Internet which interconnects diff
kinds of systems worldwide.
• We can download a Java applet from a remote computer onto our local system via internet and execute it loc
• Java ensures portability in 2 ways
• First, Java compiler generates bytecode instructions that can be implemented on any machine.
• Secondly, the size of the primitive data types are machine-independent.
Java ensures portability in 2 ways
• First, Java compiler generates bytecode instructions that can be implemented on any machine.
• Secondly, the size of the primitive data types are machine-independent.
c) Object-Oriented
• Java is a true OO language.
• Almost everything in Java is an Object.
• All program code and data reside within objects and classes.
• Java comes with an extensive set of lasses, arranged in packages, that can use in our programs by inheritance.
• The Object model in Java is simple and easy to extend.
d) Robust and Secure
Robust
• Java is a robust language.
• It provides many safeguards to ensure reliable code.
• It has strict compile time and run time checking for data types.
• It is designed as a garbage-collected language relieving the programmers virtually all memory management
problems.
• Java also incorporates the concept of Exception handling which captures serious and eliminates any risk of
crashing the system.
Security
• It becomes an important issue for a language that is used for programming on Internet.
• Threat of Viruses and abuse of resources are everywhere.
• Java systems not only verify all memory access but also ensure that no viruses are communicated with an ap
• The absence of pointers in Java ensures that programs cannot gain access to memory locations without prope
authorization.
e) Distributed
• Java is designed as a distributed language for creating applications on networks.
• It has the ability to share both data & programs
• Java applications can open & access remote a bjects on Internet as easily as they can do in a local system.
• It enables multiple programmers at multiple remote locations to collaborate and work together on a single projec
f) Simple, Small and Familiar
Simple & Small
• Java is a small and simple language.
• Many features of C & C++ that are earlier redundant or sources of unreliable code are not part of java.
• Ex: no pointers, processor header files, goto and many others.
• Also eliminates Operator Overloading and multiple inheritance.
Familiar
• To make the language look familiar to the existing programmers.
• It was modeled on C & C++ languages.
• It used many constructs of C & C++
• In fact, Java is a simplified version of C++.
g) Multithreaded and Interactive
• Multithreaded means handling multiple tasks simultaneously.
• Java supports multithreaded programs
• We need not wait for the application to finish one task before beginning another.
• It improves the interactive performance of graphical applications.
• The Java runtime comes with tools that support multiprocess synchronization and construct smoothly running
interactive systems.
h) High Performance
• Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode.
• Java speed is comparable to the native C/C++.
• Java architecture is also designed to reduce overheads during runtime.
• The incorporation of multithreading enhances the overall execution speed of Java programs.
i) Dynamic and Extensible
• Java is a dynamic language.
• Java is capable of dynamically linking in new class libraries, methods, and objects.
• Java can also determine the type of class through a query, making it possible to either dynamically link or abort t
program, depending on the response.
• Java programs support functions written in other languages such as C & C++.
• These functions known as native methods.
• This facility enables the programmers to use the efficient functions available in these languages.
• Native methods are linked dynamically at runtime.
II) Additional Features of J2SE 5.0
a) Ease of Development
• Java 2 Standard Edition (J2SE) 5.0 supports features, such as Generics, enhanced for Loop. Autoboxing or unbox
Typesafe Enums, Varargs, Static import and Annotation.
• It reduce the work of the programmer by shifting the responsibility ofcreating the reusable code to the compiler.
• The resulting source code is free from bugs because the errors made by the compiler are less when compared to t
made by programmers.
• Thus, each of the linguistic features is designed to develop java programs in a easier way.
b) Scalability and Performance
• J2SE 5.0 assures a significant increase in scalability and perfoemance by improving the startup time and reducing
amount of memory used in Java 2 runtime environment.
• For example, the introduction of the class, data sharing in the Hotspot Java Virtual Machine(JVM) improves the
time by loading the core classes from the jar files into a shared archive.
• Memory utilization is reduced by sharing data in the shared archive multiple JVM processes.
c) Monitoring and Manageability
• Java supports a number of APIs, such as JVM Monitoring and Management API, Sun Management Platform
Extension, Logging, Monitoring and Management Interface and Java Management Extension (JMX) to monitor a
mange java applications.
d) Desktop client
• J2SE 5.0 provides enhanced features to meet to meet the requirements and challenges of the java desktop users.
• It provides an improved Swing look and feel called Ocean.
• This feature is mainly used for developing graphics applications that require OpenGL hardware acceleration.
• Miscellaneous Features
J2SE 5.0 supports the following features:
e) Core XML Support
• J2SE 5.0 adds a powerful XML feature to the Java platform.
• Java contains some special packages for interface to instantiate Simple API for XML(SAX) and Document Obje
Model (DOM) parsers to parse an XML document, transform the content of an XML document, and validate an X
document against the schema.
f) Supplementary Character Support
• Java adds the 32-bit supplementary character support as part of the Unicode 4.0 support.
• The supplementary characters are encoded with UTF-16 values to generate a different character called surrogate
point.
g) JDBC RowSet
• To send data in a tabular format between the remote components of a distributed enterprise application.
• Contains CacheRowSet & WebRowSet.
• This object contains a number of rows of data, which are retrieved from the database.
• The data stored in the CacheRowtSet can be directly accessed without connecting to the database or any other da
source.
• The rows of data that are retrieved from the database can be synchronized later.
• The WebRowSet object can operate without being connected to the database or data source and it uses XML form
read and write the rowset.
• III) Enhancement in Java SE 6
• Some of the Key enhancements in Java SE 6 are :
• a) Scripting Language Support
• Java SE 6 integrates various scripting languages such as Java Script and PHP Script into the Java platform.
• It allows scripts to be embedded in Java programs and compiled and executed with the help of appropriate scripti
engine.
• b) XML Processing and Web services
• It allows development of web services and clients that communicate using XML
• c) JDBC 4.0 Support
• For developing database-centric applications
• As a result, programmers can leverage the various features of JDBX 4.0 such as automatic loading of JDBC driv
class, connection management features etc.,
• d) Annotation-based Programming
• It allows programmers to define annotations(meta-tags) for various program elements so that the same can be use
the compiler or other tools to generate ready code whenever necessary.
• e) Dynamic compilation
• The Java compiler API allows dynamic compilation of Java source code form a running Java application.
IV) Enhancement in Java SE 7
Some of the Key enhancements in Java SE 7 are :
a) Language Enhancements
• Java SE 7adds several language features aimed at helping the programmers implement difficult functionality
ease.
• The new language features include strings in switch statement, multiple handling, diamond syntax etc.
b) NIO 2.0
• The new file system API(NIO 2.0) in Java SE 7 makes it a lot easier to work with the systems.
• It contains several enhancements to the standard file operations such as open, read, write etc.
• In addition, it also allows the programmers to create custom file systems.
c) Parallel Programming
• Java SE 7 facilitates Parallel Programming through the use of Fork/join Framework.
• While the conventional multithreaded programming allowed programmers to use a single processor for
multitasking.
d) Dynamic Language Support
• The Java SE 7 supports dynamically typed languages in the JVM.
• The invoked dynamic instruction is used to define customized linkage mechanisms for these languages.
3. How Java Differs from C and C++
• Although Java was modeled after C & C++languages
• It differs from C and C++ in many ways
• Java does not incorporate a number of features available in C & C++.
• For the benefit of C & C++ programmers, we point out here a few major differences between C/C++ & Java
languages.
Java and C
Major Difference :
• Java is an OOP and has mechanism to define classes and objects.
• In an effort to build a simple and safe language, the java team did not include some of the C features in Java
i) Java does not include the C unique statement keywords sizeof and typedef.
ii) Java does not contain the data types strut and union.
iii) Java does not define the type modifiers keyword auto, extern, register, signed and unsigned.
iv) Java does not support an explicit pointer type.
v) Java does not have a preprocessor and therefore we cannot use #define, #include and #ifdef statements.
vi) Java requires that the functions with no arguments must be declared with empty parenthesis and not with the
keyword as done in C.
vii) Java adds new operators such as instance of and >>>.
viii) Java adds labeled break and continue statements.
ix) Java adds many features required for OOP.
Java and C++
Major Difference :
• Java is an true OOP language while C++ is basically C with OO extension.
i) Java does not support operator overloading.
ii) Java does not have template classes as in C++.
iii) Java does not support multiple inheritance of classes. But it is accomplished using new feature called “interf
iv) Java does not support global variables. Every variable and method is declared within a class and form part o
class.
v) Java does not use pointers.
vi) Java has replaced the destructor function with a finalize( ) function.
vii) There are no header files in Java.
Java also add some new features :
• While C++ is a superset of C
• Java is neither a superset nor a subset of C or C++.
• Java may be considered as a first cousin of C++ and a second cousin of C.
Diagram
Overlapping of C, C++ and Java
4. Java and Internet
• Java is strongly associated with the Internet because of the fact that the first application program written in J
was HotJava, a Web browser to run applets on Internet.
• Internet users can use Java to create applet programs and run them locally using a “java-enabled browser” su
HotJava.
• They can also use a Java-enabled browser to download an applet located on a computer anywhere in the inte
and run it on his local computer.
• In fact, java applets have made the Internet a true extension of the storage system of the local computer.
• Internet users can also set up their web sites containing Java applets that could be used by other remote users
Internet.
• The ability of Java applets to hitch a ride on the information superhighway has made Java a unique program
language for the Internet.
• Java is popularly known an Internet language.
Diagram
5. Java and WWW
WWW
• WWW is an open-ended information retrieval system designed to be used in the internet’s distributed
environment.
• Contains web pages that provide both information and controls.
• Unlike a menu-driven system where we are guided through a particular direction using a decision tree structu
• The web system is open-ended and we can navigate to a new document in any direction.
• It is made possible with the help of a language called HTML
• Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents worldwide
Diagram
• Java was meant to be used in distributed environment such as internet.
• Since, both the Web and Java share the same philosophy, java could be easily incorporated into the web syst
• Before java, the WWW limited to the display of still images and texts.
• However, the incorporation of java into web pages has made it capable of supporting animation, graphics, ga
and a wide range of special effects.
• With the support of java , the web has become more interactive and dynamic.
• We can run a java program on someone else’s computer across the internet.
Diagram
Communication Steps
• The user sends a request for an HTML document to the remote computer’s web server. The web server is a
program that accepts a request, and sends the required document.
• The HTML document is returned to the user’s browser. The document contains the APPLET tag, which iden
the applet.
• The corresponding Applet bytecode is transferred to the user’s computer. This bytecode had been previously
created by the java compiler using the java source code file for that applet.
• The java-enabled browser on the user’s computer interprets the bytecodes and provides output.
• The user may have further interaction with the applet but with no further downloading from the provider’s w
server. This is because the bytecode contains all the information necessary to interpret the applet.
6. Web Browsers
• The internet is a vast sea of information in many formats and stored on many computers.
• A large portion of the internet is organized as the WWW which uses hypertext.
• Web Browsers are used to navigate through the information found on the net.
• They allow us to retrieve the information spread across the internet and display using the HTML.
• Examples
i) HotJava
ii) Netscape Navigator
iii) Internet Explorer
i) HotJava
• is the web browser from Sun Microsystems that enables the display of interactive content on the Web using
Java Language.
• Written entirely in Java and demonstrates the capabilities of the java programming language.
• When the java language was first developed and ported to the Internet, no browsers were available that could
java applets.
• Although we can view a web page that includes java applets with a regular browser, we will not gain any of
benefits.
ii) Netscape Navigator
• From netscape communication corporation, is a general-purpose browser that can run java applets.
• With version available for Windows, Solaris and Apple Macintosh, Netscape Navigator was one of the most
widely used browsers of its time.
• But with increasing popularity of IE browser, the use of NN decreased over a period of time.
• Even Netscape communication has stopped further development of this browser after its latest stable release
March 2008
iii) Internet Explorer
• It is another popular browser developed by Microsoft for Windows 95, NT and XP workstations.
• Both the NN & IE use tool bars, menus and dialog boxes for easy navigation.
• IE uses a just-in-time(JIT) compiler which greatly increases the speed of execution.
7. H/W & S/W Requirements :
• Platform – Solaris, windows intel architecture 32-bit, Linux 32-bit etc.,
• Memory - 64/128 MB
• Browsers – Mozila, IE
• Disk Space – 98/110/58/56 MB
8. Java Support Systems :
• Internet connection
• Web Server
• Web Browser
• HTML
• APPLET Tag
• Java Code
• Byte code
• Proxy server
• Mail Server
9. Java Environment :
i) JDK (Java Development Kit)
comes with a collection of tools that are used for developing and running java programs.
• Appletviewer – for viewing java applets
• Javac – java compiler
• Java – java interpreter
• Javap – jave disassembler
• Javah – for C header files
• Javadoc – for creating HTML documents
• Jdb – java debugger
ii) API (Application Programming Interface)
includes 100s of classes and methods grouped into several functional packages.
• Language support Package – implementing basic features of Java
• Utilities Package – provide utility functions such as date and time functions
• I/O Package – for I/O manipulation
• Networking Package – for communicating with other computers via the internet
• AWT Package – implements platform-independent GUI
• Applet Package – allows us to create java applets
iii) JRE (Java Runtime Environment)
facilitates the execution of programs developed in Java
• JVM – it is a program that interprets the intermediate Java byte code and generates the desired o/p.
• Runtime class libraries – a set of core class libraries that are required for the execution of java programs.
• User interface toolkit – support varied i/p methods for the users to interact with the application program.
• Deployment technologies – comprises
a) Java plug-in – enbles the execution of a java applet on the browser
b) Java web start – enables remote-deployment of an application.
OVERVIEW OF JAVA LANGUAGE
To create a simple java program, you need to create a class that contains main method. Let's understand the
requirement first.
REQUIREMENT FOR HELLO JAVA EXAMPLE:
For executing any java program, you need to
• install the JDK if you don't have installed it, download the JDK and install it.
• set path of the jdk/bin directory.
• create the java program
• compile and run the java program
CREATING HELLO JAVA EXAMPLE :
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
save this file as Simple.java
To compile : javac Simple.java
To execute :java Simple
JAVA PROGRAM STRUCTURE
• Let’s use example of HelloWorld Java program to understand structure and features of class.
• This program is written on few lines, and its only task is to print “Hello World from Java” on the screen. Refer th
following picture.
1.“PACKAGES”:
2. “PUBLIC CLASS HELLOWORLD”:
3. COMMENTS SECTION:
4. “PUBLIC STATIC VOID MAIN (STRING [ ] ARGS)”:
5. SYSTEM.OUT.PRINTLN("HELLO WORLD FROM JAVA")
JAVA TOKENS
• A Java program is basically a collection of classes.
• A class is defined by a set of declaration statements and methods containing executable statements.
• Most statements contain expressions, which describe the actions carried out on data.
• Smallest individual unit in a program are known as tokens.
• The compiler recognizes them for building up expressions and statements.
5 Types of Tokens
i. Reserved keywords
ii. Identifiers
iii. Literals
iv. Operators
v. Separators
Diagram
JAVA CHARACTER SET
• The smallest units of Java language are the characters used to write Java tokens.
• These characters are defined by the Unicode character set.
• Emerging standard that tries to create characters for a large number of scripts worldwide.
• The Unicode is a 16-bit character coding system and currently supports more than 34,000 defined characters.
• That is derived from 24 languages
KEYWORDS IN JAVA
• Java Keywords also called a reserved word. Keywords are identifiers that Java reserves for its own use.
• Since keywords have specific meanings
• These identifiers have built-in meanings that cannot change.
• There are 50 reserved keywords currently defined in the Java language and they are shown in the below table.
• Eg. Boolean, interface, abstract
• We cannot use them as names for variables, classes, methods etc.,.
JAVA STATEMENT:
• Statements are roughly equivalent to sentences in natural languages.
• A statement is an executable combination of token ending with a semicolon(;) mark.
• A statement forms a complete unit of execution.
• The following types of expressions can be made into a statement by terminating the expression with a semicolon
• Statements are usually executed in sequence in the order in which they appear.
• So it control flow of execution
• If necessary , using special statements.
• Assignment expressions
• Any use of ++ or --
• Method invocations
• Object creation expressions
• Such statements are called expression statements.
• Here are some examples of expression statements.
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();
Diagram
Statement Description Remarks
Empty
Statement
These do nothing and are used during
program development as a place
holder
Same as C
& C++
Labelled
Statement
Any Statement may begin with a
lebel. Such label not be keywords
Identical to
C & C++
except jump
Summary of Java Statements :
2 Diagrams
WHAT JVM DOES?
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Expression
Statement
Most Statements are expression
Statements.
7 Types : Assignment, Pre-increment,
Pre-Decrement, post-increment. Post-
Decrement, Method call and
Allocation Expression
Same as
C++
Selection
Statement
Select one of several control flows: if,
if-else.
Same as C
& C++
Iteration
Statement
How and when looping will take place Identical to
C & C++
except
jump& label
Jump Statement Pass control to the beginning or end of the current
block
C & C++ do not use
labels with jump
Synchronization
Statement
These are used fro handling issues with
multithreading
Now available in C &
C++
Guarding Statement For safe handling of code that may cause
exceptions. Try, catch, finally…
Same as in C++
except finally
statement
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
VARIABLES IN JAVA
1. Introduction
2. Declaration of Variables
3. Giving Values to Variables
4. Scope of Variables
5. Getting Values of variables
6. Standard Default Values
7. Type casting
1. INTRODUCTION :
• A variable is an identifier that denotes a storage location used to store a data value.
• Constants – that remain unchanged during the execution of a program
• Variable – may take different values of different times during the execution of the program
• variable is chosen by the programmer in a meaningful way.
• Consists of alphabets, digits, underscore and dollar characters
Conditions :
• They must not begin with a digit
• Uppercase & Lowercase are distinct.
• Not be a keyword
• White space is not allowed
• Any length
2. Declaration of Variables :
• Variables hold one value at a time, but that value can change
• After defining suitable names, declare them to the compiler.
3 things
i. It tells the compiler what the variable name is
ii. Specifies type of the data variable
iii. Scope of the variable
Syntax:
dataType identifier;
or
dataType var1, var2, … varn;
• Variables are separated by commas
Ex:
int x;
float y;
3. Giving Values to Variables :
A variable must be given a value after it has been declared but before used
Achieved in 2 Ways :
i) By using an Assignment statement
ii) By using a read statement
By using an Assignment statement
- A simple method of giving value to a variable
Syntax:
variableName = value;
Ex : x = 5;
- Also possible to assign a value to a variable at the time of declaration
Syntax: type variableName = value;
Ex : int x = 5;
By using a read statement
- through the keyboard using the readLine( ) method
Ex : System.out.printline(“Enter vale”);
x = Integer.parseInt(in.readLine( ));
readLine( ) – reads the i/p from the keyboard as a string which is then converted to the corresponding data ty
using the data type wrapper classes.
i) By using a read statement
Reading I/p from Keyboard
a) Use System.Console class – to read lines
Ex :
System.out.printline(“Enter value”);
int x = System.Console().readLine( );
System.out.printline(“The valu is :” + x);
b) Use java.util.Scanner class and System.in
Ex : Scanner sc=new Scanner(System.in);
String s = sc.nextLine(); -> read the line
System.out.println(“ the string is” + s);
By using a read statement
Reading I/p from Keyboard
c) Use BufferedReader class – to read lines
Ex : InputStreamReader isr = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(isr);
4. Scope of Variables :
3 Kinds :
a) instance variables
b) class variables
c) local variables
Instance and class variables are declared inside a class
a) instance variables
- created when the objects are instantiated and they are associated with the objects.
- take different values for each objects.
b) class variables
- global to a class & belong to the entire set of objects that class creats
- only one memory location is created.
c) local variables
- variables declared and used inside methods are called local variables
-not available for outside the method definition
-declared inside a program blocks
- defined b/w { } .
5. Getting Values of Variables :
Java supports 2 o/p methods
- i) print( ) method
- ii) println( ) method
i) print( ) method
- sends information into a buffer
-This buffer is not flused until a
newline character in sent
- prints o/p on one line until a ne
is encountered
Ex : System.out.print(“Hi”);
ii) println( ) method
- stake the information provided
displays it on a line followed by a line f
Ex :
System.out.println(“Hi”);
6. Standard Default Variables :
- Every variable has a default valu
Type of variable Default value
byte Zero:0
short Zero:0
int Zero:0
long Zero:0L
float 0.0f
double 0.0d
char null character
boolean false
7. TYPE CASTING :
- To store a value of one type into a variable of another type
Syntax:
type var1 = (type) var2;
Ex :
int m = 10;
byte n = (byte) m;
Automatic Conversion
- assign a value of one type to a variable of a different type without a cast.
- the conversion of the assigned value automatically known as automatic-type conversion
Ex : byte b =10; int a =b;
From To
byte Short, char, int, long, float, double
short Int, long, float, double
char Int, long, float, double
int long, float, double
reference null
long float, double
float double
VARIABLE ARGUMENT (VARARGS):
The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded
method or take an array as the method parameter but it was not considered good because it leads to the maintenance
problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach.
ADVANTAGE OF VARARGS:
WE DON'T HAVE TO PROVIDE OVERLOADED METHODS SO LESS CODE.
SYNTAX OF VARARGS:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
1. return_type method_name(data_type... variableName){}
SIMPLE EXAMPLE OF VARARGS IN JAVA:
1.
2. class VarargsExample1{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. }
7.
8. public static void main(String args[]){
9.
10. display();//zero argument
11. display("my","name","is","varargs");//four arguments
12. }
13. }
14.
Test it Now
Output:display method invoked
display method invoked
ANOTHER PROGRAM OF VARARGS IN JAVA:
1.
2. class VarargsExample2{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display();//zero argument
14. display("hello");//one argument
15. display("my","name","is","varargs");//four arguments
16. }
17. }
18.
Test it Now
Output:display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs
download this example
Rules for varargs:
While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as
follows:
o There can be only one variable argument in the method.
o Variable argument (varargs) must be the last argument.
EXAMPLES OF VARARGS THAT FAILS TO COMPILE:
1.
2. void method(String... a, int... b){}//Compile time error
3.
4. void method(int... a, String b){}//Compile time error
5.
EXAMPLE OF VARARGS THAT IS THE LAST ARGUMENT IN THE METHOD:
1.
2. class VarargsExample3{
3.
4. static void display(int num, String... values){
5. System.out.println("number is "+num);
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display(500,"hello");//one argument
14. display(1000,"my","name","is","varargs");//four arguments
15. }
16. }
17.
Test it Now
Output:number is 500
hello
number is 1000
my
name
is
varargs
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of
values. This argument that can accept variable number of values is called varargs.
The syntax for implementing varargs is as follows:
accessModifier methodName(datatype… arg) {
// method body
}
In order to define vararg, ... (three dots) is used in the formal parameter of a method.
A method that takes variable number of arguments is called a variable-arity method, or simply a varargs method.
First, let’s look at the example without using varargs:
class NoVararg {
public int sumNumber(int a, int b){
return a+b;
}
public int sumNumber(int a, int b, int c){
return a+b+c;
}
public static void main( String[] args ) {
NoVararg obj = new NoVararg();
System.out.println(obj.sumNumber(1, 2));
System.out.println(obj.sumNumber(1, 2, 3));
}
}
When you run this program, the output will be:
3
6
As you can clearly see, you had to overload sumNumber() method to make it work for 3 arguments.
THINGS TO REMEMBER WHILE USING VARARGS
Here are a couple of things you should remember while working with Java vargars:
1. While defining method signature, always keep varargs at last.
The variable argument must be the last argument passed to the method. Let's consider, you
invoked doSomething() method like this:
doSomething(1, 2, 3, 4);
And, your doSomething() method is defined as:
// incorrect method declaration
public void doSomething(int ... nums, int p){
// method body
}
In this case, compiler cannot figure out the number of arguments passed to nums.
However, if you define your method as:
public void doSomething(int p, int ... nums) {
// method body
}
The Java compiler assigns the first argument to p, and the remaining int arguments are assigned to nums.
2. A method can have only one varargs parameter.
For example, this method declaration is incorrect:
int doSomething(int p, float ... floatNums, double ... doubleNums) {
// code
}
AMBIGUITY IN VARARGS METHOD OVERLOADING
Let’s consider you overloaded test() method like this:
class Demo {
static void test(int ... vargs) {
// method body
}
static void test(int n, int ... vargs) {
// method body
}
}
In the above program, the compiler gets confused if you try to invoke the test() method even though test() methods
are overloaded and accepts different number of arguments.
OPERATORS IN JAVA :
2 )
1 )
3 )
4 )
5 )
6 )
7)
8 )
9 )
10 )
11 ) 1
13 )
14
15 )
17 )
18 )
EXPRESSIONS IN JAVA :
Definition :
• An expression in java is a combination of operators , variables ,constants & method invocations.
• Expression is used to perform the computation indicated by the elements of the expression and return some value.
Example : int a=5; // returns 5
if(a==b) // returns Boolean value
c = a + b; // returns a manipulated values
System.in.read(); // evaluate a single value
TYPES OF EXPRESSIONS :
There are three types of expressions in java. They are,
1. Expression that produce a value
2. Expression that assign a variable
3. Expressions with no result
EXPRESSIONS THAT PRODUCE A VALUE :
• It uses operators to produce a value such a Arithmetic operators ,Conditional operator, Comparison operator
, etc…
• Example: C=3+2
A=10/5
B= 2*4/5
EXPRESSIONS THAT ASSIGN A VARIABLE :
• It is a expression that assigns a value to the variable.
• Example: Int A=0; // assigns integer value
B= true; // assigns boolean value
EXPRESSIONS WITH NO RESULT :
• Some expressions does not produce result but give a side effect which occurs when an expression changes
the Value of an operands.
• Example: P = a*b;
Here value of variable ‘p’ is changed when calculated , but value of variable ‘a’ and ‘b’ does not change. This is
called side effect.
• a++
• Here ,value of variable ‘a’ is changed according to the program.
Unit – II
Classes, Objects and Methods
1. Introduction
2. 2. Defining a Class
3. Methods Declaration
4. Creating Objects
5. Accessing Class Members
6. Constructors
7. Method Overloading
8. Static Members
9. Nesting of Methods
10. Inheritance : Extending a Class
11. Overriding Methods
12. Final Variables and Methods
13. Final Classes
14. Finalizer Methods
15. Abstract Methods and Classes
16. Methods with Varargs
17. Visibility Control
INTRODUCTION :
• Java is a true OOPL
• The underlying structure of all Java programs is classes.
• Anything represented in a class
• Class defines the state and behavior of the basic program components known as objects
• Classes create objects and objects use methods to communicate between them
• Classes provide a convenient method for packing together a group of logically related data items and
functions
• In Java The data items are called fields and the functions are called methods.
DEFINING A CLASS :
• A class is a user-defined data type with a template that serves to define its properties
• These variables are called instance variables because they are created whenever an object of the class is
instantiated.
Ex : class A
{
int length;
Int width;
}
3. FIELDS DECLARATION :
• Data is encapsulated in a class by placing data fields inside the body of the class definition
• Once the class type has been defined, we can create variables of that type using declarations that are similar to
the basic-type declarations.
• These termed as instances of classes, which are the actual objects.
Syntax
class classname [extends superclasname]
{
[ fields declaration; ]
[methods declaration;] }
Ex : class A
{ }
4. METHODS DECLARATION :
• A class with only data fields & without methods that operate on that data has no life.
• The objects created by such a class cannot respond to any messages.
Syntax
type methodname (parameter-list)
{
Method-body;
}
4 basic parts :
i) The name of the method – method name
ii) The type of the value the method returns – type
iii) A list of parameters(parameter-list)
iv) The body of the method
Ex : Class Rect
{
Int len, wid;
Void getdata(int x, int y)
{
len=x;
Wid=y;
}
}
5. CREATING OBJECTS :
• An object in java is essentially a block of memory that contains space to store all the instance variables.
• object in java are created using the new operator
• The new operator creates an object of the specified class and returns a reference to that object.
Ex: Rect r1;
R1=new Rect( );
(or)
Rect r1 = new Rect( );
Diagram
Diagram
6. ACCESSING CLASS MEMBERS :
• All variables must be assigned values before they are used.
• Outside of the class cannot access the instance variables and methods directly.
• so, we must use the concerned object and the dot operator
Syntax :
objectname.variablename = value;
objectname.methodname(parameter-list);
Variablename -> name of the instance variable inside the object we wish to access
Methodname -> the method we wish to call
Parameter list-> actual values that must match in type and number
Ex: Rect r1 = new Rect( );
Rect r2=r1; r1.getdata(25, 30)
r1.length = 10;
r2.length = 12;
Ex: void getdata(int x, int y)
{ length = x;
width = y; }
….main( )
{ Rect r1 = new Rect( );
r1.getdata(25, 30) }
7. CONSTRUCTORS :
2 approaches ( objects created) :
i) Uses the dot operator to access the instance vars & assign values to them immediately.
- difficult to initialize all the vars to all the objs
ii) Takes the help of a method like r1.getdata(15,20); - simple one
iii) But java supports special type of method called a constructor.
- It enables an object to initialize itself when it is created.
Constructor :
• Have the same name as the class itself
• Do not specify a return type not even void
• Because it return the instance of the class itself.
Ex : class Rect
{ int length;
int width;
Rect(int x, int y)
{ length = x;
width = y; }
int rectArea()
{ return(length * width); }}
8. METHOD OVERLOADING :
Definition – Method Overloading
In java, possible to create methods that have the same name, but different parameter lists and different definitions. T
called method overloading.
• It is used when objects are required to perform similar task but using different input parameters
• When we call a method, it follows
- first matches the method name
- then the number of parameters
- type of parameters
• This process is known as polymorphism.
• Ex : – Method Overloading
class Rect
{ int length;
int width;
Rect(int x, int y) // Constructor 1
{ length = x;
width = y }
Rect(int x) // Constructor 2
{ length = width=x; }
int rectArea()
{ return(length * width); }}
9. STATIC MEMBERS :
Class contains 2 sections
i) declares variables
ii) declares methods
- these variables & methods are called instance variables & instance methods.
- because every time the class is instantiated, a new copy of each of them is created.
- they are accessed using the objects with dot operator.
• Assume, we want to define a member that is common to all the objects and accessed without using a
particular object.
• ie., the member belongs to the class as whole rather than the objects created from the class.
Ex:
static int c;
static int area(int x, int y);
- the members are declared as static are called static members.
- these members associated with the class itself rather than individual objects.
- the static vars & methods referred to as class vars & methods.
- Static vars are used when we want to have a var common to all instances of a class.
Ex :
class Operation
{ static float mul(float x, float y)
{ return x*y; }
static float div(float x, float y)
{ return x/y; }}
Class MathOp
{ public void static main(String args[])
{ float a = Operation.mul(5.0,2.0);
float b = Operation.div(6.0,2.0);
System.out.ptintln(“a=“+a);
System.out.ptintln(“b=“+b) }}
10. NESTING OF METHODS :
Def : A method can be called by using only its name by another method of the same class is known as nesting
of methods.
class Nest
{ int large()
{ …. }
class display( )
{ int l = large( ); }
Class Ntest
{ public void static main(String args[])
{ ….. }
INHERITANCE IN JAVA :
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class,
extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class. You can use the same fields and methods already
defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{ //methods and fields }
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning
of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called
child or subclass.
Java Inheritance Example
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship
between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee{ float salary=40000; }
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
} }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code
reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about
interfaces later.
Note: Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class
inherits the Animal class, so there is the single inheritance.
TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{ void bark(){System.out.println("barking..."); } }
class TestInheritance{ public static void main(String args[]) {
Dog d=new Dog();
d.bark();
d.eat(); }}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");} }
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat(); }}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes
have the same method and you call it from child class object, there will be ambiguity to call the method of A or B
class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked? } }
Test it Now
Compile Time Error
Method Overriding
Method Overloading and Method Overriding are the topics that should be on your to-do list before appearing for
the interview. In this post, I will share what is method overriding, the rules of method overriding, and examples. So
let's dive in and understand method overriding in java.
What is Method Overriding
When the child class(subclass) has the method which has the same name, same parameters and same return type (or
covariant return type) as a method in its parent class(or super-class), then the child method has overridden the
parent class method.
Runtime polymorphism can be achieved through method overriding. Remember that at runtime, Object type
(not reference variable's type) determines which overridden method is used.
If the parent class object is used to invoke the method, then the parent class method will be executed. Otherwise, if,
a child class object is used to invoke the method, then the child class method will be executed.
Example of Method Overriding
// Method Overriding Example
//Base class
class Parent { public void display() {
System.out.println("parent method is executed"); }}
//Derived or Inherited class
class Child extends Parent { //Below method overrides the Parent display() method
@Override
public void display() { System.out.println("child method is executed"); }}
//Driver class
public class MethodOverriding1 {
public static void main(String args[])
{ // If a Parent type reference refers
// to a Parent object, then Parent's
// display() is called
Parent parentObject = new Parent();
parentObject.display();
// If a Parent type reference refers
// to a Child object Child's display()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent childObject = new Child();
childObject.display(); }}
Output:
parent method is executed
child method is executed
Rules for Method Overriding in Java
1. ACCESS MODIFIERS AND OVERRIDING
The access level can't be more restrictive than the overridden method. The access level can be less restrictive than
that of the overridden method.
For example, a protected instance method in the parent class(superclass) can be made public but not private in the
child class(subclass). If you try to make a child class private then it will give the compile-time..error.
// Access Modifiers and Overriding Example
//Base class
class Parent { //Access modifier of parent's display() method is protected
protected void display() { System.out.println("parent method is executed"); }}
//Derived class
class Child extends Parent { //Below method overrides the Parent display() method
//Access modifier public is less restrictive than protected
@Override
public void display() { System.out.println("child method is executed"); } }
//Driver class
PublicclassMethodOverriding2{
public static void main(String args[])
{ Parent parentObject = new Parent();
parentObject.display();
Parent childObject = new Child();
childObject.display(); }}
Output :
parent method is executed
child method is executed
2. Private methods can not be overridden
Another rule regarding access modifiers is you can not override private methods in the parent class. If subclass
tries to override the private method of a parent class then the program will throw a compile-time error as shown
below.
// Access Modifiers and Overriding Example
//Base class or Superclass
class Parent { //Access modifier of parent method is private
// This method can not override the child class method
private void display() { System.out.println("parent method is executed"); }}
//Derived class or Subclass
class Child extends Parent {
//Below method can not overrides the Parent display() method
//This method is unique to the child class
private void display() { System.out.println("child method is executed"); }}
//Driver class
public class MethodOverriding3 {
public static void main(String args[])
{ Parent parentObject = new Parent();
parentObject.display(); // this line when execute will throw compiler error
Parent childObject = new Child();
childObject.display(); // this line when execute will throw compiler error }}
3. Final methods can not be overridden in Java
You can not override a method marked final. It will throw a compile-time error if you try to do so.
// Simple Java program showing
// final methods cannot be overridden
//Parent class or Superclass
class Parent
{ // Can't be overridden
final void display() { } }
//Child class or Subclass
class Child extends Parent
{ // This would produce compile time error
void display() { } }
Output :
/Main.java:13: error: display() in Child cannot override display() in Parent
void display()
{ }
^
overriddenmethodisfinal1error
4. Static methods can not be overridden
You can not override a method mark static. If you define a static method in the subclass (child class) with the same
method signature as the superclass(parent class) then it is called method hiding.
// Method hiding example
//Base class or SuperClass
class Parent {
static void display() {
System.out.println("parent static method is executed"); }
void show() {
System.out.println("parent non-static (instance) method is executed"); }}
//Derived class or SubClass
class Child extends Parent {
//This method hides the Parent display() method
static void display() { System.out.println("child static method is executed"); }
// This method overrides the Parent show() method
void show() { System.out.println("child non-static (instance) method is executed"); }}
//Driver Class
public class MethodOverriding4 { public static void main(String args[])
{ Parent childObject = new Child();
// static method can not be overridden,
// so below line calls parent display() method
childObject.display();
// Expected child method will run
childObject.show(); }}
Output:
parent static method is executed
child non-static (instance) method is executed
5. Invoking a superclass (Parent class) version of overridden method
It's easy to call the superclass(Parent class) version of overridden method by using the super keyword.
// Invoking SuperClass version of Overridden Method Example
//Base class or SuperClass
class Parent {
void display() {
System.out.println("parent method is executed");
}
}
//Derived class or SubClass
class Child extends Parent {
//This method overrides the Parent display() method
@Override
void display() {
super.display();
System.out.println("child method is executed");
}
}
public class MethodOverriding5 {
public static void main(String args[])
{
Parent childObject = new Child();
childObject.display();
}
}
Output :
parent method is executed
child method is executed
6. Overriding method must have the same return type (or Covariant return type) :
The method return type must be the same, or a subtype of, the return type declared in the original
overridden..method..in..the..superclass. Since java 5.0 it is made possible to have a different return type for an
overriding method in a child class. But child's return type should be a subtype of the parent's
return..type…This..phenomenon..is..called..covariant..return..type.
Example of Covariant Return Type
class Alpha { Alpha doStuff(char c) {
return new Alpha(); }}
class Beta extends Alpha {
Beta doStuff(char c) { // legal override in Java 1.5
return new Beta(); }}
public class MethodOverriding6 {
public static void main(String args[])
{ Alpha childObject = new Beta();
childObject.doStuff('a'); }}
The above code will compile and run.
7. Constructor and Overriding
You can not override the constructor as the constructor name of the base class and child class can never be the same.
(Constructor name is always the same as the class name).
8. Exception Handling and Overriding
Rule 1. The overriding method can throw any unchecked(runtime) exception regardless of whether the overridden method
declares the exception.
// Overriding when superclass does not throw an exception
//Base class or SuperClass
class Parent { //overridden method
void display() {
System.out.println("parent method is executed"); }}
//Derived class or SubClass
class Child extends Parent {
//This method overrides the Parent display() method
//It throws unchecked exception i.e Arithmetic Exception
@Override
void display() throws ArithmeticException{
System.out.println("child method is executed"); }}
public class MethodOverriding7 {
public static void main(String args[])
{ Parent childObject = new Child();
childObject.display(); }}
Output: child method is executed
Rule 2. The overriding method must not throw checked exceptions that are new or broader than those declared by
the overridden method. For example, a method that declares a FileNotFoundException can not be overridden by a
method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of
FileNotFoundException.
Note : The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes
risks" doesn't mean that the overriding subclass' exception takes the same risks.
Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of
what the overridden method declares.
9. Abstract method and Overriding
Abstract methods can only be overridden by the first concrete class (classes that have no abstract methods)
otherwise a compiler error will be thrown.
//Abstract class
abstract class Parent
{ public abstract void display( int x, String j); }
//Subclass or Derived Class
class Child extends Parent
{ @Override
public void display( int x, String j )
{ System.out.println("child method is executed"); }}
//Driver class
public class MethodOverriding8 {
public static void main(String args[])
{ Parent childObject = new Child();
childObject.display(1, "Alive is Awesome"); }}
Output : child method is executed
10. Synchronized/strictfp method and Overriding
Synchronized or strictfp methods do not have any impact on the overriding method. It's possible that a non-
synchronized or non-strictfp method can override a synchronized/strictfp method or vice versa.
MultiLevel Method Overriding in Java
In the multilevel method overriding we create a grandchild class and override the display() method of the
parent class. Let's find out what will happen if we perform runtime polymorphism in multilevel..overriding.
// MultiLevel Overriding
//Base class or SuperClass
class Parent { //overridden method
void display() {
System.out.println("parent method is executed"); }}
//Derived class or SubClass
class Child extends Parent {
//This method overrides the Parent display() method
@Override
void display() {
System.out.println("child method is executed"); }}
//Inherited Class
class GrandChild extends Child {
// This method overrides the Parent display() method
@Override
void display() { System.out.println("grand child method is executed"); }}
//Driver Class
public class MethodOverriding9 {
public static void main(String args[])
{ Parent grandchildObject = new GrandChild();
grandchildObject.display(); }}
Output: grand child method is executed
Examples of Legal/Illegal Method Overrides
Let's have a simple class Animal with the eat() method.
public class Animal { public void eat() { } }
Below is the list of the legal/illegal overrides of the Animal eat() method.
1. private void eat() {} - Illegal override code. Access modifier is more restrictive.
2. public void eat() throws IOException {} - Illegal override code. It declares a checked exception not defined by
the superclass version.
3. public void eat(String food) {} - A legal overload, not an override because the argument list changed.
4. public String eat() {} - Not an override because of the return type, not an overload either because there's no
change in the argument list.
Advantages of Using @Override Annotation in the Code
According…to Oracle…docs,
@Override annotation informs the compiler that the element is meant to override an element declared in
a..superclass.
// mark method as a superclass method // that has been overridden
@Override
int overriddenMethod() { }
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method
marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates
an error.
Overloading vs Overriding
1. Overloading is an example of compile-time polymorphism while Overriding is an example of run-
time…polymorphism.
2. In the method overloading parameters must be different. In overriding parameters must be the same
(different…if…covarians…return…type).
3. Method overloading increases the readability of the program. Meanwhile, method overriding provides a specific
implementation of the method.
Difference between method overloading and method overriding in java :
There are many differences between method overloading and method overriding in java. A list of differences
between method overloading and method overriding are given below:
Method Overloading Method Overriding
1) Method overloading is used to increase the readability
of the program.
Method overriding is used to provide the
specific implementation of the method that is
already provided by its super class.
2) Method overloading is performed within class. Method overriding occurs in two classes
that have IS-A (inheritance) relationship.
3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be
same.
4) Method overloading is the example of compile time polymorphism. Method overriding is the example of
Run time polymorphism.
5) In java, method overloading can't be performed by changing return type
of the method only. Return type can be same or different in method
overloading. But you must have to change the parameter.
Return type must be same or covariant in
method overriding.
Java Method Overloading example
class OverloadingExample{ static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;} }
Java Method Overriding example
class Animal{ void eat(){System.out.println("eating..."); } }
class Dog extends Animal{ void eat(){System.out.println("eating bread..."); } }
VARIABLES IN JAVA
1. Introduction
2. Declaration of Variables
3. Giving Values to Variables
4. Scope of Variables
5. Getting Values of variables
6. Standard Default Values
7. Type casting
1. INTRODUCTION :
• A variable is an identifier that denotes a storage location used to store a data value.
• Constants – that remain unchanged during the execution of a program
• Variable – may take different values of different times during the execution of the program
• variable is chosen by the programmer in a meaningful way.
• Consists of alphabets, digits, underscore and dollar characters
Conditions :
• They must not begin with a digit
• Uppercase & Lowercase are distinct.
• Not be a keyword
• White space is not allowed
• Any length
2. Declaration of Variables :
• Variables hold one value at a time, but that value can change
• After defining suitable names, declare them to the compiler.
3 things
iv. It tells the compiler what the variable name is
v. Specifies type of the data variable
vi. Scope of the variable
Syntax:
dataType identifier;
or
dataType var1, var2, … varn;
• Variables are separated by commas
Ex:
int x;
float y;
3. Giving Values to Variables :
A variable must be given a value after it has been declared but before used
Achieved in 2 Ways :
iii) By using an Assignment statement
iv) By using a read statement
By using an Assignment statement
- A simple method of giving value to a variable
Syntax:
variableName = value;
Ex : x = 5;
- Also possible to assign a value to a variable at the time of declaration
Syntax: type variableName = value;
Ex : int x = 5;
By using a read statement
- through the keyboard using the readLine( ) method
Ex : System.out.printline(“Enter vale”);
x = Integer.parseInt(in.readLine( ));
readLine( ) – reads the i/p from the keyboard as a string which is then converted to the corresponding data ty
using the data type wrapper classes.
ii) By using a read statement
Reading I/p from Keyboard
b) Use System.Console class – to read lines
Ex :
System.out.printline(“Enter value”);
int x = System.Console().readLine( );
System.out.printline(“The valu is :” + x);
b) Use java.util.Scanner class and System.in
Ex : Scanner sc=new Scanner(System.in);
String s = sc.nextLine(); -> read the line
System.out.println(“ the string is” + s);
By using a read statement
Reading I/p from Keyboard
c) Use BufferedReader class – to read lines
Ex : InputStreamReader isr = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(isr);
4. Scope of Variables :
3 Kinds :
a) instance variables
b) class variables
c) local variables
Instance and class variables are declared inside a class
a) instance variables
- created when the objects are instantiated and they are associated with the objects.
- take different values for each objects.
b) class variables
- global to a class & belong to the entire set of objects that class creats
- only one memory location is created.
c) local variables
- variables declared and used inside methods are called local variables
-not available for outside the method definition
-declared inside a program blocks
- defined b/w { } .
5. Getting Values of Variables :
Java supports 2 o/p methods
- i) print( ) method
- ii) println( ) method
i) print( ) method
- sends information into a buffer
-This buffer is not flused until a
newline character in sent
- prints o/p on one line until a ne
is encountered
Ex : System.out.print(“Hi”);
ii) println( ) method
- stake the information provided
displays it on a line followed by a line f
Ex :
System.out.println(“Hi”);
6. Standard Default Variables :
- Every variable has a default valu
Type of variable Default value
byte Zero:0
short Zero:0
int Zero:0
long Zero:0L
float 0.0f
double 0.0d
char null character
boolean false
7. TYPE CASTING :
- To store a value of one type into a variable of another type
Syntax: type var1 = (type) var2;
Ex : int m = 10;
byte n = (byte) m;
Automatic Conversion
- assign a value of one type to a variable of a different type without a cast.
- the conversion of the assigned value automatically known as automatic-type conversion
Ex : byte b =10; int a =b;
From To
byte Short, char, int, long, float, double
short Int, long, float, double
char Int, long, float, double
int long, float, double
long float, double
float double
Final Keyword In Java
1. Final variable
2. Final method
3. Final class
reference null
4. Is final method inherited ?
5. Blank final variable
6. Static blank final variable
7. Final parameter
8. Can you declare a final constructor
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final
can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be
static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn
the basics of final keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
Example of final method
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error
3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not be
changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Example of blank final variable
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:
1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output: 70
static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can
be initialized only in static block.
Example of static blank final variable
1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.
1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now
Output: Compile Time Error
Q) Can we declare a constructor final?
No, because constructor is never inherited.
Java Object finalize() Method
Finalize() is the method of Object class. This method is called just before an object is garbage collected. finalize()
method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.
Syntax
1. protected void finalize() throws Throwable
Throw
Throwable - the Exception is raised by this method
Example 1
1. public class JavafinalizeExample1 {
2. public static void main(String[] args)
3. {
4. JavafinalizeExample1 obj = new JavafinalizeExample1();
5. System.out.println(obj.hashCode());
6. obj = null;
7. // calling garbage collector
8. System.gc();
9. System.out.println("end of garbage collection");
10.
11. }
12. @Override
13. protected void finalize()
14. {
15. System.out.println("finalize method called");
16. }
17. }
Test it Now
Output:
2018699554
end of garbage collection
finalize method called
ABSTRACT CLASS IN JAVA :
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and
non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where you type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods.
It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
Example of abstract class
1. abstract class A{}
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as an abstract method.
Example of abstract method
1. abstract void printStatus();//no method body and abstract
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided
by the Honda class.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Test it Now
running safely
Understanding the real scenario of Abstract class
In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the
implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.
File: TestAbstraction1.java
1. abstract class Shape{ abstract void draw(); }
2. //In real scenario, implementation is provided by others i.e. unknown by end user
3. class Rectangle extends Shape{
4. void draw(){System.out.println("drawing rectangle");} }
5. class Circle1 extends Shape{
6. void draw(){System.out.println("drawing circle");} }
7. //In real scenario, method is called by programmer or user
8. class TestAbstraction1{ public static void main(String args[]){
9. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
10. s.draw(); } }
Test it Now
drawing circle
Another example of Abstract class in java
File: TestBank.java
1. abstract class Bank{
2. abstract int getRateOfInterest(); }
3. class SBI extends Bank{
4. int getRateOfInterest(){return 7;} }
5. class PNB extends Bank{
6. int getRateOfInterest(){return 8;} }
7. class TestBank{ public static void main(String args[]){ Bank b;
8. b=new SBI();
9. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
10. b=new PNB();
11. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %"); }}
Test it Now
Rate of Interest is: 7 %
Rate of Interest is: 8 %
VARIABLE ARGUMENT (VARARGS):
The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded
method or take an array as the method parameter but it was not considered good because it leads to the maintenance
problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach.
ADVANTAGE OF VARARGS:
We don't have to provide overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
return_type method_name(data_type... variableName){}
SIMPLE EXAMPLE OF VARARGS IN JAVA:
15.
16. class VarargsExample1{
17. static void display(String... values){
18. System.out.println("display method invoked "); }
19. public static void main(String args[]){
20. display();//zero argument
21. display("my","name","is","varargs");//four arguments } }
Test it Now
Output:display method invoked
display method invoked
ANOTHER PROGRAM OF VARARGS IN JAVA:
19.
20. class VarargsExample2{
21. static void display(String... values){
22. System.out.println("display method invoked ");
23. for(String s:values){
24. System.out.println(s); } }
25. public static void main(String args[]){
26. display();//zero argument
27. display("hello");//one argument
28. display("my","name","is","varargs");//four arguments } }
Test it Now
Output:display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs
download this example
RULES FOR VARARGS:
While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as
follows:
o There can be only one variable argument in the method.
o Variable argument (varargs) must be the last argument.
EXAMPLES OF VARARGS THAT FAILS TO COMPILE:
6. void method(String... a, int... b){}//Compile time error
7. void method(int... a, String b){}//Compile time error
EXAMPLE OF VARARGS THAT IS THE LAST ARGUMENT IN THE METHOD:
18. class VarargsExample3{ static void display(int num, String... values){
19. System.out.println("number is "+num);
20. for(String s:values){
21. System.out.println(s);
22. } }
23. public static void main(String args[]){
24. display(500,"hello");//one argument
25. display(1000,"my","name","is","varargs");//four arguments } }
26.
Test it Now
Output:number is 500
hello
number is 1000
my
name
is
varargs
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of
values. This argument that can accept variable number of values is called varargs.
The syntax for implementing varargs is as follows:
accessModifier methodName(datatype… arg) { // method body }
In order to define vararg, ... (three dots) is used in the formal parameter of a method.
A method that takes variable number of arguments is called a variable-arity method, or simply a varargs method.
First, let’s look at the example without using varargs:
class NoVararg {
public int sumNumber(int a, int b){
return a+b; }
public int sumNumber(int a, int b, int c){
return a+b+c; }
public static void main( String[] args ) {
NoVararg obj = new NoVararg();
System.out.println(obj.sumNumber(1, 2));
System.out.println(obj.sumNumber(1, 2, 3)); }}
When you run this program, the output will be:
3
6
As you can clearly see, you had to overload sumNumber() method to make it work for 3 arguments.
THINGS TO REMEMBER WHILE USING VARARGS
Here are a couple of things you should remember while working with Java vargars:
1. While defining method signature, always keep varargs at last.
The variable argument must be the last argument passed to the method. Let's consider, you
invoked doSomething() method like this:
doSomething(1, 2, 3, 4);
And, your doSomething() method is defined as:
// incorrect method declaration
public void doSomething(int ... nums, int p){ // method body }
In this case, compiler cannot figure out the number of arguments passed to nums.
However, if you define your method as:
public void doSomething(int p, int ... nums) { // method body }
The Java compiler assigns the first argument to p, and the remaining int arguments are assigned to nums.
2. A method can have only one varargs parameter.
For example, this method declaration is incorrect:
int doSomething(int p, float ... floatNums, double ... doubleNums) { // code}
AMBIGUITY IN VARARGS METHOD OVERLOADING
Let’s consider you overloaded test() method like this:
class Demo {
static void test(int ... vargs) { // method body }
static void test(int n, int ... vargs) // method body }}
In the above program, the compiler gets confused if you try to invoke the test() method even though test() methods
are overloaded and accepts different number of arguments.
Visibility Control/Access Modifiers in Java
JAVA ACCESS MODIFIERS:
In Java, We have seen that the variables and methods of a class are visible everywhere in the program. However, it
may be necessary for some situations to restrict access to certain variables and methods from outside the class. We
can achieve this in Java by applying visibility modifiers to the instance variables and methods. These visibility
modifiers are also known as Java Access Modifiers. There are five types of Java Access Modifiers are exists:
Private Protected Access Modifiers
PUBLIC:
Any variable or method is visible to the entire class in which it is defined. A variable or method declared
as public has the widest possible visibilty and accessible everywhere.
Example:
public int number;
public void add()
{
.........
.........
}
PRIVATE:
Private field has the highest degree of protection. They are accessible only with their class. They can’t be inherited
by subclasses and therefore not accessible in the subclass. A method declared as private behaves like a method
declared as final. It prevents the method from being subclassed.
Example:
private int number;
private void add()
{ ......... .........}
FRIENDLY OR DEFAULT:
When no access modifier is specified, the member defaults to a limited version of public accessibility that is known
as “Friendly or Default Access Modifiers”.
The difference between the “public” and “friendly or default” access modifiers is that the public makes fields
visible in all classess including other packages, while friendly or default makes fields visible only in the same
package, but not in other packages.
Example:
int number;
void add() { ......... .........}
PROTECTED:
The protected makes the fields visible not only to all classes and subclasses in the same package but also to
subclasses in other packages and non-subclassess in other packages can’t access the protected members.
Example:
public class test{ protected int number;
protected void add() {
......... ......... } }
PRIVATE PROTECTED:
Private Protected makes the fields visible in all subclasses regardless of what package they are in. These fields
aren’t accessible by other classes in the same package.
Example:
private protected int number;
private protected void add()
{ ......... .........}
1. Private access modifier
2. Role of private constructor
3. Default access modifier
4. Protected access modifier
5. Public access modifier
6. Access Modifier with Method Overriding
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package through
child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we
are going to learn the access modifiers only.
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.
Access
Modifier
within
class
within
package
outside package by
subclass only
outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");} }
4. public class Simple{
5. public static void main(String args[]){
6. A obj=new A();
7. System.out.println(obj.data);//Compile Time Error
8. obj.msg();//Compile Time Error } }
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class. For
example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");} }
4. public class Simple{
5. public static void main(String args[]){
6. A obj=new A();//Compile Time Error } }
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more
restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");} }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{ public static void main(String args[]){
5. A obj = new A();//Compile Time Error
6. obj.msg();//Compile Time Error } }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the
package.
3) Protected
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the
class.
It provides more accessibility than the default modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can
be accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");} }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B extends A{
5. public static void main(String args[]){
6. B obj = new B();
7. obj.msg(); } }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg(); } }
Output:Hello
Java Access Modifiers with Method Overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
1. class A{
2. protected void msg(){System.out.println("Hello java");} }
3. public class Simple extends A{
4. void msg(){System.out.println("Hello java");}//C.T.Error
5. public static void main(String args[]){
6. Simple obj=new Simple();
7. obj.msg(); } }
The default modifier is more restrictive than protected. That is why, there is a compile-time error.
JAVA ACCESS MODIFIERS:
In Java, We have seen that the variables and methods of a class are visible everywhere in the program. However, it
may be necessary for some situations to restrict access to certain variables and methods from outside the class. We
can achieve this in Java by applying visibility modifiers to the instance variables and methods. These visibility
modifiers are also known as Java Access Modifiers. There are five types of Java Access Modifiers are exists:
PUBLIC:
Any variable or method is visible to the entire class in which it is defined. A variable or method declared
as public has the widest possible visibilty and accessible everywhere.
Example:
public int number;
public void add()
{ ......... .........}
PRIVATE:
Private field has the highest degree of protection. They are accessible only with their class. They can’t be inherited
by subclasses and therefore not accessible in the subclass. A method declared as private behaves like a method
declared as final. It prevents the method from being subclassed.
Example:
private int number;
private void add() { ......... .........}
FRIENDLY OR DEFAULT:
When no access modifier is specified, the member defaults to a limited version of public accessibility that is known
as “Friendly or Default Access Modifiers”.
The difference between the “public” and “friendly or default” access modifiers is that the public makes fields
visible in all classess including other packages, while friendly or default makes fields visible only in the same
package, but not in other packages.
Example:
int number;
void add()
{ ......... .........}
PROTECTED:
The protected makes the fields visible not only to all classes and subclasses in the same package but also to
subclasses in other packages and non-subclassess in other packages can’t access the protected members.
Example:
public class test{
protected int number;
protected void add()
{ ......... .........} }
PRIVATE PROTECTED:
Private Protected makes the fields visible in all subclasses regardless of what package they are in. These fields
aren’t accessible by other classes in the same package.
Example:
private protected int number;
private protected void add()
{ ......... .........}
JAVA PROGRAMMING
UNIT – V
MANAGING INPUT/OUTPUT in JAVA
1. INTRODUCTION
2. CONCEPT OF STREAMS
3. STREAM CLASSES
4. BYTE STREAM CLASSES
5. CHARACTER STREAM CLASSES
6. USING STREAMS
7. OTHER USEFUL I/O CLASSES
8. USING THE FILE CLASS
9. INPUT/OUTPUT EXCEPTIONS
10. CREATION OF FILES
11. READING/WRITING CHARACTERS
12. READING/WRITING BYTES
13. HANDLING PRIMITIVE DATA TYPES
14. CONCATENATING AND BUFFERING FILES
15. RANDOM ACCESS FILES
16. INTERACTIVE INPUT AND OUTPUT
17. OTHER STREAM CLASSES
1. INTRODUCTION
Problems in variables and arrays:
i) The data is lost either when a variable goes out of scope or when the program is terminated.
ii) It is difficult to handle volumes of data using variables and arrays.
Solution:
 Storing data on secondary storage devices such as floppy disk or hard disks
- The data stored in these devices using the concept of files. Data stored in files is called persistent data.
Files:A file is a collection of related records placed in a particular area on the disk.
Record: A record I composed of several fields and a field is a group of characters.
Characters:Character in Java are Unicode characters composed of 2 bytes, each byte containing eight binary
digits, 1 or 0.
File Processing:
Storing and managing data using files is known as file processing which include tasks such as
- Creating files
- Updating files
- Manipulation of data
Features:
- Reading and writing of data in a file can be done at the level of bytes and characters or fields depending on the
requirements of a particular application.
- Also provides capabilities to read and write close objects directly.
- The process of reading and writing objects is called object serialization.
Fig : Data Representation in java files
2. CONCEPT OF STREAMS
In file processing, input refers to the flow of data into a program and output means the flow of data out of a
program.
I/P : input to a program may come from the keyboard, the mouse, the memory, the disk, a network or
another program.
O/P : output from a program may got to the screen, the printer, the memory, the disk, a network, or another
program.
Fig : Relationship of Java Program with I/O devices
- Different in h/w level
- They share certain common characteristics such as unidirectional movement of data, treating data as
sequence of bytes or characters and support to the sequential access to the data.
Streams: to represent the sequence of data, a common characteristic shared by all the i/o devices.
- A stream presents a uniform, easy-to-use, OO interface b/w the program and the i/o devices.
Definition:
A stream is a path along which data flows.
- It have a source (of dta) and a destination (for that data)
- Both the source and the destination may be physical devices or programs or other streams in the
same program. Fig : Conceptual view of a stream
Java streams are classified into 2 basic types
- Input stream – an i/p stream extracts ie., reads data from the source (file) and sends it to the program.
- Output stream – an o/p stream takes data from the program and sends it to the destination.
Fig : Using input and output streams
- The program connects and opens an i/p stream on the data source and then reads the data serially.
- Similarly, the program connects and opens an o/p stream to the destination place of data out serially.
- In both cases, the program does not know the details of end points(ie., source and destination).
3. Stream Classes
The java.io package contains a large number of stream classes that provide capabilities for processing all types of
data.
2 groups :
i) Byte stream classes that provide support for handling I/O operations on bytes
ii) Character stream classes that provide support for managing i/o operations on characters.
Both contain specialized classes to deal with i/o operations independently.
4. Byte Stream classes
Designed to provide functional features for creating and manipulating streams and files for reading and writing bytes.
- The streams are unidirectional; they can transmit bytes in only one direction.
2 kinds of stream classes :
i) Input stream classes
ii) Output stream classes
i) Input Stream classes
- Used to read 8-bit bytes include a super class known as Inputstream and a number of subclasses for supporting
various input-related functions.
The super class Inputstream is an abstract class, we cannot create instances of the class.
Methods :
- Reading bytes
- Closing streams
- Marking positions in streams skipping ahead in a stream
- Finding the number of bytes in a stream
Summary of Inputstream methods
ii) Output stream
classes
Derived from the base class
outputstream
Perform following tasks :
- Writing styles
- Closing streams
- Flushing streams
5. Character Stream classes:
 Character stream can be used to read and write 16-bit Unicode characters.
 Like byte streams, there are two kinds of character stream classes namely, reader stream
and writer stream classes.
READER STREAM CLASSES:
 Reader stream classes are designed to read character from the files.
 Reader class is the base class for all classes in this group.
 These classes are functionally very similar to the input stream classes, except input stream use bytes as their
fundamental unit of information while reader stream use characters.
 The reader class contains methods that are identical
to those available in the inputstream class, except reader is designed to handle characters.
 Reader classes can perform all the functions implemented by the stream classes.
WRITER STREAM CLASSES:
 The writer classes are designed to perform all output operations on files.
 Only difference is that while output stream classes are designed to write the bytes, the writer
stream classes are designed to write characters.
 The writer class is an abstract class which acts as a base class for all the other writer stream
classes.
 This base class provides support for all output operations by defining methods that are
identical to those in output stream class.

More Related Content

Similar to java full 1 (Recovered).docx

Features of Java.pptx
Features of Java.pptxFeatures of Java.pptx
Features of Java.pptxPeter Jose
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf10322210023
 
C,c++,java,php,.net training institute in delhi, best training institute for ...
C,c++,java,php,.net training institute in delhi, best training institute for ...C,c++,java,php,.net training institute in delhi, best training institute for ...
C,c++,java,php,.net training institute in delhi, best training institute for ...MCM COmpetitive Classes
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introductionjyoti_lakhani
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxSuganthiDPSGRKCW
 
Lec 1-of-oop2
Lec 1-of-oop2Lec 1-of-oop2
Lec 1-of-oop2SM Rasel
 
Java Tutorial to Learn Java Programming
Java Tutorial to Learn Java ProgrammingJava Tutorial to Learn Java Programming
Java Tutorial to Learn Java Programmingbusiness Corporate
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
C# vs Java What are The Differences.pdf
C# vs Java What are The Differences.pdfC# vs Java What are The Differences.pdf
C# vs Java What are The Differences.pdfchristiemarie4
 
Java training in bangalore
Java training in bangaloreJava training in bangalore
Java training in bangalorezasi besant
 

Similar to java full 1 (Recovered).docx (20)

Features of Java.pptx
Features of Java.pptxFeatures of Java.pptx
Features of Java.pptx
 
Java.pptx
Java.pptxJava.pptx
Java.pptx
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
C,c++,java,php,.net training institute in delhi, best training institute for ...
C,c++,java,php,.net training institute in delhi, best training institute for ...C,c++,java,php,.net training institute in delhi, best training institute for ...
C,c++,java,php,.net training institute in delhi, best training institute for ...
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
1 java introduction
1 java introduction1 java introduction
1 java introduction
 
1 java intro
1 java intro1 java intro
1 java intro
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
Java (1)
Java (1)Java (1)
Java (1)
 
Lec 1-of-oop2
Lec 1-of-oop2Lec 1-of-oop2
Lec 1-of-oop2
 
Getting Started with JAVA
Getting Started with JAVAGetting Started with JAVA
Getting Started with JAVA
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Java Tutorial to Learn Java Programming
Java Tutorial to Learn Java ProgrammingJava Tutorial to Learn Java Programming
Java Tutorial to Learn Java Programming
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
C# vs Java What are The Differences.pdf
C# vs Java What are The Differences.pdfC# vs Java What are The Differences.pdf
C# vs Java What are The Differences.pdf
 
Java training in bangalore
Java training in bangaloreJava training in bangalore
Java training in bangalore
 

More from SATHYAKALAKSKPRCASBS (8)

java completed units.docx
java completed units.docxjava completed units.docx
java completed units.docx
 
java full.docx
java full.docxjava full.docx
java full.docx
 
java full 1.docx
java full 1.docxjava full 1.docx
java full 1.docx
 
Personal Information.docx
Personal Information.docxPersonal Information.docx
Personal Information.docx
 
Presentation1.pdf
Presentation1.pdfPresentation1.pdf
Presentation1.pdf
 
Friend function by sathya.docx
Friend function by sathya.docxFriend function by sathya.docx
Friend function by sathya.docx
 
hjdh.docx
hjdh.docxhjdh.docx
hjdh.docx
 
Contact Information.docx
Contact Information.docxContact Information.docx
Contact Information.docx
 

Recently uploaded

8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCRashishs7044
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth MarketingShawn Pang
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
BEST Call Girls In Greater Noida ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Greater Noida ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Greater Noida ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Greater Noida ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,noida100girls
 
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadIslamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadAyesha Khan
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCRashishs7044
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMintel Group
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncrdollysharma2066
 
Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africaictsugar
 
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In.../:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...lizamodels9
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...ictsugar
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst SummitHolger Mueller
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024christinemoorman
 
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130  Available With RoomVIP Kolkata Call Girl Howrah 👉 8250192130  Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Roomdivyansh0kumar0
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...lizamodels9
 

Recently uploaded (20)

8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
BEST Call Girls In Greater Noida ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Greater Noida ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Greater Noida ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Greater Noida ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
 
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadIslamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 Edition
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
 
Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africa
 
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In.../:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst Summit
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024
 
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130  Available With RoomVIP Kolkata Call Girl Howrah 👉 8250192130  Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
 

java full 1 (Recovered).docx

  • 1. UNIT I chapter 2 : Java Evolution 1. Java History 2. Java Features 3. How Java differs from C and C++ 4. Java and Internet 5. Java and World Wide Web 6. Web Browsers 1. Java History • Java is a general-purpose, OOP language developed by Sun Microsystems of USA in 1991. • Originally called Oak by James Gosling • Java was originally designed for the development of Software for Consumer electronic devices like TVs, VCRs… Goal : Make the language simple, portable and highly reliable. • Java team included the existing languages like C & C++. • But it had limitations in terms of both reliability and portability. • They modeled their new language Java on C & C++ • But removed number of features of C & C++ • And made Java a really simple, reliable, portable and powerful language. 2. Java Features • The inventors of Java wanted to design a language which could offer solutions to some of the problems encounte modern programming •The Java not only reliable, portable and distributed but also simple, compact and interactive. (Table diagram) b) Platform-Independent and Portable •The most significant features of Java is its portability. •Java programs can be easily moved from one computer system to another, anywhere and anytime.
  • 2. •Changes and upgrades in Oss, Processors and System resources will not force any changes in Java programs. •This is the reason java has become a popular language for programming on Internet which interconnects different k systems worldwide. •We can download a Java applet from a remote computer onto our local system via internet and execute it locally. b) Platform-Independent and Portable • The most significant features of Java is its portability. • Java programs can be easily moved from one computer system to another, anywhere and anytime. • Changes and upgrades in Oss, Processors and System resources will not force any changes in Java programs • This is the reason java has become a popular language for programming on Internet which interconnects diff kinds of systems worldwide. • We can download a Java applet from a remote computer onto our local system via internet and execute it loc • Java ensures portability in 2 ways • First, Java compiler generates bytecode instructions that can be implemented on any machine. • Secondly, the size of the primitive data types are machine-independent. Java ensures portability in 2 ways • First, Java compiler generates bytecode instructions that can be implemented on any machine. • Secondly, the size of the primitive data types are machine-independent. c) Object-Oriented • Java is a true OO language. • Almost everything in Java is an Object. • All program code and data reside within objects and classes. • Java comes with an extensive set of lasses, arranged in packages, that can use in our programs by inheritance. • The Object model in Java is simple and easy to extend. d) Robust and Secure Robust
  • 3. • Java is a robust language. • It provides many safeguards to ensure reliable code. • It has strict compile time and run time checking for data types. • It is designed as a garbage-collected language relieving the programmers virtually all memory management problems. • Java also incorporates the concept of Exception handling which captures serious and eliminates any risk of crashing the system. Security • It becomes an important issue for a language that is used for programming on Internet. • Threat of Viruses and abuse of resources are everywhere. • Java systems not only verify all memory access but also ensure that no viruses are communicated with an ap • The absence of pointers in Java ensures that programs cannot gain access to memory locations without prope authorization. e) Distributed • Java is designed as a distributed language for creating applications on networks. • It has the ability to share both data & programs • Java applications can open & access remote a bjects on Internet as easily as they can do in a local system. • It enables multiple programmers at multiple remote locations to collaborate and work together on a single projec f) Simple, Small and Familiar Simple & Small • Java is a small and simple language. • Many features of C & C++ that are earlier redundant or sources of unreliable code are not part of java. • Ex: no pointers, processor header files, goto and many others. • Also eliminates Operator Overloading and multiple inheritance. Familiar • To make the language look familiar to the existing programmers. • It was modeled on C & C++ languages.
  • 4. • It used many constructs of C & C++ • In fact, Java is a simplified version of C++. g) Multithreaded and Interactive • Multithreaded means handling multiple tasks simultaneously. • Java supports multithreaded programs • We need not wait for the application to finish one task before beginning another. • It improves the interactive performance of graphical applications. • The Java runtime comes with tools that support multiprocess synchronization and construct smoothly running interactive systems. h) High Performance • Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode. • Java speed is comparable to the native C/C++. • Java architecture is also designed to reduce overheads during runtime. • The incorporation of multithreading enhances the overall execution speed of Java programs. i) Dynamic and Extensible • Java is a dynamic language. • Java is capable of dynamically linking in new class libraries, methods, and objects. • Java can also determine the type of class through a query, making it possible to either dynamically link or abort t program, depending on the response. • Java programs support functions written in other languages such as C & C++. • These functions known as native methods. • This facility enables the programmers to use the efficient functions available in these languages. • Native methods are linked dynamically at runtime. II) Additional Features of J2SE 5.0 a) Ease of Development • Java 2 Standard Edition (J2SE) 5.0 supports features, such as Generics, enhanced for Loop. Autoboxing or unbox Typesafe Enums, Varargs, Static import and Annotation.
  • 5. • It reduce the work of the programmer by shifting the responsibility ofcreating the reusable code to the compiler. • The resulting source code is free from bugs because the errors made by the compiler are less when compared to t made by programmers. • Thus, each of the linguistic features is designed to develop java programs in a easier way. b) Scalability and Performance • J2SE 5.0 assures a significant increase in scalability and perfoemance by improving the startup time and reducing amount of memory used in Java 2 runtime environment. • For example, the introduction of the class, data sharing in the Hotspot Java Virtual Machine(JVM) improves the time by loading the core classes from the jar files into a shared archive. • Memory utilization is reduced by sharing data in the shared archive multiple JVM processes. c) Monitoring and Manageability • Java supports a number of APIs, such as JVM Monitoring and Management API, Sun Management Platform Extension, Logging, Monitoring and Management Interface and Java Management Extension (JMX) to monitor a mange java applications. d) Desktop client • J2SE 5.0 provides enhanced features to meet to meet the requirements and challenges of the java desktop users. • It provides an improved Swing look and feel called Ocean. • This feature is mainly used for developing graphics applications that require OpenGL hardware acceleration. • Miscellaneous Features J2SE 5.0 supports the following features: e) Core XML Support • J2SE 5.0 adds a powerful XML feature to the Java platform. • Java contains some special packages for interface to instantiate Simple API for XML(SAX) and Document Obje Model (DOM) parsers to parse an XML document, transform the content of an XML document, and validate an X document against the schema. f) Supplementary Character Support • Java adds the 32-bit supplementary character support as part of the Unicode 4.0 support.
  • 6. • The supplementary characters are encoded with UTF-16 values to generate a different character called surrogate point. g) JDBC RowSet • To send data in a tabular format between the remote components of a distributed enterprise application. • Contains CacheRowSet & WebRowSet. • This object contains a number of rows of data, which are retrieved from the database. • The data stored in the CacheRowtSet can be directly accessed without connecting to the database or any other da source. • The rows of data that are retrieved from the database can be synchronized later. • The WebRowSet object can operate without being connected to the database or data source and it uses XML form read and write the rowset. • III) Enhancement in Java SE 6 • Some of the Key enhancements in Java SE 6 are : • a) Scripting Language Support • Java SE 6 integrates various scripting languages such as Java Script and PHP Script into the Java platform. • It allows scripts to be embedded in Java programs and compiled and executed with the help of appropriate scripti engine. • b) XML Processing and Web services • It allows development of web services and clients that communicate using XML • c) JDBC 4.0 Support • For developing database-centric applications • As a result, programmers can leverage the various features of JDBX 4.0 such as automatic loading of JDBC driv class, connection management features etc., • d) Annotation-based Programming • It allows programmers to define annotations(meta-tags) for various program elements so that the same can be use the compiler or other tools to generate ready code whenever necessary. • e) Dynamic compilation
  • 7. • The Java compiler API allows dynamic compilation of Java source code form a running Java application. IV) Enhancement in Java SE 7 Some of the Key enhancements in Java SE 7 are : a) Language Enhancements • Java SE 7adds several language features aimed at helping the programmers implement difficult functionality ease. • The new language features include strings in switch statement, multiple handling, diamond syntax etc. b) NIO 2.0 • The new file system API(NIO 2.0) in Java SE 7 makes it a lot easier to work with the systems. • It contains several enhancements to the standard file operations such as open, read, write etc. • In addition, it also allows the programmers to create custom file systems. c) Parallel Programming • Java SE 7 facilitates Parallel Programming through the use of Fork/join Framework. • While the conventional multithreaded programming allowed programmers to use a single processor for multitasking. d) Dynamic Language Support • The Java SE 7 supports dynamically typed languages in the JVM. • The invoked dynamic instruction is used to define customized linkage mechanisms for these languages. 3. How Java Differs from C and C++ • Although Java was modeled after C & C++languages • It differs from C and C++ in many ways • Java does not incorporate a number of features available in C & C++. • For the benefit of C & C++ programmers, we point out here a few major differences between C/C++ & Java languages. Java and C
  • 8. Major Difference : • Java is an OOP and has mechanism to define classes and objects. • In an effort to build a simple and safe language, the java team did not include some of the C features in Java i) Java does not include the C unique statement keywords sizeof and typedef. ii) Java does not contain the data types strut and union. iii) Java does not define the type modifiers keyword auto, extern, register, signed and unsigned. iv) Java does not support an explicit pointer type. v) Java does not have a preprocessor and therefore we cannot use #define, #include and #ifdef statements. vi) Java requires that the functions with no arguments must be declared with empty parenthesis and not with the keyword as done in C. vii) Java adds new operators such as instance of and >>>. viii) Java adds labeled break and continue statements. ix) Java adds many features required for OOP. Java and C++ Major Difference : • Java is an true OOP language while C++ is basically C with OO extension. i) Java does not support operator overloading. ii) Java does not have template classes as in C++. iii) Java does not support multiple inheritance of classes. But it is accomplished using new feature called “interf iv) Java does not support global variables. Every variable and method is declared within a class and form part o class. v) Java does not use pointers. vi) Java has replaced the destructor function with a finalize( ) function. vii) There are no header files in Java. Java also add some new features :
  • 9. • While C++ is a superset of C • Java is neither a superset nor a subset of C or C++. • Java may be considered as a first cousin of C++ and a second cousin of C. Diagram Overlapping of C, C++ and Java 4. Java and Internet • Java is strongly associated with the Internet because of the fact that the first application program written in J was HotJava, a Web browser to run applets on Internet. • Internet users can use Java to create applet programs and run them locally using a “java-enabled browser” su HotJava. • They can also use a Java-enabled browser to download an applet located on a computer anywhere in the inte and run it on his local computer. • In fact, java applets have made the Internet a true extension of the storage system of the local computer. • Internet users can also set up their web sites containing Java applets that could be used by other remote users Internet. • The ability of Java applets to hitch a ride on the information superhighway has made Java a unique program language for the Internet. • Java is popularly known an Internet language. Diagram 5. Java and WWW WWW • WWW is an open-ended information retrieval system designed to be used in the internet’s distributed environment. • Contains web pages that provide both information and controls. • Unlike a menu-driven system where we are guided through a particular direction using a decision tree structu • The web system is open-ended and we can navigate to a new document in any direction. • It is made possible with the help of a language called HTML
  • 10. • Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents worldwide Diagram • Java was meant to be used in distributed environment such as internet. • Since, both the Web and Java share the same philosophy, java could be easily incorporated into the web syst • Before java, the WWW limited to the display of still images and texts. • However, the incorporation of java into web pages has made it capable of supporting animation, graphics, ga and a wide range of special effects. • With the support of java , the web has become more interactive and dynamic. • We can run a java program on someone else’s computer across the internet. Diagram Communication Steps • The user sends a request for an HTML document to the remote computer’s web server. The web server is a program that accepts a request, and sends the required document. • The HTML document is returned to the user’s browser. The document contains the APPLET tag, which iden the applet. • The corresponding Applet bytecode is transferred to the user’s computer. This bytecode had been previously created by the java compiler using the java source code file for that applet. • The java-enabled browser on the user’s computer interprets the bytecodes and provides output. • The user may have further interaction with the applet but with no further downloading from the provider’s w server. This is because the bytecode contains all the information necessary to interpret the applet. 6. Web Browsers • The internet is a vast sea of information in many formats and stored on many computers. • A large portion of the internet is organized as the WWW which uses hypertext. • Web Browsers are used to navigate through the information found on the net. • They allow us to retrieve the information spread across the internet and display using the HTML. • Examples
  • 11. i) HotJava ii) Netscape Navigator iii) Internet Explorer i) HotJava • is the web browser from Sun Microsystems that enables the display of interactive content on the Web using Java Language. • Written entirely in Java and demonstrates the capabilities of the java programming language. • When the java language was first developed and ported to the Internet, no browsers were available that could java applets. • Although we can view a web page that includes java applets with a regular browser, we will not gain any of benefits. ii) Netscape Navigator • From netscape communication corporation, is a general-purpose browser that can run java applets. • With version available for Windows, Solaris and Apple Macintosh, Netscape Navigator was one of the most widely used browsers of its time. • But with increasing popularity of IE browser, the use of NN decreased over a period of time. • Even Netscape communication has stopped further development of this browser after its latest stable release March 2008 iii) Internet Explorer • It is another popular browser developed by Microsoft for Windows 95, NT and XP workstations. • Both the NN & IE use tool bars, menus and dialog boxes for easy navigation. • IE uses a just-in-time(JIT) compiler which greatly increases the speed of execution. 7. H/W & S/W Requirements : • Platform – Solaris, windows intel architecture 32-bit, Linux 32-bit etc., • Memory - 64/128 MB • Browsers – Mozila, IE
  • 12. • Disk Space – 98/110/58/56 MB 8. Java Support Systems : • Internet connection • Web Server • Web Browser • HTML • APPLET Tag • Java Code • Byte code • Proxy server • Mail Server 9. Java Environment : i) JDK (Java Development Kit) comes with a collection of tools that are used for developing and running java programs. • Appletviewer – for viewing java applets • Javac – java compiler • Java – java interpreter • Javap – jave disassembler • Javah – for C header files • Javadoc – for creating HTML documents • Jdb – java debugger ii) API (Application Programming Interface) includes 100s of classes and methods grouped into several functional packages. • Language support Package – implementing basic features of Java • Utilities Package – provide utility functions such as date and time functions
  • 13. • I/O Package – for I/O manipulation • Networking Package – for communicating with other computers via the internet • AWT Package – implements platform-independent GUI • Applet Package – allows us to create java applets iii) JRE (Java Runtime Environment) facilitates the execution of programs developed in Java • JVM – it is a program that interprets the intermediate Java byte code and generates the desired o/p. • Runtime class libraries – a set of core class libraries that are required for the execution of java programs. • User interface toolkit – support varied i/p methods for the users to interact with the application program. • Deployment technologies – comprises a) Java plug-in – enbles the execution of a java applet on the browser b) Java web start – enables remote-deployment of an application. OVERVIEW OF JAVA LANGUAGE To create a simple java program, you need to create a class that contains main method. Let's understand the requirement first. REQUIREMENT FOR HELLO JAVA EXAMPLE: For executing any java program, you need to • install the JDK if you don't have installed it, download the JDK and install it. • set path of the jdk/bin directory. • create the java program • compile and run the java program CREATING HELLO JAVA EXAMPLE : class Simple{ public static void main(String args[]){ System.out.println("Hello Java");
  • 14. } } save this file as Simple.java To compile : javac Simple.java To execute :java Simple JAVA PROGRAM STRUCTURE • Let’s use example of HelloWorld Java program to understand structure and features of class. • This program is written on few lines, and its only task is to print “Hello World from Java” on the screen. Refer th following picture. 1.“PACKAGES”: 2. “PUBLIC CLASS HELLOWORLD”: 3. COMMENTS SECTION: 4. “PUBLIC STATIC VOID MAIN (STRING [ ] ARGS)”: 5. SYSTEM.OUT.PRINTLN("HELLO WORLD FROM JAVA") JAVA TOKENS • A Java program is basically a collection of classes. • A class is defined by a set of declaration statements and methods containing executable statements. • Most statements contain expressions, which describe the actions carried out on data. • Smallest individual unit in a program are known as tokens. • The compiler recognizes them for building up expressions and statements. 5 Types of Tokens
  • 15. i. Reserved keywords ii. Identifiers iii. Literals iv. Operators v. Separators Diagram JAVA CHARACTER SET • The smallest units of Java language are the characters used to write Java tokens. • These characters are defined by the Unicode character set. • Emerging standard that tries to create characters for a large number of scripts worldwide. • The Unicode is a 16-bit character coding system and currently supports more than 34,000 defined characters. • That is derived from 24 languages KEYWORDS IN JAVA • Java Keywords also called a reserved word. Keywords are identifiers that Java reserves for its own use. • Since keywords have specific meanings • These identifiers have built-in meanings that cannot change. • There are 50 reserved keywords currently defined in the Java language and they are shown in the below table. • Eg. Boolean, interface, abstract • We cannot use them as names for variables, classes, methods etc.,. JAVA STATEMENT: • Statements are roughly equivalent to sentences in natural languages. • A statement is an executable combination of token ending with a semicolon(;) mark. • A statement forms a complete unit of execution. • The following types of expressions can be made into a statement by terminating the expression with a semicolon • Statements are usually executed in sequence in the order in which they appear.
  • 16. • So it control flow of execution • If necessary , using special statements. • Assignment expressions • Any use of ++ or -- • Method invocations • Object creation expressions • Such statements are called expression statements. • Here are some examples of expression statements. // assignment statement aValue = 8933.234; // increment statement aValue++; // method invocation statement System.out.println("Hello World!"); // object creation statement Bicycle myBike = new Bicycle(); Diagram Statement Description Remarks Empty Statement These do nothing and are used during program development as a place holder Same as C & C++ Labelled Statement Any Statement may begin with a lebel. Such label not be keywords Identical to C & C++ except jump
  • 17. Summary of Java Statements : 2 Diagrams WHAT JVM DOES? The JVM performs following operation: Loads code Verifies code Executes code Provides runtime environment JVM provides definitions for the: Expression Statement Most Statements are expression Statements. 7 Types : Assignment, Pre-increment, Pre-Decrement, post-increment. Post- Decrement, Method call and Allocation Expression Same as C++ Selection Statement Select one of several control flows: if, if-else. Same as C & C++ Iteration Statement How and when looping will take place Identical to C & C++ except jump& label Jump Statement Pass control to the beginning or end of the current block C & C++ do not use labels with jump Synchronization Statement These are used fro handling issues with multithreading Now available in C & C++ Guarding Statement For safe handling of code that may cause exceptions. Try, catch, finally… Same as in C++ except finally statement
  • 18. Memory area Class file format Register set Garbage-collected heap Fatal error reporting etc. VARIABLES IN JAVA 1. Introduction 2. Declaration of Variables 3. Giving Values to Variables 4. Scope of Variables 5. Getting Values of variables 6. Standard Default Values 7. Type casting 1. INTRODUCTION : • A variable is an identifier that denotes a storage location used to store a data value. • Constants – that remain unchanged during the execution of a program • Variable – may take different values of different times during the execution of the program • variable is chosen by the programmer in a meaningful way. • Consists of alphabets, digits, underscore and dollar characters Conditions : • They must not begin with a digit • Uppercase & Lowercase are distinct. • Not be a keyword • White space is not allowed
  • 19. • Any length 2. Declaration of Variables : • Variables hold one value at a time, but that value can change • After defining suitable names, declare them to the compiler. 3 things i. It tells the compiler what the variable name is ii. Specifies type of the data variable iii. Scope of the variable Syntax: dataType identifier; or dataType var1, var2, … varn; • Variables are separated by commas Ex: int x; float y; 3. Giving Values to Variables : A variable must be given a value after it has been declared but before used Achieved in 2 Ways : i) By using an Assignment statement ii) By using a read statement By using an Assignment statement - A simple method of giving value to a variable Syntax: variableName = value;
  • 20. Ex : x = 5; - Also possible to assign a value to a variable at the time of declaration Syntax: type variableName = value; Ex : int x = 5; By using a read statement - through the keyboard using the readLine( ) method Ex : System.out.printline(“Enter vale”); x = Integer.parseInt(in.readLine( )); readLine( ) – reads the i/p from the keyboard as a string which is then converted to the corresponding data ty using the data type wrapper classes. i) By using a read statement Reading I/p from Keyboard a) Use System.Console class – to read lines Ex : System.out.printline(“Enter value”); int x = System.Console().readLine( ); System.out.printline(“The valu is :” + x); b) Use java.util.Scanner class and System.in Ex : Scanner sc=new Scanner(System.in); String s = sc.nextLine(); -> read the line System.out.println(“ the string is” + s); By using a read statement Reading I/p from Keyboard c) Use BufferedReader class – to read lines Ex : InputStreamReader isr = new InputStreamReader(System.in)
  • 21. BufferedReader br = new BufferedReader(isr); 4. Scope of Variables : 3 Kinds : a) instance variables b) class variables c) local variables Instance and class variables are declared inside a class a) instance variables - created when the objects are instantiated and they are associated with the objects. - take different values for each objects. b) class variables - global to a class & belong to the entire set of objects that class creats - only one memory location is created. c) local variables - variables declared and used inside methods are called local variables -not available for outside the method definition -declared inside a program blocks - defined b/w { } . 5. Getting Values of Variables : Java supports 2 o/p methods - i) print( ) method - ii) println( ) method i) print( ) method - sends information into a buffer
  • 22. -This buffer is not flused until a newline character in sent - prints o/p on one line until a ne is encountered Ex : System.out.print(“Hi”); ii) println( ) method - stake the information provided displays it on a line followed by a line f Ex : System.out.println(“Hi”); 6. Standard Default Variables : - Every variable has a default valu Type of variable Default value byte Zero:0 short Zero:0 int Zero:0 long Zero:0L float 0.0f double 0.0d char null character boolean false
  • 23. 7. TYPE CASTING : - To store a value of one type into a variable of another type Syntax: type var1 = (type) var2; Ex : int m = 10; byte n = (byte) m; Automatic Conversion - assign a value of one type to a variable of a different type without a cast. - the conversion of the assigned value automatically known as automatic-type conversion Ex : byte b =10; int a =b; From To byte Short, char, int, long, float, double short Int, long, float, double char Int, long, float, double int long, float, double reference null
  • 24. long float, double float double VARIABLE ARGUMENT (VARARGS): The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach. ADVANTAGE OF VARARGS: WE DON'T HAVE TO PROVIDE OVERLOADED METHODS SO LESS CODE. SYNTAX OF VARARGS: The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows: 1. return_type method_name(data_type... variableName){} SIMPLE EXAMPLE OF VARARGS IN JAVA: 1. 2. class VarargsExample1{ 3. 4. static void display(String... values){ 5. System.out.println("display method invoked "); 6. } 7. 8. public static void main(String args[]){ 9. 10. display();//zero argument 11. display("my","name","is","varargs");//four arguments 12. } 13. } 14. Test it Now Output:display method invoked display method invoked ANOTHER PROGRAM OF VARARGS IN JAVA:
  • 25. 1. 2. class VarargsExample2{ 3. 4. static void display(String... values){ 5. System.out.println("display method invoked "); 6. for(String s:values){ 7. System.out.println(s); 8. } 9. } 10. 11. public static void main(String args[]){ 12. 13. display();//zero argument 14. display("hello");//one argument 15. display("my","name","is","varargs");//four arguments 16. } 17. } 18. Test it Now Output:display method invoked display method invoked hello display method invoked my name is varargs download this example Rules for varargs: While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows: o There can be only one variable argument in the method. o Variable argument (varargs) must be the last argument.
  • 26. EXAMPLES OF VARARGS THAT FAILS TO COMPILE: 1. 2. void method(String... a, int... b){}//Compile time error 3. 4. void method(int... a, String b){}//Compile time error 5. EXAMPLE OF VARARGS THAT IS THE LAST ARGUMENT IN THE METHOD: 1. 2. class VarargsExample3{ 3. 4. static void display(int num, String... values){ 5. System.out.println("number is "+num); 6. for(String s:values){ 7. System.out.println(s); 8. } 9. } 10. 11. public static void main(String args[]){ 12. 13. display(500,"hello");//one argument 14. display(1000,"my","name","is","varargs");//four arguments 15. } 16. } 17. Test it Now Output:number is 500 hello number is 1000 my name is varargs Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs.
  • 27. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body } In order to define vararg, ... (three dots) is used in the formal parameter of a method. A method that takes variable number of arguments is called a variable-arity method, or simply a varargs method. First, let’s look at the example without using varargs: class NoVararg { public int sumNumber(int a, int b){ return a+b; } public int sumNumber(int a, int b, int c){ return a+b+c; } public static void main( String[] args ) { NoVararg obj = new NoVararg(); System.out.println(obj.sumNumber(1, 2)); System.out.println(obj.sumNumber(1, 2, 3)); } } When you run this program, the output will be: 3 6 As you can clearly see, you had to overload sumNumber() method to make it work for 3 arguments. THINGS TO REMEMBER WHILE USING VARARGS Here are a couple of things you should remember while working with Java vargars:
  • 28. 1. While defining method signature, always keep varargs at last. The variable argument must be the last argument passed to the method. Let's consider, you invoked doSomething() method like this: doSomething(1, 2, 3, 4); And, your doSomething() method is defined as: // incorrect method declaration public void doSomething(int ... nums, int p){ // method body } In this case, compiler cannot figure out the number of arguments passed to nums. However, if you define your method as: public void doSomething(int p, int ... nums) { // method body } The Java compiler assigns the first argument to p, and the remaining int arguments are assigned to nums. 2. A method can have only one varargs parameter. For example, this method declaration is incorrect: int doSomething(int p, float ... floatNums, double ... doubleNums) { // code } AMBIGUITY IN VARARGS METHOD OVERLOADING Let’s consider you overloaded test() method like this: class Demo { static void test(int ... vargs) { // method body
  • 29. } static void test(int n, int ... vargs) { // method body } } In the above program, the compiler gets confused if you try to invoke the test() method even though test() methods are overloaded and accepts different number of arguments. OPERATORS IN JAVA : 2 ) 1 ) 3 )
  • 30. 4 ) 5 ) 6 ) 7) 8 )
  • 31. 9 ) 10 ) 11 ) 1 13 )
  • 32. 14
  • 34. 18 ) EXPRESSIONS IN JAVA : Definition : • An expression in java is a combination of operators , variables ,constants & method invocations. • Expression is used to perform the computation indicated by the elements of the expression and return some value. Example : int a=5; // returns 5 if(a==b) // returns Boolean value c = a + b; // returns a manipulated values System.in.read(); // evaluate a single value TYPES OF EXPRESSIONS : There are three types of expressions in java. They are,
  • 35. 1. Expression that produce a value 2. Expression that assign a variable 3. Expressions with no result EXPRESSIONS THAT PRODUCE A VALUE : • It uses operators to produce a value such a Arithmetic operators ,Conditional operator, Comparison operator , etc… • Example: C=3+2 A=10/5 B= 2*4/5 EXPRESSIONS THAT ASSIGN A VARIABLE : • It is a expression that assigns a value to the variable. • Example: Int A=0; // assigns integer value B= true; // assigns boolean value EXPRESSIONS WITH NO RESULT : • Some expressions does not produce result but give a side effect which occurs when an expression changes the Value of an operands. • Example: P = a*b; Here value of variable ‘p’ is changed when calculated , but value of variable ‘a’ and ‘b’ does not change. This is called side effect. • a++ • Here ,value of variable ‘a’ is changed according to the program. Unit – II
  • 36. Classes, Objects and Methods 1. Introduction 2. 2. Defining a Class 3. Methods Declaration 4. Creating Objects 5. Accessing Class Members 6. Constructors 7. Method Overloading 8. Static Members 9. Nesting of Methods 10. Inheritance : Extending a Class 11. Overriding Methods 12. Final Variables and Methods 13. Final Classes 14. Finalizer Methods 15. Abstract Methods and Classes 16. Methods with Varargs 17. Visibility Control INTRODUCTION : • Java is a true OOPL • The underlying structure of all Java programs is classes. • Anything represented in a class • Class defines the state and behavior of the basic program components known as objects • Classes create objects and objects use methods to communicate between them
  • 37. • Classes provide a convenient method for packing together a group of logically related data items and functions • In Java The data items are called fields and the functions are called methods. DEFINING A CLASS : • A class is a user-defined data type with a template that serves to define its properties • These variables are called instance variables because they are created whenever an object of the class is instantiated. Ex : class A { int length; Int width; } 3. FIELDS DECLARATION : • Data is encapsulated in a class by placing data fields inside the body of the class definition • Once the class type has been defined, we can create variables of that type using declarations that are similar to the basic-type declarations. • These termed as instances of classes, which are the actual objects. Syntax class classname [extends superclasname] { [ fields declaration; ] [methods declaration;] } Ex : class A { } 4. METHODS DECLARATION : • A class with only data fields & without methods that operate on that data has no life.
  • 38. • The objects created by such a class cannot respond to any messages. Syntax type methodname (parameter-list) { Method-body; } 4 basic parts : i) The name of the method – method name ii) The type of the value the method returns – type iii) A list of parameters(parameter-list) iv) The body of the method Ex : Class Rect { Int len, wid; Void getdata(int x, int y) { len=x; Wid=y; } } 5. CREATING OBJECTS : • An object in java is essentially a block of memory that contains space to store all the instance variables. • object in java are created using the new operator • The new operator creates an object of the specified class and returns a reference to that object. Ex: Rect r1; R1=new Rect( );
  • 39. (or) Rect r1 = new Rect( ); Diagram Diagram 6. ACCESSING CLASS MEMBERS : • All variables must be assigned values before they are used. • Outside of the class cannot access the instance variables and methods directly. • so, we must use the concerned object and the dot operator Syntax : objectname.variablename = value; objectname.methodname(parameter-list); Variablename -> name of the instance variable inside the object we wish to access Methodname -> the method we wish to call Parameter list-> actual values that must match in type and number Ex: Rect r1 = new Rect( ); Rect r2=r1; r1.getdata(25, 30) r1.length = 10; r2.length = 12; Ex: void getdata(int x, int y) { length = x; width = y; } ….main( ) { Rect r1 = new Rect( ); r1.getdata(25, 30) } 7. CONSTRUCTORS : 2 approaches ( objects created) : i) Uses the dot operator to access the instance vars & assign values to them immediately.
  • 40. - difficult to initialize all the vars to all the objs ii) Takes the help of a method like r1.getdata(15,20); - simple one iii) But java supports special type of method called a constructor. - It enables an object to initialize itself when it is created. Constructor : • Have the same name as the class itself • Do not specify a return type not even void • Because it return the instance of the class itself. Ex : class Rect { int length; int width; Rect(int x, int y) { length = x; width = y; } int rectArea() { return(length * width); }} 8. METHOD OVERLOADING : Definition – Method Overloading In java, possible to create methods that have the same name, but different parameter lists and different definitions. T called method overloading. • It is used when objects are required to perform similar task but using different input parameters • When we call a method, it follows - first matches the method name - then the number of parameters - type of parameters • This process is known as polymorphism. • Ex : – Method Overloading
  • 41. class Rect { int length; int width; Rect(int x, int y) // Constructor 1 { length = x; width = y } Rect(int x) // Constructor 2 { length = width=x; } int rectArea() { return(length * width); }} 9. STATIC MEMBERS : Class contains 2 sections i) declares variables ii) declares methods - these variables & methods are called instance variables & instance methods. - because every time the class is instantiated, a new copy of each of them is created. - they are accessed using the objects with dot operator. • Assume, we want to define a member that is common to all the objects and accessed without using a particular object. • ie., the member belongs to the class as whole rather than the objects created from the class. Ex: static int c; static int area(int x, int y); - the members are declared as static are called static members. - these members associated with the class itself rather than individual objects. - the static vars & methods referred to as class vars & methods. - Static vars are used when we want to have a var common to all instances of a class. Ex :
  • 42. class Operation { static float mul(float x, float y) { return x*y; } static float div(float x, float y) { return x/y; }} Class MathOp { public void static main(String args[]) { float a = Operation.mul(5.0,2.0); float b = Operation.div(6.0,2.0); System.out.ptintln(“a=“+a); System.out.ptintln(“b=“+b) }} 10. NESTING OF METHODS : Def : A method can be called by using only its name by another method of the same class is known as nesting of methods. class Nest { int large() { …. } class display( ) { int l = large( ); } Class Ntest { public void static main(String args[]) { ….. } INHERITANCE IN JAVA : 1. Inheritance 2. Types of Inheritance 3. Why multiple inheritance is not possible in Java in case of class? Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).
  • 43. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Why use inheritance in java o For Method Overriding (so runtime polymorphism can be achieved). o For Code Reusability. Terms used in Inheritance o Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. The syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.
  • 44. Java Inheritance Example As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Test it Now Programmer salary is:40000.0 Bonus of programmer is:10000 In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
  • 45. Note: Multiple inheritance is not supported in Java through class. When one class inherits multiple classes, it is known as multiple inheritance. For Example: Single Inheritance Example When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance. TestInheritance.java class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking..."); } } class TestInheritance{ public static void main(String args[]) { Dog d=new Dog(); d.bark(); d.eat(); }} Output: barking... eating...
  • 46. Multilevel Inheritance Example When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }} Output: weeping... barking... eating... Hierarchical Inheritance Example When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. TestInheritance3.java class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class Cat extends Animal{
  • 47. void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//C.T.Error }} Output: meowing... eating... Q) Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{//suppose if it were public static void main(String args[]){ C obj=new C(); obj.msg();//Now which msg() method would be invoked? } } Test it Now Compile Time Error
  • 48. Method Overriding Method Overloading and Method Overriding are the topics that should be on your to-do list before appearing for the interview. In this post, I will share what is method overriding, the rules of method overriding, and examples. So let's dive in and understand method overriding in java. What is Method Overriding When the child class(subclass) has the method which has the same name, same parameters and same return type (or covariant return type) as a method in its parent class(or super-class), then the child method has overridden the parent class method. Runtime polymorphism can be achieved through method overriding. Remember that at runtime, Object type (not reference variable's type) determines which overridden method is used. If the parent class object is used to invoke the method, then the parent class method will be executed. Otherwise, if, a child class object is used to invoke the method, then the child class method will be executed. Example of Method Overriding // Method Overriding Example //Base class class Parent { public void display() { System.out.println("parent method is executed"); }} //Derived or Inherited class class Child extends Parent { //Below method overrides the Parent display() method @Override public void display() { System.out.println("child method is executed"); }} //Driver class public class MethodOverriding1 { public static void main(String args[])
  • 49. { // If a Parent type reference refers // to a Parent object, then Parent's // display() is called Parent parentObject = new Parent(); parentObject.display(); // If a Parent type reference refers // to a Child object Child's display() // is called. This is called RUN TIME // POLYMORPHISM. Parent childObject = new Child(); childObject.display(); }} Output: parent method is executed child method is executed Rules for Method Overriding in Java 1. ACCESS MODIFIERS AND OVERRIDING The access level can't be more restrictive than the overridden method. The access level can be less restrictive than that of the overridden method. For example, a protected instance method in the parent class(superclass) can be made public but not private in the child class(subclass). If you try to make a child class private then it will give the compile-time..error.
  • 50. // Access Modifiers and Overriding Example //Base class class Parent { //Access modifier of parent's display() method is protected protected void display() { System.out.println("parent method is executed"); }} //Derived class class Child extends Parent { //Below method overrides the Parent display() method //Access modifier public is less restrictive than protected @Override public void display() { System.out.println("child method is executed"); } } //Driver class PublicclassMethodOverriding2{ public static void main(String args[]) { Parent parentObject = new Parent(); parentObject.display(); Parent childObject = new Child(); childObject.display(); }} Output : parent method is executed child method is executed 2. Private methods can not be overridden Another rule regarding access modifiers is you can not override private methods in the parent class. If subclass tries to override the private method of a parent class then the program will throw a compile-time error as shown below. // Access Modifiers and Overriding Example //Base class or Superclass class Parent { //Access modifier of parent method is private // This method can not override the child class method private void display() { System.out.println("parent method is executed"); }} //Derived class or Subclass class Child extends Parent { //Below method can not overrides the Parent display() method //This method is unique to the child class private void display() { System.out.println("child method is executed"); }} //Driver class public class MethodOverriding3 { public static void main(String args[]) { Parent parentObject = new Parent(); parentObject.display(); // this line when execute will throw compiler error
  • 51. Parent childObject = new Child(); childObject.display(); // this line when execute will throw compiler error }} 3. Final methods can not be overridden in Java You can not override a method marked final. It will throw a compile-time error if you try to do so. // Simple Java program showing // final methods cannot be overridden //Parent class or Superclass class Parent { // Can't be overridden final void display() { } } //Child class or Subclass class Child extends Parent { // This would produce compile time error void display() { } } Output : /Main.java:13: error: display() in Child cannot override display() in Parent void display() { } ^ overriddenmethodisfinal1error 4. Static methods can not be overridden You can not override a method mark static. If you define a static method in the subclass (child class) with the same method signature as the superclass(parent class) then it is called method hiding. // Method hiding example //Base class or SuperClass class Parent { static void display() { System.out.println("parent static method is executed"); } void show() { System.out.println("parent non-static (instance) method is executed"); }} //Derived class or SubClass class Child extends Parent {
  • 52. //This method hides the Parent display() method static void display() { System.out.println("child static method is executed"); } // This method overrides the Parent show() method void show() { System.out.println("child non-static (instance) method is executed"); }} //Driver Class public class MethodOverriding4 { public static void main(String args[]) { Parent childObject = new Child(); // static method can not be overridden, // so below line calls parent display() method childObject.display(); // Expected child method will run childObject.show(); }} Output: parent static method is executed child non-static (instance) method is executed 5. Invoking a superclass (Parent class) version of overridden method It's easy to call the superclass(Parent class) version of overridden method by using the super keyword. // Invoking SuperClass version of Overridden Method Example //Base class or SuperClass class Parent { void display() { System.out.println("parent method is executed"); } } //Derived class or SubClass class Child extends Parent { //This method overrides the Parent display() method @Override void display() { super.display();
  • 53. System.out.println("child method is executed"); } } public class MethodOverriding5 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(); } } Output : parent method is executed child method is executed 6. Overriding method must have the same return type (or Covariant return type) : The method return type must be the same, or a subtype of, the return type declared in the original overridden..method..in..the..superclass. Since java 5.0 it is made possible to have a different return type for an overriding method in a child class. But child's return type should be a subtype of the parent's return..type…This..phenomenon..is..called..covariant..return..type. Example of Covariant Return Type class Alpha { Alpha doStuff(char c) { return new Alpha(); }} class Beta extends Alpha { Beta doStuff(char c) { // legal override in Java 1.5 return new Beta(); }} public class MethodOverriding6 { public static void main(String args[]) { Alpha childObject = new Beta(); childObject.doStuff('a'); }} The above code will compile and run. 7. Constructor and Overriding You can not override the constructor as the constructor name of the base class and child class can never be the same. (Constructor name is always the same as the class name).
  • 54. 8. Exception Handling and Overriding Rule 1. The overriding method can throw any unchecked(runtime) exception regardless of whether the overridden method declares the exception. // Overriding when superclass does not throw an exception //Base class or SuperClass class Parent { //overridden method void display() { System.out.println("parent method is executed"); }} //Derived class or SubClass class Child extends Parent { //This method overrides the Parent display() method //It throws unchecked exception i.e Arithmetic Exception @Override void display() throws ArithmeticException{ System.out.println("child method is executed"); }} public class MethodOverriding7 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(); }} Output: child method is executed Rule 2. The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException can not be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException. Note : The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares. 9. Abstract method and Overriding Abstract methods can only be overridden by the first concrete class (classes that have no abstract methods) otherwise a compiler error will be thrown. //Abstract class abstract class Parent { public abstract void display( int x, String j); }
  • 55. //Subclass or Derived Class class Child extends Parent { @Override public void display( int x, String j ) { System.out.println("child method is executed"); }} //Driver class public class MethodOverriding8 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(1, "Alive is Awesome"); }} Output : child method is executed 10. Synchronized/strictfp method and Overriding Synchronized or strictfp methods do not have any impact on the overriding method. It's possible that a non- synchronized or non-strictfp method can override a synchronized/strictfp method or vice versa. MultiLevel Method Overriding in Java In the multilevel method overriding we create a grandchild class and override the display() method of the parent class. Let's find out what will happen if we perform runtime polymorphism in multilevel..overriding. // MultiLevel Overriding //Base class or SuperClass class Parent { //overridden method void display() { System.out.println("parent method is executed"); }} //Derived class or SubClass class Child extends Parent { //This method overrides the Parent display() method @Override void display() { System.out.println("child method is executed"); }} //Inherited Class class GrandChild extends Child { // This method overrides the Parent display() method @Override void display() { System.out.println("grand child method is executed"); }} //Driver Class public class MethodOverriding9 { public static void main(String args[])
  • 56. { Parent grandchildObject = new GrandChild(); grandchildObject.display(); }} Output: grand child method is executed Examples of Legal/Illegal Method Overrides Let's have a simple class Animal with the eat() method. public class Animal { public void eat() { } } Below is the list of the legal/illegal overrides of the Animal eat() method. 1. private void eat() {} - Illegal override code. Access modifier is more restrictive. 2. public void eat() throws IOException {} - Illegal override code. It declares a checked exception not defined by the superclass version. 3. public void eat(String food) {} - A legal overload, not an override because the argument list changed. 4. public String eat() {} - Not an override because of the return type, not an overload either because there's no change in the argument list. Advantages of Using @Override Annotation in the Code According…to Oracle…docs, @Override annotation informs the compiler that the element is meant to override an element declared in a..superclass. // mark method as a superclass method // that has been overridden @Override int overriddenMethod() { } While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error. Overloading vs Overriding
  • 57. 1. Overloading is an example of compile-time polymorphism while Overriding is an example of run- time…polymorphism. 2. In the method overloading parameters must be different. In overriding parameters must be the same (different…if…covarians…return…type). 3. Method overloading increases the readability of the program. Meanwhile, method overriding provides a specific implementation of the method. Difference between method overloading and method overriding in java : There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below: Method Overloading Method Overriding 1) Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. 2) Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. 3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. 4) Method overloading is the example of compile time polymorphism. Method overriding is the example of Run time polymorphism. 5) In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding. Java Method Overloading example
  • 58. class OverloadingExample{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } Java Method Overriding example class Animal{ void eat(){System.out.println("eating..."); } } class Dog extends Animal{ void eat(){System.out.println("eating bread..."); } } VARIABLES IN JAVA 1. Introduction 2. Declaration of Variables 3. Giving Values to Variables 4. Scope of Variables 5. Getting Values of variables 6. Standard Default Values 7. Type casting 1. INTRODUCTION : • A variable is an identifier that denotes a storage location used to store a data value. • Constants – that remain unchanged during the execution of a program • Variable – may take different values of different times during the execution of the program • variable is chosen by the programmer in a meaningful way. • Consists of alphabets, digits, underscore and dollar characters Conditions : • They must not begin with a digit • Uppercase & Lowercase are distinct. • Not be a keyword • White space is not allowed
  • 59. • Any length 2. Declaration of Variables : • Variables hold one value at a time, but that value can change • After defining suitable names, declare them to the compiler. 3 things iv. It tells the compiler what the variable name is v. Specifies type of the data variable vi. Scope of the variable Syntax: dataType identifier; or dataType var1, var2, … varn; • Variables are separated by commas Ex: int x; float y; 3. Giving Values to Variables : A variable must be given a value after it has been declared but before used Achieved in 2 Ways : iii) By using an Assignment statement iv) By using a read statement By using an Assignment statement - A simple method of giving value to a variable Syntax: variableName = value;
  • 60. Ex : x = 5; - Also possible to assign a value to a variable at the time of declaration Syntax: type variableName = value; Ex : int x = 5; By using a read statement - through the keyboard using the readLine( ) method Ex : System.out.printline(“Enter vale”); x = Integer.parseInt(in.readLine( )); readLine( ) – reads the i/p from the keyboard as a string which is then converted to the corresponding data ty using the data type wrapper classes. ii) By using a read statement Reading I/p from Keyboard b) Use System.Console class – to read lines Ex : System.out.printline(“Enter value”); int x = System.Console().readLine( ); System.out.printline(“The valu is :” + x); b) Use java.util.Scanner class and System.in Ex : Scanner sc=new Scanner(System.in); String s = sc.nextLine(); -> read the line System.out.println(“ the string is” + s); By using a read statement Reading I/p from Keyboard c) Use BufferedReader class – to read lines Ex : InputStreamReader isr = new InputStreamReader(System.in)
  • 61. BufferedReader br = new BufferedReader(isr); 4. Scope of Variables : 3 Kinds : a) instance variables b) class variables c) local variables Instance and class variables are declared inside a class a) instance variables - created when the objects are instantiated and they are associated with the objects. - take different values for each objects. b) class variables - global to a class & belong to the entire set of objects that class creats - only one memory location is created. c) local variables - variables declared and used inside methods are called local variables -not available for outside the method definition -declared inside a program blocks - defined b/w { } . 5. Getting Values of Variables : Java supports 2 o/p methods - i) print( ) method - ii) println( ) method i) print( ) method - sends information into a buffer
  • 62. -This buffer is not flused until a newline character in sent - prints o/p on one line until a ne is encountered Ex : System.out.print(“Hi”); ii) println( ) method - stake the information provided displays it on a line followed by a line f Ex : System.out.println(“Hi”); 6. Standard Default Variables : - Every variable has a default valu Type of variable Default value byte Zero:0 short Zero:0 int Zero:0 long Zero:0L float 0.0f double 0.0d char null character boolean false
  • 63. 7. TYPE CASTING : - To store a value of one type into a variable of another type Syntax: type var1 = (type) var2; Ex : int m = 10; byte n = (byte) m; Automatic Conversion - assign a value of one type to a variable of a different type without a cast. - the conversion of the assigned value automatically known as automatic-type conversion Ex : byte b =10; int a =b; From To byte Short, char, int, long, float, double short Int, long, float, double char Int, long, float, double int long, float, double long float, double float double Final Keyword In Java 1. Final variable 2. Final method 3. Final class reference null
  • 64. 4. Is final method inherited ? 5. Blank final variable 6. Static blank final variable 7. Final parameter 8. Can you declare a final constructor The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: 1. variable 2. method 3. class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
  • 65. 1) Java final variable If you make any variable as final, you cannot change the value of final variable(It will be constant). Example of final variable There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed. 1. class Bike9{ 2. final int speedlimit=90;//final variable 3. void run(){ 4. speedlimit=400; 5. } 6. public static void main(String args[]){ 7. Bike9 obj=new Bike9(); 8. obj.run(); 9. }
  • 66. 10. }//end of class Test it Now Output:Compile Time Error 2) Java final method If you make any method as final, you cannot override it. Example of final method 1. class Bike{ 2. final void run(){System.out.println("running");} 3. } 4. 5. class Honda extends Bike{ 6. void run(){System.out.println("running safely with 100kmph");} 7. 8. public static void main(String args[]){ 9. Honda honda= new Honda(); 10. honda.run(); 11. } 12. } Test it Now Output:Compile Time Error 3) Java final class If you make any class as final, you cannot extend it.
  • 67. Example of final class 1. final class Bike{} 2. 3. class Honda1 extends Bike{ 4. void run(){System.out.println("running safely with 100kmph");} 5. 6. public static void main(String args[]){ 7. Honda1 honda= new Honda1(); 8. honda.run(); 9. } 10. } Test it Now Output:Compile Time Error Q) Is final method inherited? Ans) Yes, final method is inherited but you cannot override it. For Example: 1. class Bike{ 2. final void run(){System.out.println("running...");} 3. } 4. class Honda2 extends Bike{ 5. public static void main(String args[]){ 6. new Honda2().run(); 7. } 8. }
  • 68. Test it Now Output:running... Q) What is blank or uninitialized final variable? A final variable that is not initialized at the time of declaration is known as blank final variable. If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialized only in constructor. Example of blank final variable 1. class Student{ 2. int id; 3. String name; 4. final String PAN_CARD_NUMBER; 5. ... 6. } Que) Can we initialize blank final variable? Yes, but only in constructor. For example: 1. class Bike10{ 2. final int speedlimit;//blank final variable 3. 4. Bike10(){ 5. speedlimit=70;
  • 69. 6. System.out.println(speedlimit); 7. } 8. 9. public static void main(String args[]){ 10. new Bike10(); 11. } 12. } Test it Now Output: 70 static blank final variable A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block. Example of static blank final variable 1. class A{ 2. static final int data;//static blank final variable 3. static{ data=50;} 4. public static void main(String args[]){ 5. System.out.println(A.data); 6. } 7. } Q) What is final parameter?
  • 70. If you declare any parameter as final, you cannot change the value of it. 1. class Bike11{ 2. int cube(final int n){ 3. n=n+2;//can't be changed as n is final 4. n*n*n; 5. } 6. public static void main(String args[]){ 7. Bike11 b=new Bike11(); 8. b.cube(5); 9. } 10. } Test it Now Output: Compile Time Error Q) Can we declare a constructor final? No, because constructor is never inherited.
  • 71. Java Object finalize() Method Finalize() is the method of Object class. This method is called just before an object is garbage collected. finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory leaks. Syntax 1. protected void finalize() throws Throwable Throw Throwable - the Exception is raised by this method Example 1 1. public class JavafinalizeExample1 { 2. public static void main(String[] args) 3. { 4. JavafinalizeExample1 obj = new JavafinalizeExample1(); 5. System.out.println(obj.hashCode()); 6. obj = null; 7. // calling garbage collector 8. System.gc(); 9. System.out.println("end of garbage collection"); 10. 11. } 12. @Override
  • 72. 13. protected void finalize() 14. { 15. System.out.println("finalize method called"); 16. } 17. } Test it Now Output: 2018699554 end of garbage collection finalize method called ABSTRACT CLASS IN JAVA : A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body). Before learning the Java abstract class, let's understand the abstraction in Java first. Abstraction in Java Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it. Ways to achieve Abstraction There are two ways to achieve abstraction in java 1. Abstract class (0 to 100%) 2. Interface (100%)
  • 73.
  • 74. Abstract class in Java A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. Points to Remember o An abstract class must be declared with an abstract keyword. o It can have abstract and non-abstract methods. o It cannot be instantiated. o It can have constructors and static methods also. o It can have final methods which will force the subclass not to change the body of the method. Example of abstract class 1. abstract class A{} Abstract Method in Java A method which is declared as abstract and does not have implementation is known as an abstract method. Example of abstract method 1. abstract void printStatus();//no method body and abstract Example of Abstract class that has an abstract method
  • 75. In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Honda class. 1. abstract class Bike{ 2. abstract void run(); 3. } 4. class Honda4 extends Bike{ 5. void run(){System.out.println("running safely");} 6. public static void main(String args[]){ 7. Bike obj = new Honda4(); 8. obj.run(); 9. } 10. } Test it Now running safely Understanding the real scenario of Abstract class In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the implementation class is provided by the factory method. A factory method is a method that returns the instance of the class. We will learn about the factory method later. In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked. File: TestAbstraction1.java 1. abstract class Shape{ abstract void draw(); } 2. //In real scenario, implementation is provided by others i.e. unknown by end user 3. class Rectangle extends Shape{ 4. void draw(){System.out.println("drawing rectangle");} } 5. class Circle1 extends Shape{ 6. void draw(){System.out.println("drawing circle");} } 7. //In real scenario, method is called by programmer or user 8. class TestAbstraction1{ public static void main(String args[]){ 9. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method 10. s.draw(); } } Test it Now
  • 76. drawing circle Another example of Abstract class in java File: TestBank.java 1. abstract class Bank{ 2. abstract int getRateOfInterest(); } 3. class SBI extends Bank{ 4. int getRateOfInterest(){return 7;} } 5. class PNB extends Bank{ 6. int getRateOfInterest(){return 8;} } 7. class TestBank{ public static void main(String args[]){ Bank b; 8. b=new SBI(); 9. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %"); 10. b=new PNB(); 11. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %"); }} Test it Now Rate of Interest is: 7 % Rate of Interest is: 8 % VARIABLE ARGUMENT (VARARGS): The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach. ADVANTAGE OF VARARGS: We don't have to provide overloaded methods so less code. Syntax of varargs: The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows: return_type method_name(data_type... variableName){} SIMPLE EXAMPLE OF VARARGS IN JAVA: 15. 16. class VarargsExample1{ 17. static void display(String... values){
  • 77. 18. System.out.println("display method invoked "); } 19. public static void main(String args[]){ 20. display();//zero argument 21. display("my","name","is","varargs");//four arguments } } Test it Now Output:display method invoked display method invoked ANOTHER PROGRAM OF VARARGS IN JAVA: 19. 20. class VarargsExample2{ 21. static void display(String... values){ 22. System.out.println("display method invoked "); 23. for(String s:values){ 24. System.out.println(s); } } 25. public static void main(String args[]){ 26. display();//zero argument 27. display("hello");//one argument 28. display("my","name","is","varargs");//four arguments } } Test it Now Output:display method invoked display method invoked hello display method invoked my name is varargs download this example RULES FOR VARARGS: While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows: o There can be only one variable argument in the method. o Variable argument (varargs) must be the last argument.
  • 78. EXAMPLES OF VARARGS THAT FAILS TO COMPILE: 6. void method(String... a, int... b){}//Compile time error 7. void method(int... a, String b){}//Compile time error EXAMPLE OF VARARGS THAT IS THE LAST ARGUMENT IN THE METHOD: 18. class VarargsExample3{ static void display(int num, String... values){ 19. System.out.println("number is "+num); 20. for(String s:values){ 21. System.out.println(s); 22. } } 23. public static void main(String args[]){ 24. display(500,"hello");//one argument 25. display(1000,"my","name","is","varargs");//four arguments } } 26. Test it Now Output:number is 500 hello number is 1000 my name is varargs Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body } In order to define vararg, ... (three dots) is used in the formal parameter of a method. A method that takes variable number of arguments is called a variable-arity method, or simply a varargs method. First, let’s look at the example without using varargs: class NoVararg {
  • 79. public int sumNumber(int a, int b){ return a+b; } public int sumNumber(int a, int b, int c){ return a+b+c; } public static void main( String[] args ) { NoVararg obj = new NoVararg(); System.out.println(obj.sumNumber(1, 2)); System.out.println(obj.sumNumber(1, 2, 3)); }} When you run this program, the output will be: 3 6 As you can clearly see, you had to overload sumNumber() method to make it work for 3 arguments. THINGS TO REMEMBER WHILE USING VARARGS Here are a couple of things you should remember while working with Java vargars: 1. While defining method signature, always keep varargs at last. The variable argument must be the last argument passed to the method. Let's consider, you invoked doSomething() method like this: doSomething(1, 2, 3, 4); And, your doSomething() method is defined as: // incorrect method declaration public void doSomething(int ... nums, int p){ // method body } In this case, compiler cannot figure out the number of arguments passed to nums. However, if you define your method as: public void doSomething(int p, int ... nums) { // method body } The Java compiler assigns the first argument to p, and the remaining int arguments are assigned to nums. 2. A method can have only one varargs parameter.
  • 80. For example, this method declaration is incorrect: int doSomething(int p, float ... floatNums, double ... doubleNums) { // code} AMBIGUITY IN VARARGS METHOD OVERLOADING Let’s consider you overloaded test() method like this: class Demo { static void test(int ... vargs) { // method body } static void test(int n, int ... vargs) // method body }} In the above program, the compiler gets confused if you try to invoke the test() method even though test() methods are overloaded and accepts different number of arguments. Visibility Control/Access Modifiers in Java JAVA ACCESS MODIFIERS: In Java, We have seen that the variables and methods of a class are visible everywhere in the program. However, it may be necessary for some situations to restrict access to certain variables and methods from outside the class. We can achieve this in Java by applying visibility modifiers to the instance variables and methods. These visibility modifiers are also known as Java Access Modifiers. There are five types of Java Access Modifiers are exists: Private Protected Access Modifiers PUBLIC: Any variable or method is visible to the entire class in which it is defined. A variable or method declared as public has the widest possible visibilty and accessible everywhere. Example: public int number; public void add()
  • 81. { ......... ......... } PRIVATE: Private field has the highest degree of protection. They are accessible only with their class. They can’t be inherited by subclasses and therefore not accessible in the subclass. A method declared as private behaves like a method declared as final. It prevents the method from being subclassed. Example: private int number; private void add() { ......... .........} FRIENDLY OR DEFAULT: When no access modifier is specified, the member defaults to a limited version of public accessibility that is known as “Friendly or Default Access Modifiers”. The difference between the “public” and “friendly or default” access modifiers is that the public makes fields visible in all classess including other packages, while friendly or default makes fields visible only in the same package, but not in other packages. Example: int number; void add() { ......... .........} PROTECTED:
  • 82. The protected makes the fields visible not only to all classes and subclasses in the same package but also to subclasses in other packages and non-subclassess in other packages can’t access the protected members. Example: public class test{ protected int number; protected void add() { ......... ......... } } PRIVATE PROTECTED: Private Protected makes the fields visible in all subclasses regardless of what package they are in. These fields aren’t accessible by other classes in the same package. Example: private protected int number; private protected void add() { ......... .........} 1. Private access modifier 2. Role of private constructor 3. Default access modifier 4. Protected access modifier 5. Public access modifier 6. Access Modifier with Method Overriding There are two types of modifiers in Java: access modifiers and non-access modifiers. The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
  • 83. There are four types of Java access modifiers: 1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. 2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. 3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. 4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only. Understanding Java Access Modifiers Let's understand the access modifiers in Java by a simple table. Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y 1) Private The private access modifier is accessible only within the class. Simple example of private access modifier In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is a compile-time error.
  • 84. 1. class A{ 2. private int data=40; 3. private void msg(){System.out.println("Hello java");} } 4. public class Simple{ 5. public static void main(String args[]){ 6. A obj=new A(); 7. System.out.println(obj.data);//Compile Time Error 8. obj.msg();//Compile Time Error } } Role of Private Constructor If you make any class constructor private, you cannot create the instance of that class from outside the class. For example: 1. class A{ 2. private A(){}//private constructor 3. void msg(){System.out.println("Hello java");} } 4. public class Simple{ 5. public static void main(String args[]){ 6. A obj=new A();//Compile Time Error } } Note: A class cannot be private or protected except nested class. 2) Default If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public. Example of default access modifier In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package. 1. //save by A.java 2. package pack; 3. class A{ 4. void msg(){System.out.println("Hello");} } 1. //save by B.java 2. package mypack; 3. import pack.*; 4. class B{ public static void main(String args[]){
  • 85. 5. A obj = new A();//Compile Time Error 6. obj.msg();//Compile Time Error } } In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package. 3) Protected The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class. It provides more accessibility than the default modifer. Example of protected access modifier In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance. 1. //save by A.java 2. package pack; 3. public class A{ 4. protected void msg(){System.out.println("Hello");} } 1. //save by B.java 2. package mypack; 3. import pack.*; 4. class B extends A{ 5. public static void main(String args[]){ 6. B obj = new B(); 7. obj.msg(); } } Output:Hello 4) Public The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. Example of public access modifier 1. //save by A.java
  • 86. 2. 3. package pack; 4. public class A{ 5. public void msg(){System.out.println("Hello");} 6. } 1. //save by B.java 2. package mypack; 3. import pack.*; 4. class B{ 5. public static void main(String args[]){ 6. A obj = new A(); 7. obj.msg(); } } Output:Hello Java Access Modifiers with Method Overriding If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive. 1. class A{ 2. protected void msg(){System.out.println("Hello java");} } 3. public class Simple extends A{ 4. void msg(){System.out.println("Hello java");}//C.T.Error 5. public static void main(String args[]){ 6. Simple obj=new Simple(); 7. obj.msg(); } } The default modifier is more restrictive than protected. That is why, there is a compile-time error. JAVA ACCESS MODIFIERS: In Java, We have seen that the variables and methods of a class are visible everywhere in the program. However, it may be necessary for some situations to restrict access to certain variables and methods from outside the class. We can achieve this in Java by applying visibility modifiers to the instance variables and methods. These visibility modifiers are also known as Java Access Modifiers. There are five types of Java Access Modifiers are exists:
  • 87. PUBLIC: Any variable or method is visible to the entire class in which it is defined. A variable or method declared as public has the widest possible visibilty and accessible everywhere. Example: public int number; public void add() { ......... .........} PRIVATE: Private field has the highest degree of protection. They are accessible only with their class. They can’t be inherited by subclasses and therefore not accessible in the subclass. A method declared as private behaves like a method declared as final. It prevents the method from being subclassed. Example: private int number; private void add() { ......... .........} FRIENDLY OR DEFAULT: When no access modifier is specified, the member defaults to a limited version of public accessibility that is known as “Friendly or Default Access Modifiers”. The difference between the “public” and “friendly or default” access modifiers is that the public makes fields visible in all classess including other packages, while friendly or default makes fields visible only in the same package, but not in other packages. Example: int number; void add()
  • 88. { ......... .........} PROTECTED: The protected makes the fields visible not only to all classes and subclasses in the same package but also to subclasses in other packages and non-subclassess in other packages can’t access the protected members. Example: public class test{ protected int number; protected void add() { ......... .........} } PRIVATE PROTECTED: Private Protected makes the fields visible in all subclasses regardless of what package they are in. These fields aren’t accessible by other classes in the same package. Example: private protected int number; private protected void add() { ......... .........} JAVA PROGRAMMING UNIT – V MANAGING INPUT/OUTPUT in JAVA 1. INTRODUCTION 2. CONCEPT OF STREAMS 3. STREAM CLASSES 4. BYTE STREAM CLASSES
  • 89. 5. CHARACTER STREAM CLASSES 6. USING STREAMS 7. OTHER USEFUL I/O CLASSES 8. USING THE FILE CLASS 9. INPUT/OUTPUT EXCEPTIONS 10. CREATION OF FILES 11. READING/WRITING CHARACTERS 12. READING/WRITING BYTES 13. HANDLING PRIMITIVE DATA TYPES 14. CONCATENATING AND BUFFERING FILES 15. RANDOM ACCESS FILES 16. INTERACTIVE INPUT AND OUTPUT 17. OTHER STREAM CLASSES
  • 90. 1. INTRODUCTION Problems in variables and arrays: i) The data is lost either when a variable goes out of scope or when the program is terminated. ii) It is difficult to handle volumes of data using variables and arrays. Solution:  Storing data on secondary storage devices such as floppy disk or hard disks - The data stored in these devices using the concept of files. Data stored in files is called persistent data. Files:A file is a collection of related records placed in a particular area on the disk. Record: A record I composed of several fields and a field is a group of characters. Characters:Character in Java are Unicode characters composed of 2 bytes, each byte containing eight binary digits, 1 or 0. File Processing: Storing and managing data using files is known as file processing which include tasks such as - Creating files - Updating files - Manipulation of data Features: - Reading and writing of data in a file can be done at the level of bytes and characters or fields depending on the requirements of a particular application. - Also provides capabilities to read and write close objects directly. - The process of reading and writing objects is called object serialization. Fig : Data Representation in java files
  • 91. 2. CONCEPT OF STREAMS In file processing, input refers to the flow of data into a program and output means the flow of data out of a program. I/P : input to a program may come from the keyboard, the mouse, the memory, the disk, a network or another program. O/P : output from a program may got to the screen, the printer, the memory, the disk, a network, or another program. Fig : Relationship of Java Program with I/O devices - Different in h/w level - They share certain common characteristics such as unidirectional movement of data, treating data as sequence of bytes or characters and support to the sequential access to the data. Streams: to represent the sequence of data, a common characteristic shared by all the i/o devices. - A stream presents a uniform, easy-to-use, OO interface b/w the program and the i/o devices. Definition: A stream is a path along which data flows. - It have a source (of dta) and a destination (for that data) - Both the source and the destination may be physical devices or programs or other streams in the same program. Fig : Conceptual view of a stream
  • 92. Java streams are classified into 2 basic types - Input stream – an i/p stream extracts ie., reads data from the source (file) and sends it to the program. - Output stream – an o/p stream takes data from the program and sends it to the destination. Fig : Using input and output streams - The program connects and opens an i/p stream on the data source and then reads the data serially. - Similarly, the program connects and opens an o/p stream to the destination place of data out serially. - In both cases, the program does not know the details of end points(ie., source and destination). 3. Stream Classes The java.io package contains a large number of stream classes that provide capabilities for processing all types of data. 2 groups : i) Byte stream classes that provide support for handling I/O operations on bytes ii) Character stream classes that provide support for managing i/o operations on characters. Both contain specialized classes to deal with i/o operations independently. 4. Byte Stream classes Designed to provide functional features for creating and manipulating streams and files for reading and writing bytes. - The streams are unidirectional; they can transmit bytes in only one direction. 2 kinds of stream classes :
  • 93. i) Input stream classes ii) Output stream classes i) Input Stream classes - Used to read 8-bit bytes include a super class known as Inputstream and a number of subclasses for supporting various input-related functions. The super class Inputstream is an abstract class, we cannot create instances of the class. Methods : - Reading bytes - Closing streams - Marking positions in streams skipping ahead in a stream - Finding the number of bytes in a stream Summary of Inputstream methods ii) Output stream classes Derived from the base class outputstream
  • 94. Perform following tasks : - Writing styles - Closing streams - Flushing streams 5. Character Stream classes:  Character stream can be used to read and write 16-bit Unicode characters.  Like byte streams, there are two kinds of character stream classes namely, reader stream and writer stream classes. READER STREAM CLASSES:  Reader stream classes are designed to read character from the files.  Reader class is the base class for all classes in this group.  These classes are functionally very similar to the input stream classes, except input stream use bytes as their fundamental unit of information while reader stream use characters.
  • 95.  The reader class contains methods that are identical to those available in the inputstream class, except reader is designed to handle characters.  Reader classes can perform all the functions implemented by the stream classes. WRITER STREAM CLASSES:  The writer classes are designed to perform all output operations on files.  Only difference is that while output stream classes are designed to write the bytes, the writer stream classes are designed to write characters.  The writer class is an abstract class which acts as a base class for all the other writer stream classes.  This base class provides support for all output operations by defining methods that are identical to those in output stream class.