0% found this document useful (0 votes)
86 views

Unit - I: Chapter - 1

The document provides an overview of key concepts in Java programming including: - The history and origins of Java from its initial development in 1991 at Sun Microsystems. - The structure of Java programs including standard programs, applets, packages, and importing classes. - How Java code is compiled into bytecode and executed by the Java Virtual Machine (JVM). - Documentation comments in Java source code and the different comment styles. - The main primitive data types in Java including byte, int, float, boolean, and others.

Uploaded by

kavirishi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Unit - I: Chapter - 1

The document provides an overview of key concepts in Java programming including: - The history and origins of Java from its initial development in 1991 at Sun Microsystems. - The structure of Java programs including standard programs, applets, packages, and importing classes. - How Java code is compiled into bytecode and executed by the Java Virtual Machine (JVM). - Documentation comments in Java source code and the different comment styles. - The main primitive data types in Java including byte, int, float, boolean, and others.

Uploaded by

kavirishi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 75

UNIT - I

CHAPTER – 1
java
CONTENTS
1. INTRODUCTION
1.1. history of java
2. STRUCTURE OF JAVA PROGRAM
2.1. standard program and Applets
2.2. packages
2.3. importing classes and Packages 3. THE JAVA
COMPILER AND VIRUTAL
MACHINE
4. DOCUMENTATION COMMENTS
5. DATA TYPES
6. METHODS
6.1. parameters
6.2. Overloaded Methods
7. EXCEPTIONS
7.1. throwing an exception
7.2. handling exceptions
8. ACCESS MODIFIERS
9. INHERITANCE AND METHOD OVERRIDING
9.1. Super-classes and Subclasses
10. GENERIC METHODS
11. GARBAGE COLLECTION
12. RECURSION
12.1. recursive function
12.2. induction
12.3. recursive methods
13. TESTING AND DUBUGGING
13.1. what is testing
13.2. designing test data
13.3. debugging
1. INTRODUCTION
1.1. HISTORY OF JAVA

1. Java programming language is usually associated


with “ World Wide Web ”.
2. Java predates the Web.
3. Java began it’s life as the programming language
“ Oak ”.
4. Oak was developed by the “Green Project Members”
* Patrick Naughton
* Mike Sheridan
* James Gosling
5. A group formed in 1991 to create products for the
“ Smart electronic Markets “
6. The existing programming language were not
suitable for “ consumer electronics “.
7. The Chief Programmer of Sun Microsystem –
James Gosling :
created the software for controlling
“ Consumer Electronic devices “.
8. The team wanted a fundamentally new way of
computing , based on the power of “ Networks “.
And the S/W to run on different kinds of computers

9. Patenting issues gave a new name to Oak – Java.

10. HotJava
- The first Java-enabled Web browser
characteristics of java
• Java is simple
• Java is object-oriented
• Java is distributed
• Java is interpreted
• Java is robust
• Java is secure
• Java is architecture-neutral
• Java is portable
• Java is high-performance
• Java is multithreaded
• Java is dynamic language
• Java is simple
Java is simple language, can be learned easily.
• Java is object-oriented
Java provides Abstraction, Encapsulation, Inheritance and
Polymorphism.
• Java is distributed
Java is tuned to the Web, So java program can access data
– across the Web as easily as they access data from local
system.
• Java is interpreted
Java is both Interpreted and compiled. The code is
complied to byte code that’s “ Binary “ and “ platform
independent”.
• Java is robust
Java forces the programmer to handle unexpected errors.
This ensure that java programs are “Robust” (Reliable) and
bug free and don’t crash.
• Java is secure

A program traveling from internet to pc could possibly


carry a virus. Java done strong type-checking on the user-
machine, and changes in the program are tagged as errors and
program will not executed. So, java is “secure”.
. Java is architecture-neutral
The byte code can be executed on a variety of computers
running on different operating systems.
• Java is portable

Java program can run on any machine that has a java


interpreter. Other people can use the programs written in java,
even if they have different machines with different operating
systems.
• Java is multithreaded

perform multiple task at the same time.


• Java is dynamic language

Maintaining different versions of an application is very


easy in Java.
2. STRUCTURE OF JAVA PROGRAM
• Types of Java Programs are:
1. Applications (or) stand-alone program
- they are program that don’t need a browser
to run simultaneously.
- need MS-DOS or UNIX prompt to execute
the program.
2. Applets
- Applets are programs that execute inside
a Web page.
- Applets require a Java enabled browser like
* MS-internet Explorer
* Netscape Navigator
* Hotjava
- Applet have Graphical User Interface.
3. Servlets
- these programs extend the functionality of
web servers
4. Packages
- they are collections of classes that can be
shared by other Java programs.
2.1. standard program and Applets
• Every java program is a – CLASS
• Every class may contain data and METHOD members

S. No Application applet
1. METHOD name is “ main” METHOD name is “ int”

2. Syntax for Compiling Syntax for Compiling


javac javac <filename.java>
<filename.java>
3. Syntax for Executing Syntax for Executing
java filename Appletviewer <URL.html file>
2.2. packages
• DEFINITION
A Package is a collection of classes that can be shared by
java program.
Packages are used to organize classes into groups.
• Types of Packages

(i). Pre-defined (ii). User-defined


1. java.lang
2. java.util user can
3. java.applet create their
4. java.awt own packages
5. java.io (e.g) lab program
6. java.net
1. java.lang
- provides classes and interfaces that are
fundamental to java programming.
2. java.util
- provides classes that support collections, data and
calendar operations, parsing, internationalization
and basic event processing. Also refers to all
programs in the directory (lang/java or lang\java).
3. java.applet
- provides classes, necessary for basic applet
programming.
4. java.awt (abstract window toolkit)
- provides classes for creating GUI programs.
5. java.io
- provides classes for reading and writing data in
the form of streams. (input stream, output stream)
e.g: memory, file, buffer, network
6. java.net
- provides classes that provide network
programming.
2.3. importing classes and Packages
Syntax for package
• import <package_name>.*;
• import <package_name> . <class_name>;

Example:
import java.awt.*;
import java.awt.Button;

import java.awt.*;
in this syntax all the classes in awt package have to
imported
import java.awt.Button;
in this syntax only button class from awt package
have to imported
3. The java compiler and virtual machine
• Java source code is converted into Java Byte code (or) J-
code.
* When the program <programName> is compiled, the
program source code is read from the file
<programName.java>
* The compiled byte code is written in the file
<programName.class>
* Java Virtual Machine (JVM) is a software that
interpret and executes the byte code.
• The main task of JVM is – the loading of .class files
• JVM- has class loaders that loads the .class files, and
executed by the execution engine.
• Each java applications run inside a JVM.
• JVM starts when you start a java program and terminates
when the program ends.
• The no. of JVM starts when you start a java program and
terminates when the program ends.

• CLASS LOADER ARCHITECTURE


1. A JVM can have many class Loader. They provide
security and network to java programs.
2. The JVM has two types of class loaders.
(a) Primordial Class Loader
(b) Class Loader Objects
(a) Primordial Class Loader
A primordial Class Loader is a part of the JVM
implementation. It loads the java API classes when you
execute a java program.
(b) Class Loader Objects
An application can create many class loaders at runtime
for loading the classes of the application.

Implementation of Class Loader

Class Loader Class Loader

Java Virtual Machine Implementation


Primordial Class Loader Java API
JAVA VIRUTAL MACHINE
• Through the Java VM, the same application is capable of
running on multiple platforms.
• The Java platform has two components:
– The Java Virtual Machine (JVM)
– The Java Application Programming Interface (API)
4. DOCUMENTATION comments
• A comment is a message for a programmer & describes a
class, a method, or even a statement. The complier ignore
what you write as comments
• Comments are ignored by the compiler but are useful to
other programmers
• Java support three styles of comments:
1. Multiple line comments
2. Single line comment entries
3. The javadoc comments
1.Multiple line comments
Anything you write between /* and */ is treated as a
comment. The text that you type here can cover many lines.
/* multiple line comments */
2. Single line comment entries
anything you type after // is treated as a comment. The text
can’t span (extend) more than a line. If you have multiple lines
as comments, you must start every line with //.
// single line comment
3. The javadoc comments
these lines are used by the javadoc utility to create
documentation. These comments are similar o the multiple
line comments but start with a /** instead of /*
/** this is a javadoc comment*/
5. DATA TYPES
• The data that’s stored in memory can be of many types. For
example:
* a person’s age is stored as a numeric value & an
address is stored as alphanumeric characteristics.
* an address is stored as alphanumeric characters
Data types are used to define the operations possible on
them and the storage method.

* The data types in java are classified as:


1. primitive (or) standard data types
2. Abstract (or) derived data types
1. primitive (or) standard data types

Data Type Size/Format Description Range


(Numbers)

Byte 8-bit Byte-length -128 to +128


integer If signed(-2 7 to
27 -1)
If unsigned(0 to
255)

Short 16-bit Short integer -32768 to


+32767(-215 to
215-1)
Int 32-bit Integer -231 to 231-1
Data Type Size/Format Description Range
(Numbers)

long 64-bit Long integer -2 63 to 2 63-1

float 32-bit Single- +/-about 10 39


precision
floating point

double 64-bit Double- +/-about 10 317


precision
floating point
(other types)
Char 16-bit A single character

Boolean 1-bit A Boolean value (true or false)


2. Abstract (or) derived data types

• Abstract data types are based on primitive data types and have
more functionality than primitive data types.
• Example
“String” is an abstract data type that can store letters, digits
and other characters like /,(), : , ; , $ , #

* “String ”provides methods for concatenating two strings,


searching for one string within another, and extracting a
portion of a string. The primitive data types don’t have these
features.
6. METHODS
1. parameters
• A method is a body of code that’s used for performing a set of
tasks. The behavior of an object is determined by the program.
• Declaring Methods:

syntax:
[<access_specifier>] [<modifiers>] <return_type>
<method_name> ([argument_list])
{
//statements
}
• Example:
public static int abc (int a, int b, int c)
{
return a+b*c+b/c;
}
Where:
abc - name of the method
int - return type of the method is ‘int’
(int a, int b, int c) – formal paramenters of the
method abc, each is of integer
type.
• If the method is invoked by the statement
Z = abc (2,x,y)
then 2,x,y are the ‘actual parameter’.

* when the method ‘abc’ is invoked the


a - is assigned to 2
b - is assigned to x
c - is assigned to y
* In java all method parameters are ‘value parameters’.
* At run time the value of each ‘actual parameter’ is
copied into the corresponding format parameter before
the method is executed.
2. Overloaded methods
• Overloading is a technique in which more than one method
having the same name can be present in a program. The
compiler resolves the method to be invoked using the
signature of the method.
• Function signature
1. The name of the method
2. The number of arguments it takes
3. The data type of the arguments
4. The order of the arguments
- when we call a method, the compiler uses the signature
of the method to resolve the method to be invoked.
- A class can’t have two methods having the same signature.
- this is because the compiler will not know which method to
invoke if more than one method has the same signature.
Example:
java supports method overloading and hence, the methods can be
declared as follows:
* public void add(int a, int b); // add two integers
* public void add(float a, float b); // add two floats
* public void add(float a, int b); // adds a float and
an integer
* In the following example the ‘calculator’ class, the methods have
the same name but different parameters and the signatures of
the methods are different.
class calculator
{
public int add(int a, int b)
{
System.out.println("int and int");
return a + b;
}

public float add(float a, float b)


{
System.out.println("float and float");
return a + b;
}
public float add(float a, int b)
{
System.out.println("float and int");
return a + b;
}
public static void main(String args[])
{
calculator c = new calculator();
System.out.println(c.add(1,10))
System.out.println(c.add(1.6f,10.5f));
}
}
class calculator
{
public int add(int a, int b)
{
System.out.println("int and int");
return a + b;
}

public float add(float a, float b)


{
System.out.println("float and float");
return a + b;
}
public float add(float a, int b)
{
System.out.println("float and int");
return a + b;
}
public static void main(String args[])
{
calculator c = new calculator();
System.out.println(c.add(1,10))
System.out.println(c.add(1.6f,10.5f));
System.out.println(c.add(10.5f,2));
}
}
7. EXCEPTIONS
• An exception is defined as an ‘abnormal’ event that occurs
during program execution and disturb the normal flow of
instructions.
• Error-handling becomes necessary, when developing
applications and need to take care of unexpected situations.
• The unexpected situations that may occur during program
execution are:
* Running out of memory
* Resource allocation errors
* Inability to find files
* Problems in network connectivity
Exception-Handling Techniques
• When an unexpected error occurs in a method, java creates an
object of the types ‘ Exception’.
• After creating the Exception object, java sends it to the
program, by an action called “throwing an exception”.
• The Exception object contains information about the

- type of error
- status of the program when the exception occurred
* Key words in Excepting:
try
catch
throw
throws
finally
• Try Block
syntax:
try
{
//statements that may cause an exception
}
* If an exception occurs within the try block, the appropriate
exception-handler that’s associated with the try block handles
the exception.
* A try block must have at least one catch block that follows it
immediately.
• catch Block
syntax:
try
{
//statements that may cause an exception
}
catch(……)
{
// error handling routines
}
• The catch statement take the object of the exception class that
refers to the exception caught.
• Once the exception is caught, the statements within the catch
block are executed.
• The scope of the catch block is based on the statement in the
preceding try block.
Exception handling mechanism
• In java, exception-handling facility handles abnormal &
unexpected situation in a structured manner.
• When an exception occurs, the java runtime system searches
for an exception-handler (try-catch-block).
• If a handler is not found in the current method, the handler is
searched for in the ‘calling method’.
• The searches goes on till the runtime system finds an
appropriate exception-handler.
• EXAMPLE:
// derivedclass.java
class baseclass
{
public int divide(int num1, int num2)
{
return num1 / num2;
}
}
public class derivedclass extends baseclass
{
public int divide(int a, int b)
{
return super.divide(a,b);
}
public static void main(String args[])
{
int result = 0;
derivedclass d1 = new derivedclass();
try
{
result = d1.divide(100, 0);
}
catch(ArithmeticException e)
{
System.out.println(“Error…division by zero”);
}
System.out.println(“The result is: “ + result”);
}
}
Multiple catch block - example

public class trycatch


{
public static void main(String args[])
{
int num1, num2, result = 0;
num1 = 100;
num2 = 0;
try
{
result = num1/num2;

}
catch(ArithmeticException e)
{
System.out.println("Error---division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error----out of bounds");
}
catch(Exception e)
{
System.out.println("some other error");
}
System.out.println("The result is: " + result);
}

}
EXAMPLE-2

public class trycatch


{
public static void main(String args[])
{
int num1, num2, result = 0;
num1 = 100;
num2 = 4;
try
{
result = num1/num2;

}
catch(ArithmeticException e)
{
System.out.println("Error---division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error----out of bounds");
}
catch(Exception e)
{
System.out.println("some other error");
}
System.out.println("The result is: " + result);
}

}
throw statement
• When a user enters a wrong login-ID (or) password, the throw
statement is used to throw an exception.
• The throw statement takes a single statement, which is an
object of the ‘Exception class’.
• Syntax
throw Throwableinstance;
* Example
throw ThrowObject;
• The compiler gives an error if the object ‘ThrowObject”
doesn’t belong to a valid ‘Exception class’.
• The ‘throw statement is commonly used in ‘programmer-
defined’ exceptions.
throws statement
• Throws statement is used to specify that ‘ an exception has to be
handled by the calling method. It’s used for an exception that a
method is capable of raising, but not handling.
• Syntax
[<access_specifier>][<modifier>]<return_type>
<method_name> (<arg_list>) [throws <exception_list>]
• Example
public void acceptpassword() throws IllegalAccessException
{
System.out.println(“ intruder !!”);
throw new IllegalAccessException;
}
Finally Block
• The finally block is used when it’s necessary to process certain
statements no matter, whether an exception is raised or not.
• Example
try
{
openFile();
writeFile(); // may cause an exception
}
catch(……..)
{
// process the exception
}
Finally
{ closeFile();

}
Common exceptions

1. ArithmeticException Exception

2. NullPointerException Exception

3. ArrayIndexOutofBoundsException Exception
8. ACCESS MODIFIERS
• An access specifier determines which features of a class (the
class itself, the data members, and the method) may be used
by the other classes.
• Java supports three specifiers (or) Access Modifiers
1. public
2. private
3. Protected
4. Default
1. Public access specifier
A class, data member (or) method that has a public access
specifier can be accessed by any object. An inner class can’t
have a public access specifier.
• Syntax
<access_specifier> <return_type> <method> ([argment list])
{ ----------
}
Example:
public class employee
{
string empname;
string empadd;
public void displaydetails( )
{
// place the code for displaying employee details
}
}
2. Private access specifier
• Only object of the same class can access a variable or a
method that has a private access specifier. The variables and
method of the inner classes can be declared as private.
• Example:
private int privateVariable;

3. Protected access specifier


variable, methods, and inner classes that are declared protected
accessible to the subclasses of the class in which they are
declared.
Example:
protected int protectedVariable
4.Default access
A class, a variable or a method that doesn’t have an access
specifier as private, public, protected is said to have default
access. These classes, variables or methods are accessible to
all the classes of a package.
Example:
consider following set of classes y and z inherit from class x.
class z belongs to the package p1 and classes x and y belong to
the package p2.

Package p1

Class X Package p2

Class Z
Class Y
* A method accesme() has been declared in class X. The
following table shows the accessibility of the method
accessme() from class Y and Z.

Access specifier Class X Class Y


accessme() is Accessible as Y is a Accessible as z is a
declared as subclass subclass (even if
protected it’s in another class)

accessme() is Accessible as it is Not accessible as it


declared without an in the same package is not in the same
access speicifer pckage
Access Specifier Member Visibility
Default Member is visible only to
classes in the same package.

Private Member is visible only


within the class C.
Protected Member is visible to all
classes in the same package
and to subclasses of c in
other packages.

Public Member is visible to all


classes in all packages.
MODIFIERS
• Modifiers determine how the data members and methods are
used in other classes and objects.
• The modifiers in java:
1. static
2. final
3. abstract
4. native
5. transient
6. synchronized
7. volatile
9. INHERITANCE AND METHOD
OVERRIDING
• Inheritance is a situation in which a class derives a set of
attributes and related behavior from a parent class.
• 9.1. super classes and subclasses:
* super class:
super class is a class from which another class inherits
properties. It share its properties with its child classes.
* sub class:
sub class is a class that inherits attributes and methods from a
super class.
• Super class some times referred to as the ‘base class’ and the
subclass is referred to as the ‘derived class’.
• Subclass don’t inherit the constructs of the super class.
• Example:
let us take the example of ‘air tickets’- it can be of two types.
Confirmed and request ticket. both the tickets have a lot of
common attributes. For example
flight_number, date, time and destination.
confirmed ticket would have a ‘seat number’, while a
request ticket would have a ‘status’.
• Example:
Ticket

RequestTicket ConfirmedTicket

Syntax:

public class <subclass name> extends <superclass name>

public class confirmedTicket extends Ticket


Final keyword
• The final modifier doesn’t allow a class to be inherited. A
method declared anal can’t be overridden by a subclass.
• Final- keyword can prevent people from extending a class by
using the ‘final’ modifier as follow:
example:
final class password
{
--------
}
OVERRIDING methods
• In overridding, a subcalss method overrrides the definition of a
super class method, if the method defined in the subcalss has
the same signature of a method in the super class.
• Example:
let us consider the class ‘wheelchair’ is derived from the
‘chair class’. Both the classes have a method called
‘adjustHeight()’. Wheelchair is adjusted differently form the
way other chairs are adjusted. Therefore, the wheelchair class
overrides superclass method ‘adjustHeight()’.
// declaring base class chair (saved as wheelchair.java)
class chair
{
public void adjustHeight()
{
System.out.println(“adjusting chair height”);
}
}
//deriving wheelchair class from chair
public class wheelchair extends chair
{
public static void main (String args[])
{ wheelchair w
w = new wheelchair();
w.adjustHeight();
}
}
// declaring base class chair (saved as wheelchair.java)
class chair
{
public void adjustHeight()
{
System.out.println(“adjusting chair height”);
}
}
//deriving wheelchair class from chair
public class wheelchair extends chair
{
//overriding adjustHeight() method
public void adjustHeight()
{ System.out.println(“adjust wheelchair height”);
}
public static void main (String args[])
{ wheelchair w
w = new wheelchair();
w.adjustHeight();
}
}

You might also like