Unit I-Java Notes (New Syllabus)
Unit I-Java Notes (New Syllabus)
UNIT I NOTES
1. INTRODUCTION TO OOPS
1.1) Paradigms of Programming Languages
1.2) Basic concepts of Object Oriented Programming
1.3) Differences between POP(C) and OOP(Java)
1.4) Difference between c++ and Java
1.5) Benefits of OOPs
1.6) Application of OOPs.
2. JAVA EVOLUTION
2.1) Java History
2.2) Java Features
2.3) Java and Internet
2.4) Java and World Wide Web
2.5) Web Browsers
2.6) Java Environment
3. INTRODUCTION TO JAVA
3.1) Types of java program
3.2) Java Program Structure
3.3) Naming Conventions
3.4) Creating and Executing a Java program
3.5) Java Tokens
3.6) Java Character set
3.7) Java Statements
3.8) Java Virtual Machine (JVM)
3.9) Command Line Arguments
3.10) Comments in Java program.
1
JAVA NOTES UNIT - I
a)Procedure-Oriented Programming:
In the procedure oriented approach, the problem is viewed as the sequence of things to be
done such as reading, calculating and printing. The primary focus is on functions.
C++ was mainly designed for systems programming and Java was created initially to support
network computing.
C++ supports pointers whereas Java does not pointers.
At compilation time Java Source code converts into byte code. The interpreter execute this
byte code at run time and gives output. While C++ run and compile using compiler which
converts source code into machine level languages. so, C++ is platform dependent.
Java is platform independent language but C++ depends upon operating system machine etc.
Java uses both compiler and interpreter and C++ uses only compiler
3
JAVA NOTES UNIT - I
C++ supports operator overloading and multiple inheritance but java does not support
operator overloading and multiple inheritance concepts.
Java does not support all the complicated aspects of C++ (ex: Pointers, templates, unions,
structures etc.)
Thread support is built-in in Java but not in C++.
Internet support is built-in in Java but not in C++.
Java does not support header files, #include library files just like C++. Java uses import
statements to include different Classes and methods.
Java does not support default arguments like C++.
Exception and Auto Garbage Collector handling in Java is different because there are no
destructors into Java.
Java has method overloading, but no operator overloading just like C++.
i) Objects:
Definition: Objects are the basic run time entities in an object oriented system. Object takes up
space in the memory and has an associated address. When a program is executed the objects
interact by sending messages to one another
Example:
ii) Class:
Definition: A class is a collection of objects of similar data types. They are user defined data
types. Once a class has been defined, we can create any number of objects belonging to that
class. Objects are variables of type class.
Example:
class fruit
{
-----
------
-----
} mango, grapes;
mango and grapes are the objects for the class fruit.
iii) Encapsulation:
Definition: The wrapping up of data and methods into a single unit called class is known as
encapsulation. The data is not accessible to the outside world and only those methods which
are wrapped in the class can access it.
Example:
class student
4
JAVA NOTES UNIT - I
{
int a,b;
public:
void sum();
}
v) Data Abstraction:
Definition: Abstraction refers to the act of representing essential features without including the
background details or explanations.
Example: size, weight, cost etc.
size, weight, cost are called attributes or data members. Functions that operate on these data are
called methods or member functions.
vi) Inheritance:
Definition: Inheritance is a process by which objects of one class acquire the properties of objects
of another class. The concept of inheritance provides the idea of Reusability. we can add additional
features to an existing class without modifying it.
Example:
vii) Polymorphism:
Definition: Polymorphism means the ability to take more than one form. An operation may exhibit
different behaviours in different instances. The behaviour depends upon the types of data used in the
operation
Example:
Addition of two numbers generates a sum (eg. 1+2=3)
Addition of two strings generates a concatenation (eg. Sun + flower = sunflower)
OOP offers several benefits to both the program designer and the user. ObjectOrientation
contributes to the solution of many problems associated with the
development and quality of software products. The new technology promises greater
programmer productivity, better quality of software and lesser maintenance cost. The
principal advantages are:
Through inheritance, we can eliminate redundant code extend the use of existing Classes.
We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
The principle of data hiding helps the programmer to build secure program that cannot be
invaded by code in other parts of a programs.
It is possible to have multiple instances of an object to co-exist without any interference.
It is possible to map object in the problem domain to those in the program.
It is easy to partition the work in a project based on objects.
The data-cantered design approach enables us to capture more detail of a model in an
implemental form.
Object-oriented system can be easily upgraded from small to large system.
Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
Software complexity can be easily managed.
The most popular application of object-oriented programming, up to now, has been in the
area of user interface design such as window. Hundreds of windowing systems have been developed,
using the OOP techniques.
Real-business system are often much more complex and contain many more objects
with complicated attributes and method. OOP is useful in these types of application
because it can simplify a complex problem. The promising areas of application of OOP
include:
Real-time system
Simulation and modeling
Object-oriented data bases
Hypertext, Hypermedia, and expertext
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAM/CAD systems
6
JAVA NOTES UNIT - I
2. JAVA EVOLUTION
2.1) Java History:
Year Development
1990 Sun Microsystems decided to develop special software that could be used
manipulate consumer electronic devices. A team of Sun Microsystems
programmers headed by James Gosling was formed to undertake this task.
1991 After exploring the possibility of using the most popular object-oriented language
C++, the team announced a new language named “Oak”.
1992 The team, known as Green Project team by Sun, demonstrated the application of
their new language to control a list of home appliances using a hand-held device
with a tiny touch sensitive screen.
1993 The World Wide Web (WWW) appeared on the Internet and transformed the text-
based Internet into a graphical-rich environment. The Green Project team came up
with the idea of developing Web applets (tiny programs) using the new language
that could run on all types of computers connected to Internet
1994 The team developed a Web browser called “Hot Java” to locate and run applet
programs on Internet. Hot Java demonstrated the power of the new language, thus
making it instantly popular among the Internet users.
1995 Oak was renamed “Java”, due to some legal snags. Java is just a name and is not
an acronym. Many popular companies including Netscape and Microsoft
announced their support to Java
1996 Java established itself not only as a leader for Internet programming but also as a
general-purpose, object-oriented programming language. Sun releases Java
Development Kit 1.0.
1997 Sun releases Java Development Kit 1.1 (JDK 1.1)
1998 Sun releases the Java 2 with version 1.2 of the Software Development Kit (SDK
1.2)
1999 Sun releases the Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition
(J2EE)
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with SDK 5.0( instead of JDK 1.5) was released. This is known as J2SE 5.0
2006 Java SE 6 was released. With this release , sun changed the name from ‘J2SE’ to
Java SE and also removed ‘0’ from the version name.
2011 Java SE 7 was released.
3) Object Oriented:
The object model in Java is simple and easy to extend. It is a fully Object Oriented language.
Everything in java is object even the primitive data types can also be converted into object by using
the wrapper class.
5) Distributed:
Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols.
Internet programmers can call functions on these protocols and can get access the files from any
remote machine on the internet rather than writing codes on their local system.
8) High Performance:
Java uses native code usage, and lightweight process called threads for faster execution. The
advance version of JVM uses the adaptive and just in time compilation technique that improves the
performance.
Java is strongly associated with the internet because of the first application program is
written in Java was hot Java. Web browsers to run applets on the internet. Internet users can use
Java to create applet programs & run then locally using a Java-enabled browser such as hot Java.
Java applets have made the internet a true extension of the storage system of the local computer.
The web-browser is a program that accepts a request, processes the request and sends the
required documents.
The HTML document is returned to that user browser.
The document contains the applet tag which identifies the applet. The corresponding applet is
transferred to the user computer.
The Java enabled browser on the user's computer interprets the byte code and provide output.
A browser is a software application used to locate, retrieve and display content on the
World Wide Web, including Web pages, images, video and other files. As a client/server model,
the browser is the client run on a computer that contacts the Web server and requests
information. The Web server sends the information back to the Web browser which displays
the results.
The browser application retrieves or fetches code, usually written in HTML (HyperText
Markup Language) and/or another language, from a web server, interprets this code, and
renders (displays) it as a Web page for you to view. on the computer or another Internet-
enabled device that supports a browser.
Examples of Web Browsers:
Hot Java
Netscape Navigator
Internet Explorer
HotJava
HotJava was a modular, extensible web browser from Sun Microsystems implemented
in Java. It was the first browser to support Java applets, and was Sun's demonstration
platform for the then-new technology. It has since been discontinued and is no longer
supported.
Netscape Navigator
Netscape Navigator is a browser that became popular in 1994 when it was released by
Netscape Communications. This was released as a competition to Internet Explorer, however it
soon lost popularity.
Internet Explorer
Internet Explorer (IE) is a product from software giant Microsoft. This is the most commonly
used browser in the universe. This was introduced in 1995 along with Windows 95 launch .it
uses just-in-time compiler which greatly increases the speed of execution.
10
JAVA NOTES UNIT - I
2.6) Java Environment
Java Environment includes a large number of development tools and hundreds of classes and
methods. The development tools are part of the system known as Java Development kit (JDK)
and the classes and methods are part of the Java Standard Library(JSL), also known as the
Application Programming Interface(API).
The Java Development Kit comes with a collection of tools that are used for developing
and running Java Programs. They include:
a) appletviewer(for viewing Java Applets) : Enables us to run Java applets(without actually
using a Java-compatible browser).
b) javac( Java Compiler) : The Java comiler, which translates Java sourcecode to bytecode
files that the interpreter can understand.
c) java( Java Interpreter) : Java interpreter, which runs applets and applications by reading
and interpreting bytecode files.
d) javadoc : Creates HTML format documentation from Java source code files.
e) javah : Produces header files for use with native methods.
f) javap : Java disassembler, which enable us to convert byte code files into a program
description.
g) Jdb : Java debugger, which helps us to find errors in our programs.
11
JAVA NOTES UNIT - I
The way these tools are applied to build and run application programs is illustrated in
above figure. To create a Java program, we need to create a source code file using a text
editor. The source code is then compiled using the Java compiler javac and executed using
the Java interpreter java. The Java debugger jdb is used to find errors, if any, in the source
code. A compiled Java program can be converted into a source code with the help of Java
disassemble javap.
The Java Standard Library (or API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are:
Language Support Package: A collection of classes and methods required for implementing
basic features of java.
Utilities Package: A collection of classes to provide utility functions such as date and time
functions.
Input/Output Package : A collection of classes required for input/output manipulation.
Networking Package: A collection of classes for communicating with order computers via
Internet.
AWT package : The Abstract Window Tool Kit package contains classes that implements
platform-independent graphical user interface.
Applet Package : This includes a set of classes that allows us to create Java applets.
The java Runtime Environment (JRE) facilitates the execution of programs developed in java.
It primarily comprises the following:
Java virtual machine (JVM) : it is a program that interprets the intermediate Java byte code
and generates the desired output. It is because of byte code and JVM concepts that programs
written in Java are highly portable.
Runtime class Libraries: These are a set of core class libraries that are required for the
execution of Java programs.
User interface tool kits: AWT and Swing are examples of tool kits that support varied input
methods for the users to interact with the application program.
Deployment technologies: JRE comprises the following key deployment technologies:
a) Java plug-in: Enables the execution of a Java applet on the browser.
b) Java Web Start: Enables remote-deployment of an application. With web start, users can
launch an application directly from the web browser without going through the installation
procedure.
3. INTRODUCTION TO JAVA
Java is a programming language that is used to build programs that can work on the local
machine and on the internet as well. It is a platform independent language which could be used to
create software for embedded systems. So there are various categories of programs that can be
developed in Java.
WEB APPLICATIONS - These are the applications which are web-based in nature and require a
web browser for execution. The Web applications makes use of a Server to store the data, and
every time a user requests to execute that application, the request is passed on to the server for
suitable reply. E.g. Applet and Servlet.
An applet is an application designed to be transmitted over the Internet and executed by a Java-
compatible Web browser. An applet is actually a tiny Java program, dynamically downloaded
across the network, just like an image, sound file, or video clip.
In Servlets, the client sends a request to a server. The server processes the request and sends a
response back to the client.
CLIENT SERVER APPLICATIONS - These applications too make use of web technology for
their execution. They follow simple Client-Server model, where a client makes requests directly to
the server.
Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/blue print that describes the behaviors /states that object
of its type support.
Methods - A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object's state is created
by the values assign
Documentation Section Suggested
//This program will display the output “My first Java program”
import java.io.*;
class first
{
public static void main(String args[])
{
System.out.println(“My first Java program”);
}
}
Documentation section - The documentation section consist of a set of comment lines such
as the name of the program, program details etc. The three types of comments are
// Single line comment
/* ………..*/ Multiline comment
/**………..*/ For generating documentation automatically
Package Statements: The first statement allowed in a java file is a package statement. This
statement declares a package name and informs the compiler that classes defined here belong
to this package.
E.g: package student;
Import statements - It instructs the interpreter to load the corresponding class contained in
the package statement. There can be any number of import statements in a java program.
Eg: import student.test;
This statement instructs the interpreter to load the test class contained in the package student.
Interface Statements: An interface is like a class but includes group of method declarations.
This is also an optional section and used only when we wish to implement the multiple
inheritance features in a program.
Class Declaration – This line declares a class. class is an object-oriented construct and a
keyword which states that the class declaration follows. “first” is the name of the class.
Opening and Closing Brace - The entire class definition, including all of its members, will
be between the opening curly brace ({) and the closing curly brace (}).
Public - The keyword public is an access specifier that declares the main method accessible
to all other classes.
Static - The keyword static states that this method belongs to the entire class. The keyword
static allows main() to be called without having to instantiate a particular instance of the class.
Void - The type modifier void states that the main() method does not return any value.
Main() – The main() function is similar to the the main() in C/C++. Every Java application
program must include the main() method. It is the method called when a Java application
begins.
14
JAVA NOTES UNIT - I
String args[ ] - The parameter args[] denotes an array of instances of the class String.
Output Line –The println() method is a member of the out object, which is a static data
member of System class. System is a predefined class that provides access to the system, and
out is the output stream that is connected to the console.
a) Names of all public methods and instances start with a leading lower case letters.
Eg. average
sum
b) When more than one words are used in a name, the second words are marked with a leading
upper case letters.
Eg. day Temperature
total Marks
c) All private and local variables use only lower case letters combined with under score.
Eg. area_triangle
d) All classes and interfaces start with the leading upper case letters.
Eg. Area
e) Variables that represent constant values use all upper case letters and under score.
Eg. TOTAL
MAX_COUNT
The tokens are the small building blocks of a Java program that are meaningful to the Java
compiler.
Types of Tokens:
1) Keywords
2) Identifiers
3) Literals
4) Operators
5) Separators
1) Keywords:
These are the pre-defined reserved words of any programming language. Each keyword has a
special meaning. It is always written in lower case. Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements
2) Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It usually defined by the
user. It uses letters, underscores, or a dollar sign as the first character. The label is also known as a
special kind of identifier that is used in the goto statement.
15
JAVA NOTES UNIT - I
Rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign.
o It cannot start with digits but may contain digits.
o The white space cannot be included in the identifier.
o Identifiers are case sensitive.
3) Literals:
Literal is a notation that represents a fixed value (constant) in the source code. It is defined by the
programmer. Once it has been defined it cannot be changed. Java provides five types of literals:
o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type
23 int
9.86 double
"java" String
4) Operators:
Operators are the special symbol that tells the compiler to perform a special operation. Java
provides different types of operators that can be classified according to the functionality they
provide.
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
16
JAVA NOTES UNIT - I
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
The separators in Java is also known as punctuators. There are nine separators in Java:
o Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional
array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the
two statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
The smallest units of java language are the characters used to write java tokens. These
characters are defined by the Unicode character set which tries to create characters for a large
number of scripts world wide.
The Unicode is a l6-bit character coding system and currently supports more than 34,000
defined Characters derived from 24 languages from America, Europe, Middle East, Africa and Asia
(including India)
Labelled Statement:
Any statement which begins with a Label. These are not keywords and they are the
arguments of jump statements.
Expression Statement:
Java has seven types of Expression Statements like
1) Assignment
2) Pre-decrement
3) Post-decrement
4) Pre-increment
5) Post -increment
6) Method call
7) Allocation Expression.
Control statements:
Selection Statement: This statement is used for selecting one of several control flows.
Iteration Statement: These statement specify how and when looping will take place.
Jump Statement: This statement pass control to the beginning or end of the current block,
or a labeled Statement.
18
JAVA NOTES UNIT - I
Synchronization Statement:
These are used for multithreading in Java.
Guarding Statement:
This statements are used for safe handling of code and uses try , catch and finally block.
Remember that, before we begin creating the program, the java development kit(jdk) must be
properly installed in your system.
Class Test
{
public static void main(String args[])
{
System.out.println(“Hello!”);
System.out.println(“Welcome to the world of java”);
System.out.println(“Let us learn java”);
}
}
We must save this program in a file called Test.java ensuring that the file name has the class
name properly. This file is called the source file. Note that all java source file will have the
extension java. Note also that if a program contain multiple classes, the file name must be the
class name of the class containing the main method.
3.Running Program
We need to use the java interpreter to run a stand-alone program. At the command prompt,
type java Test
now, the interpreter looks for the main method in the program and begins execution from there.
When executed, the program displays the following:
Hello!
Welcome to the world of java
Let us learn java
Note that we simply type “Test” at the command line and not “Test.class” or “Test.java”.
4.Machine Neutral
The compiler converts the source code files into bytecode files. These codes are machine
independent and therefore can be run on any machine. This is a program complied on an IBM
machine will run on a Macintosh machine.
Java interpreter reads the bytecode files and translates them into machine code for the
specific machine on which the java program is running. The interpreter is therefore specially
written for each type of machine.
All language compilers translates source code into machine code for a specific computer.
Java compiler also does the same thing. Then, how does java achieved architecture neutrality? The
answer is that the java compiler produces an intermedia code known as bytecode for a machine
that does not exist. The machine is called the Java Virtual Machine and it exist only inside the
computer memory. It is a simulated computer within the computer and does all major functions
of a real computer. Below figure illustrate the process of compiling a java program into bytecode
which is also referred to as virtual machine code.
20
JAVA NOTES UNIT - I
The virtual machine code is not machine specific. The machine specific code(known as a
machine code) is generated by the java interpreter by acting as an intermediary between the
virtual machine and the real machine as shown in below figure. Remember that the interpreter is
different for different machine
Below figure illustrate how java works on a typical computer. The Java object framework
(Java API) acts as the intermediary between the user program and the virtual machine which in turn
acts as the intermediary between the operating system and the java object framework.
Sometimes you will want to pass some information on a program when you run it. This is
accomplished by passing command-line arguments to main( ).
A command-line argument is an information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java program is
quite easy. They are stored as strings in the String array passed to main( ). We can pass any
number of arguments because argument type is an array.
Any argument provided in the command line at the time of program execution, are accepted
to the array args as its elements. Using index or subscripted entry can access the individual elements
of an array. The number of element in the array args can be getting with the length parameter.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
class commandline
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.
Syntax:
//This is single line comment
Example:
public class CommentExample1
{
public static void main(String[] args)
{
int i=10;//Here, i is a variable
System.out.println(i);
}
}
Output:
22
JAVA NOTES UNIT - I
10
Syntax:
/*
This
is
multi line
comment
*/
Example:
public class CommentExample2
{
public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}}
Output:
10