You are on page 1of 161

Programming with JAVA

• Introduction of java
• Java Virtual Machine
• Java system overview /Java compile-time Environment
• Java Buzzwords
• Difference between C++ and JAVA
Introduction of java
• Java was developed by Jems Goslin at Sun Microsystems in
the early 1990’s.
• The world wide web appeared in 1993, the language has been
enhanced to facilitate programming on web.
• Since then it become one of the most popular language for
web.
• This language was initially called “Oak” but renamed as java in
1995.
• The primary motivation was the need of platform-independent
language that could be used to create software to be
embedded in various customer electronic devices, such as
microwave ovens and remote controls.
• Java never provides any tool to handle operations related to
memory.
• The memory addressing is implemented and controlled by java
virtual machine (JVM).
• Memory addressing mean where the variables are created,
objects are stored, and methods are stored in memory.
Introduction of java
• Java is derived from c++, because most of the
features are taken from c++.
• Sun released the first JDK 1.0 in 1995.
• It promised a platform independent language to
the programmer.
• it was ‘write Once Run anywhere’.
• Sun launched different versions for different
purposes, e.g. J2EE is enterprise edition, use for
server side programming, J2ME is micro edition
used for mobile applications, and J2SE is for
standard edition.
• Introduction of wrapper class makes java a
complete OOP language.
• When a java source file is compiled, a class file
is generated, which is a collection of Byte codes.
Byte codes are portable. These are later
changed to native code by JVM.
• Bytes code are least affected by virus as
compared by executable files. If the Byte code is
affected, these are recognized by the JVM and
not allowed to be executed.
• Java has built-in support for exception handling.
• It has built-in support for multithreading
application development.
• There is a built-in support for networking.
Java Virtual Machine
• JVM system is an interpreter.
• Java virtual machine is a software system that translates and execute java
byte code.
– An instruction set and the meaning of those instructions – the byte codes
– A binary format – the class file format
– An algorithm to verify the class file

Class files Class loader


subsystem

Java PC Native
Method Area Heap method
Stacks Registers
Stacks
Runtime data areas

Native method interface Native


Execution Engine method
libraries
1. Class loader Sub-System performs its task in a
sequential way:
• It loads a class file .
• It checks the correctness of the class file. If any one has
manipulated the class file, then the class file can not be
executed.
• It allocate memory for static variables.
• It sets the default value of all static variable.
• It transforms symbolic reference into direct reference.
2. Method Area
It is a logical memory component of JVM.
This logical section of memory holds the information about
classes and interfaces.
Static variables are treated as class variables, because they
take memory from method area.
3. Heap
• When object or array is created, memory is allocated to
them from heap.
• JVM through the use of new operator allocates memory
from the heap for an object.
• The JVM has a daemon thread known as Garbage
Collector whose task is to free those objects from heap
whose reference is not alive in stack.
4. JAVA Stack
• Method codes are stored inside method area.
• For execution, a method needs memory because of local
variables and the arguments it has taken.
• This purpose is fulfilled by java stack.
5. Program counter register
• It keeps track of the sequence of the program.
• Pc register holds the address of the instructions to be
executed next.
6. Native method stack
• When a java application invokes a native method, that
application does not only use java stack but also use the
native method stack for the execution of native
methods.
• The libraries required for the execution of native
methods are available to the JVM through Java Native
Interface.
7. Execution Engine
• Generate and executes the java byte code.
• It contains an interpreter and Just In Time compiler.
8. Java Native interface

• JNI is used when the programmer has already


developed the code in c/ c++ and wishes to make it
accessible to java code.
• JNI never imposes any restriction on JVM.
• JVM can add support to JNI without affecting other
parts of virtual machine.
• Native methods accesses JVM features by calling JNI
functions.
Java system overview
Java compile-time Environment

Compile-time Run-time Environment


Environment Class
Loader Java
Class
Bytecode Libraries
Java Verifier
Source
(.java)

Java Just in
Java Interprete Time
Byte codes r Compiler Java
move locally Virtual
or through machine
Java network
Compiler
Runtime System

Java
Bytecod Operating System
e
(.class )
Hardware
Java compile-time Environment

• Java is platform independent only for the reason:


– Only depends on the Java Virtual Machine (JVM),
– code is compiled to byte code, which is
interpreted by the resident JVM,
– JIT (just in time) compilers attempt to increase
speed.
Java Buzzwords or features of java
• Simple
– fixes some clumsy features of C++
– no pointers
– automatic garbage collection
– rich pre-defined class library
• Object oriented
– focus on the data (objects) and methods
manipulating the data
– all functions are associated with objects
– almost all data types are objects (files, strings, etc.)
– potentially better code organization and reuse.
cont…...

• Interpreted
– java compiler generate byte-codes, not native
machine code
– The compiled byte-codes are platform-independent
– java byte codes are translated on the fly to machine
readable instructions in runtime (Java Virtual
Machine)
• Portable
– same application runs on all platforms
– The sizes of the primitive data types are always the
same.
– The libraries define portable interfaces
Cont….
• Reliable
– Extensive compile-time and runtime error checking.
– No pointers but real arrays. Memory corruptions or
unauthorized memory accesses are impossible.
– Automatic garbage collection tracks objects usage over
time.
• Secure
The Java language is secure in that it is very difficult to write incorrect
code or viruses that can corrupt/steal your data, or harm hardware such
as hard disks.
– No pointer arithmetic
• Garbage collection
• Array bounds checking
• No illegal data conversions
• Browser level (applies to applets only):
• No local file I/O
Java achieved protection by confining an applet to java execution
environment and not allowing it access to other parts of the computer.

• Multithreaded

– multiple concurrent threads of executions can run simultaneously.


– utilizes a sophisticated set of synchronization primitives (based on
monitors and condition variables paradigm) to achieve this.
• Dynamic

– java is designed to adapt to evolving environment


– libraries can freely add new methods and instance variables without
any effect on their clients
– interfaces promote flexibility and reusability in code by specifying
a set of methods an object can perform, but leaves open how these
methods should be implemented
– can check the class type in runtime
• Distributed
It handles TCP/IP protocols.
Java also support remote Method Invocation (RMI), this
feature enables a program to invoke methods across a
network.
• Architecture- Neutral
The JVM make java ‘write once run any where, any time
forever.
• Robustness
The Java language is robust. It has several features designed
to avoid crashes during program execution, including:
Array and string bounds checking
No jumping to bad method addresses
Interfaces and exceptions
First Java Program
Class Example
{
// your program begins with a call to main
public static void main (String args[])
{
System.out.println (“This is a simple Java program”);
}
}
Save this program Example.java
Compile with javac Example.java
Execute with java Example
Here class is to declare new class is being defined.
Example is an identifier.
Public static void main (string args[])

Public is access specifier then that member may be accessed by code out
side the class in which it is declared.
• Static allows main to be called without having to instantiate a
particular instance of the class. This is necessary since main() is
called by JVM before any objects are made.
• void simply tells the compiler that main() does not return a
value.
• main() is the method called when a java application begins.
• String args [] declares a parameter named args, which is an
array of instances of the class string.
• Objects of type string store character strings. In this case
args receives any command-line arguments present when a
program is executed.
• System.out.println (“This is a simple Java program”);

• println() is a built-in method for providing out puts,


println() is also used to display other type of information's.
• system is a predefined class that provides access to the
system, and out is the output stream that is connected to the
console.
Difference Between C++ and JAVA
• Java is (an interpreted) write once, run anywhere
language.

– The biggest potential stumbling block is speed:


interpreted Java runs in the range of 20 times
slower than C. But: nothing prevents the Java
language from being compiled and there are just-
in-time (JIT) compilers that offer significant speed-
ups.
– Write once, run everywhere does (nearly) NEVER
work with C++, but does (nearly) ALWAYS work
with JAVA.
JAVA vs C++

• You don't have separated HEADER-files defining class-


properties

– You can define elements only within a class.


– All method definitions are also defined in the body of the class.
Thus, in C++ it would look like all the functions are inlined (but
they’re not).
– File- and classname must be identical in JAVA
– Instead of C++ “#include“ you use the “import keyword“.
• For example: import java.awt.*;.
• #include does not directly map to import, but it has a similar feel to
it
JAVA vs C++
• Everything must be in a class.

– There are no global functions or global data. If you want the


equivalent of globals, make static methods and static data within
a class.
– There are no structs or enumerations or unions, only classes.
– Class definitions are roughly the same form in Java as in C++,
but there’s no closing semicolon.
• Java has no preprocessor.

– If you want to use classes in another library, you say import and
the name of the library.
– There are no preprocessor-like macros.
– There is no conditional compiling (#ifdef)
JAVA vs C++
• All the primitive types in Java have specified sizes that
are machine independent for portability.
– On some systems this leads to non-optimized performance
– The char type uses the international 16-bit Unicode character
set, so it can automatically represent most national characters.

• Type-checking and type requirements are much tighter


in Java.
– For example:
• 1. Conditional expressions can be only boolean, not integral.
• 2. The result of an expression like X + Y must be used; you can’t
just say "X + Y" for the side effect.
JAVA vs C++

• There are Strings in JAVA


– Strings are represented by the String-class, they
aren‘t only some renamed pointers
– Static quoted strings are automatically converted into
String objects.
– There is no independent static character array string
like there is in C and C++.
• There are no Java pointers in the sense of C and
C++

– There‘s nothing more to say, except that it is a bit


confusing, that a pointerless language like JAVA has a
‘null-pointer‘ error-message... 
JAVA vs C++
• Although they look similar, arrays have a very different structure and
behavior in Java than they do in C++.

– There’s a read-only length member that tells you how big the array
is, and run-time checking throws an exception if you go out of
bounds.
– All arrays are created on the heap, and you can assign one array to
another (the array handle is simply copied).
• There is a garbage collection in JAVA
– Garbage collection means memory leaks are much harder to cause
in Java, but not impossible. (If you make native method calls that
allocate storage, these are typically not tracked by the garbage
collector.)
– The garbage collector is a huge improvement over C++, and makes
a lot of programming problems simply vanish. It might make Java
unsuitable for solving a small subset of problems that cannot
tolerate a garbage collector, but the advantage of a garbage
collector seems to greatly outweigh this potential drawback.
JAVA vs C++
• There are no destructors in Java.

– There's no need because of garbage collection.


• Java uses a singly-rooted hierarchy, so all objects are
ultimately inherited from the root class Object.

– The inheritance of properties of different classes is handled by


interfaces.
– Java provides the interface keyword, which creates the
equivalent of an abstract base class filled with abstract methods
and with no data members. This makes a clear distinction
between something designed to be just an interface and an
extension of existing functionality via the extends keyword.
– It’s worth noting that the abstract keyword produces a similar
effect in that you can’t create an object of that class.
JAVA vs C++
• Java has method overloading, but no operator
overloading.
• Java has both kinds of comments like C++ does.
• There’s no goto in Java.
– The one unconditional jump mechanism is the break
label or continue label, which is used to jump out of
the middle of multiply-nested loops.
• Java has built-in support for comment documentation
– so the source code file can also contain its own
documentation, which is stripped out and reformatted
into HTML via a separate program. This is a boon for
documentation maintenance and use.
JAVA vs C++
• Java contains standard libraries for GUIs

– Simple, robust and effective way of creating user-interfaces


– Graphical output as part of the language
• Java contains standard libraries for solving specific tasks. C++ relies
on non-standard third-party libraries.

– These tasks include:


• Networking, Database Connection (via JDBC)
• Distributed Objects (via RMI and CORBA)
• Compression, Commerce
• Whatever you want: VoIP, Video-Telephony, MIDI, Games,...
• The availability and standard nature of these libraries allow for
more rapid application development.
JAVA vs C++
• Generally, Java is more robust, via:
– Object handles initialized to null (a keyword).Handles
are always checked and exceptions are thrown for
failures
– All array accesses are checked for bounds violations
– Automatic garbage collection prevents memory leaks
– Clean, relatively fool-proof exception handling
– Simple language support for multithreading
– Bytecode verification of network applets
– Standard GUI
Data Types
• Java defines eight simple (or elemental) types of data:
byte, short, int, long, char, float, double, and
boolean.
• These can be put in four groups:
• Integers This group includes byte, short, int, and
long, which are for whole valued signed numbers.
• Floating-point numbers This group includes float and
double, which represent numbers with fractional
precision.
• Characters This group includes char, which represents
symbols in a character set, like letters and numbers.
• Boolean This group includes Boolean, which is a special
type for representing true/false values
• Integers
• Java defines four integer types: byte, short, int, and long. All of these
are signed, positive and negative values.
• long 64, int 32, short 16, byte 8

• Byte
• The smallest integer type is byte. This is a signed 8-bit type that has a
range from –128 to 127.
• Variables of type byte are especially useful when you’re working with
a stream of data from a network or file. They are also useful when
you’re working with raw binary data that may not be directly
compatible with Java’s other built-in types.
• short
• short is a signed 16-bit type. It has a range from –32,768 to
32,767. It is probably the least-used Java type, since it is defined
as having its high byte first
• int
• The most commonly used integer type is int. It is a signed 32-
bit type that has a range from –2,147,483,648 to 2,147,483,647.
In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays.
• Long

• long is a signed 64-bit type and is useful for those occasions


where an int type is not large enough to hold the desired value.
• The range of a long is quite large. This makes it useful when
big, whole numbers are needed.
• Floating-Point Types
• Floating-point numbers, also known as real numbers, are
used when evaluating expressions that require fractional
precision.
• float
• The type float specifies a single-precision value that uses
32 bits of storage. Single precision is faster on some
processors and takes half as much space as double
precision, but will become imprecise when the values are
either very large or very small
• double
• Double precision, as denoted by the double keyword,
uses 64 bits to store a value. Double precision is actually
faster than single precision on some modern processors
that have been optimized for high-speed mathematical
calculations. All transcendental math functions, such as
sin( ), cos( ), and sqrt( ), return double values.
• Characters
• In Java, the data type used to store characters is char.
However, C/C++ programmers beware: char in Java
is not the same as char in C or C++. In C/C++, char
is an integer type that is 8 bits wide. This is not the
case in Java. Instead, Java uses Unicode to represent
characters. Unicode defines a fully international
character set that can represent all of the characters
found in all human languages, in Java char is a 16-bit
type.
• Booleans
• Java has a simple type, called boolean, for logical
values. It can have only one of two possible values,
true or false.
The Scope and Lifetime of Variables
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Type Conversion and Casting
• Java’s Automatic Conversions
• When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two
conditions are met:
■ The two types are compatible e.g. an int value to a long variable..
■ The destination type is larger than the source type, e.g. the int type is
always large enough to hold all valid byte values.
• Casting Incompatible Types
• If you want to assign an int value to a byte variable, This conversion
will not be performed automatically, because a byte is smaller than an
int. This kind of conversion is sometimes called a narrowing
conversion, since you are explicitly making the value narrower so that
it will fit into the target type.
• (target-type) value,
• If the integer’s value is larger than the range of a byte, it will be
reduced modulo (the remainder of an integer division by the) byte’s
range.
int a;
byte b;
// ...
b = (byte) a;
Example of type conversion
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}}
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Arrays
• Array is a linear homogeneous data structure, it is simply a
collection of similar type elements.
• A specific element of an array is accessed by the index.
• One-dimensional array declaration is:
Data_Type Variable_name []= new Data_Type[size];
or
Data_Type [] Variable_name = new Data_Type[size];
• In general to create an array three steps are to be followed.
(a) Declaration (b) construction ( c) initialization
• Declaration conveys array name and the type of its elements
to the java compiler e.g. int [] int a;
• Construction means calling the new operator to allocate
memory for the array variable.
• During the initialization process, elements of array initialized to
their default values.
• Byte – 0, int -0, float- 0.0 f, char-’\u0000’ , short- 0, long-
0L ,double- 0.0d, boolean-false , reference-null.

public class Demo


{
public static void main(String arg[])
{
int [] arr = new int [2];
System.out.println(arr[0]);
System.out.println(arr[1]);
}
}
Out put: 0 0
import java.util.*;
public class Demo
{
public static void main (String[] args)
{
int [] ar = new int[3];
Scanner sc= new Scanner(System.in);
System.out.println("Enter elements of an array");
for(int i=0;i<3;i++)
ar[i]=sc.nextInt();
System.out.println("elements of array are");
for(int i=0;i<3;i++)
System.out.println(ar[i]);
}
}
The new operator will allocate memory from heap, ar is a reference
type variable, which mean that it will hold the address of memory
location.
stack Heap

mak Mak[0] Mak[1] Mak[2]

6556 1 2 3

6556 6560 6564

Representation of array in memory


Explicit Initialization of Arrays
• Java provides a declaration form to explicitly specify the initial values of the
elements of an array.
• Assuming an n element array, the general form is:
ElementType[] id = {expr0, expr1, ..., exprn-1};
where each expri is an expression that evaluates to type ElementType.

Examples:
int[] fibonacci = {1, 1, 2, 3, 5, 8, 13, 21, 34};
String[] cats = {“bug”, “squeaky”, “paris”, “kitty
kat”};
int[] unit = {1};
Constant Arrays
• As in other declarations, the modifier final can be applied in an array
declaration. The modifier has the usual effect – after its initialization,
the array variable is treated as a constant. In this case, the array
variable cannot change which array it references, however, the values in
the array can be changed!
final int[] B = {10, 20};
• Graphically this would look like the following:

 10 20
B

where indicates that the value of the reference cannot be changed.


B = new int[2]; //illegal: a final cannot be the
//target of an assignment
B[1] = 30; //legal: B[1] is not final
Array Bounds
• Unlike many programming languages, Java automatically
checks that proper array subscripts are used. If a
subscript is determined to be invalid, an exception of
type IndexOutOfBoundsException is generated.
(Unless the program provides exception handling code,
this exception causes the program to terminate.)
• The following code segment contains two misuses of
array sample.
int[] sample = new int[40];
sample[-1] = 0; //subscript too small
sample[40] = 10; //subscript too large
Member Methods and Arrays
• Because an array is a Java object, an array as associated with
it all of the member methods of an Object (e.g., clone()
and equals()). However, the array clone() method is
overridden specifically for arrays.
• In addition to member methods, an array also has a public
final data field length specifying the number of elements
in the array. Designers of Java were quite helpful to
programmer by including this field as it is a convenience not
found in many other programming languages. This allows the
programmer to do the following:
int fibonacci = {1, 1, 2, 3, 5, 7, 13, 21, 34, 55};
for (int i = 0; i < fibonacci.length; ++i){
System.out.println(“Fibonacci Number “ + i +
“ is: “, fibonacci[i]);
}
Sorting elements of an array
import java.util.*;
class Test2 {
public static void main(String args[])
{
int i,j,temp;
int ar[]= new int[4];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the elements of an array");
for(i=0;i<ar.length;i++) {
ar[i]=sc.nextInt();
for(j=0;j<ar.length;j++) {
if(ar[i]<ar[j]) {
temp=ar[j];
ar[j]=ar[i];
ar[i]=temp;
}}}
System.out.println("After sorting values of an Array are:");
for(i=0;i<ar.length;i++) {
System.out.println(ar[i]);
}}}
Passing Arrays to Methods

• Arrays are passed as reference parameters to methods.


• Since arrays are passed as reference parameters their
cell values can be modified in the method.
• Arrays are mutable in methods.
AddArrays.java
import java.util.Scanner;
class AddArrays
{
public static void main (String [] args)
{
Scanner sc=new Scanner(System.in);
int[] array1 = new int[4];
int[] array2 = new int[4];
System.out.println("Enter values in first array:");
for(int i=0;i<4;i++)
array1[i]=sc.nextInt();
System.out.println("Enter values in second array:");
for(int i=0;i<4;i++)
array2[i]=sc.nextInt();
System.out.println ("Array 1 sum: " + sum (array1));
System.out.println ("Array 2 sum: " + sum (array2));
}
public static int sum (int[] x)
{ int sum = 0;
for (int i = 0; i < x.length; i++)
sum = sum + x [i];
return sum;
} }
Copying an array
• An array is an object and like as any object its name actually the
name of the reference to that object. Assigning an array to another
does not duplicate the array. It merely assigns another reference to
the same object.

System.arraycopy( src, srcpos, dest, destpos, length)


arraycopy( a, 4, b, 2, 3);
would copy 3 elements from a[] to b[].
here elements { a[4], a[5], a[6] } get copied to { b[2], b[3], b[4] }
CopyArrays

class CopyArrays
{
public static void main (String [] args)
{
int[] Array1 = {1, 2, 3, 4};
int[] Array2 = {5, 6, 7, 8};
copy (Array1, Array2);
for (int i=0; i< Array1.length; i++)
System.out.println(Array1[i] + " ");
System.out.flush();
for (int i=0; i< Array2.length; i++)
System.out.print (Array2[i] + " ");
System.out.flush();
}
public static void copy (int[] x, int[] y)
{
for (int i=0; i<x.length;i++)
y[i]=x[i];
}
}
Multi-Dimensional Array
• Multi-dimensional arrays are actually array of arrays. It is like a
pointer to an array of pointers.

• Two-Dimensional Array
Syntax:
datatype [ ][ ] variable=new type[n][m];
int [ ][ ] town= new int [3][3];
Heap
1000 6556
Stack
6556
Town[0][0] Town[0][1] Town[0][2]
Town[0
Town ]
96656
1000
1000 Town[1 96656
]
13665
Town[2
]
13665

Representation of multidimensional array in memory


Two dimensional array

class demo
{
public static void main(String args[])
{
int [] [] town= new int [4] [];
system.out.println(town[0]);
system.out.println(town[1]);
system.out.println(town[2]);
}}

Output:
Null
Null
Null
two-dimensional array

int twoD[][] = new int[3][3];


This allocates a 4 by 5 array and assigns it to twoD. Internally this
matrix is implemented as an array of arrays of int.
// Demonstrate a two-dimensional array.
import java.util.*;
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[3][3];
Scanner sc= new Scanner(System.in);
int i, j;
System.out.println("Enter elements of 2D array");
for(i=0; i<3; i++)
for(j=0; j<3; j++) {
twoD[i][j] = sc.nextInt();
}
System.out.println("Elements of 2D array are:");
for(i=0; i<3; i++) {
for(j=0; j<3; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
} }}
Unequal second dimension array
class Demo{
public static void main( String args[])
{
int [] []town= new int[3] [];
town[0] = new int [1];
town[1] = new int [2];
town[2] = new int [3];
int i, j, k=0;
for (i=0;i<3;i++)
for (j=0;j<=i;j++)
{
town [i] [j]= k;
k++;
}
for (i=0;i<3;i++)
{
for (j=0;j<=i;j++)
{
System.out.print ( town [i] [j] +" ");
}
System.out.println();
}}}
Output:
0
1 2
3 4 5
Three-dimensional array
class threeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println(); }
System.out.println();
} } }
This program generates the following output:
00000
00000
00000
00000

0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12

0 0 000
0 2 468
0 4 8 12 16
0 6 12 18 24
Arrays
• Advantages
– Very efficient, quick to access and add to
– Type-safe, can only add items that match the
declared type of the array
• Disadvantages
– Fixed size, some overhead in copying/resizing
– Can’t tell how many items in the array, just how large
it was declared to be
– Limited functionality, need more general functionality
Reading strings using BufferedReader
• Recall from our earlier look at using
BufferedReader that we need to first declare
a BufferedReader object that was directed to
read from the input stream attached to the
standard input device. Once this is done,
reading strings from the keyboard is
straightforward.

BufferedReader stdin = new BufferedReader(


new InputStreamReader(System.in));
BufferedReader Example
import java.io.*;

public class readName {


public static void main(String[] args)throws IOException{

BufferedReader stdin = new BufferedReader(new


InputStreamReader(System.in));
System.out.println("Enter your first name: ");
String firstName = stdin.readLine();
System.out.println("Enter your last name: ");
String lastName = stdin.readLine();
System.out.println("Your name is " + firstName + " "+ lastName
+ ".");
}
}
Wordlength Example
import java.io.*;

public class Wordlength {


public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));

//read the word from the user


System.out.println(“Enter a word: “);
String word = stdin.readLine();

//determine the length of the word


int wordLength = word.length();

//output results
System.out.println(“Word “ + word + “ has a length of “
+ wordLength + “ characters.”);
}
}
Palindrome Example
//Checks words to see if they are palindromes
import java.io.*;

public class Palindrome {


static boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
boolean flag = true;
while ((i<j) && flag){
if (s.charAt(i) != s.charAt(j))
flag = false;
else {i++; j--; }
}
return flag;
}
Palindrome Example (cont.)

public static void main(String args[]) throws IOException {


String s;
BufferedReader stdin = new BufferedReader (new InputStreamReader
(System.in));

System.out.print("A String > ");


System.out.flush();
s = stdin.readLine();

if (isPalindrome(s))
System.out.println(s + " is a palindrome");
else
System.out.println(s + " is not a palindrome");
}
}
Decimal to Binary -- Example
import java.io.*;
public class DecToBinary {
static StringBuffer toBinary(int decVal) {
StringBuffer sb = new StringBuffer("");
if (decVal == 0)
sb.insert(0,"0"); //note insert position
else
while (decVal != 0) {
if (decVal%2 == 0)
sb.insert(0,"0"); //note insert position
else
sb.insert(0,"1"); //note insert position
decVal = decVal / 2;
}
return sb;
}
Decimal to Binary – Example (cont.)

public static void main(String args[]) throws IOException {


int num;
BufferedReader stdin =
new BufferedReader (new InputStreamReader(System.in));

System.out.print("An integer > ");


System.out.flush();
num = Integer.parseInt(stdin.readLine().trim());

System.out.println("Decimal Number: " + num +


" Corresponding Binary Number: " + toBinary(num));
}
}
Taking input from keyboard
import java.io.*;
class test {
public static void main(String args[]) {
String s;
DataInputStream d= new DataInputStream(System.in);
try {
System.out.println("Enter your name");
s=d.readLine();
}
catch(Exception e)
{
}
System.out.println("Welcome to java");
}
}
Using BufferedReader

import java.io.*;
class test1 {
public static void main(String args[])throws Exception {
String s;
int a,b,c;
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter two values");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println("Addition is:" + c);
}}
Reading a character Using Buffered Reader
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Using Scanner class
import java.util.*;
class test3 {
public static void main(String args[])
{
double a, b, c;
System.out.println("Enter The values:");
Scanner sc= new Scanner(System.in);
a=sc.nextDouble();
b=sc.nextDouble();
c=a+b;
System.out.println("The value of addition is :" +c );
}
}
Reading a character

import java.util.Scanner;
public class ScDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a character");
char c = sc.next().charAt(0);
System.out.println("c = "+c);
}
}
Java Garbage Collection
• In java, garbage means unreferenced
objects.
• Garbage Collection is process of reclaiming
the runtime unused memory automatically.
In other words, it is a way to destroy the
unused objects.
• To do so, we were using free() function in C
language and delete() in C++. But, in java
it is performed automatically. So, java
provides better memory management.
Advantage of Garbage Collection

• It makes java memory efficient because


garbage collector removes the
unreferenced objects from heap memory.
• It is automatically done by the garbage
collector(a part of JVM) so we don't need
to make extra efforts.
• Programmer doesn't need to worry about
dereferencing an object.
Can the Garbage Collection be forced explicitly ?

• No, the Garbage


Collection can not be
forced explicitly. We may
request JVM for garbage
collection by
calling System.gc() met
hod. But This does not
guarantee that JVM will
perform the garbage
collection.
gc() method
• The gc() method is used to invoke the garbage
collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
• public static void gc(){}  
• Garbage collection is performed by a
thread called Garbage Collector(GC). This
thread calls the finalize() method before
object is garbage collected.
Simple Example of garbage collection in java

package testgarb;
public class TestGarb {
public void finalize(){
System.out.println("object is garbage collected");
}
void show()
{
System.out.println("method called");
}
public static void main(String args[])
{
TestGarb s1=new TestGarb();
TestGarb s2=new TestGarb();
s1=null;
s2=null;
System.gc();
s1.show();
}
}
• object is garbage collected
• object is garbage collected
finalize() method
• Sometime an object will need to perform some
specific task before it is destroyed such as
closing an open connection or releasing any
resources held. To handle such
situation finalize() method is used. 
• finalize() method is called by garbage collection
thread before collecting object. Its the last
chance for any object to perform cleanup utility.
• Signature of finalize() method
• protected void finalize() { //finalize-code }
Some Important Points to Remember

• finalize() method is defined
in java.lang.Object class, therefore
it is available to all the classes.
• finalize() method is declare
as proctected inside Object class.
• finalize() method gets called only
once by GC threads.
Class

• Class is a new data type.


• This new type can be used to create
objects of that type.
• A class is a template for an object, and an
object is an instance of a class.
The General Form of a Class
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
• The data, or variables, defined within a class are called instance variables.
A Simple Class
class Box {
double width;
double height;
double depth;
}
class declaration only creates a template; it does not create an actual
object.
• To actually create a Box object, you will use a statement like the
following:
• Box mybox = new Box(); // create a Box object called mybox.
• After this statement executes, mybox will be an instance of Box.
Example of a class
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Declaring Objects
• Box mybox = new Box();
• This statement combines the two steps just described. It
can be rewritten like this to show each step more
clearly:
• Box mybox; // declare reference to object
• mybox = new Box(); // allocate a Box object
• The first line declares mybox as a reference to an
object of type Box.
• After this line executes, mybox contains the value null,
which indicates that it does not yet point to an actual
object.
• Any attempt to use mybox at this point will result in a
compile-time error.
• The next line allocates an actual object and assigns a
reference to it to mybox.
Assigning Object Reference Variables
• Box b1 = new Box();
• Box b2 = b1;
• after this fragment executes, b1 and b2 will both refer to the same
object.
• The assignment of b1 to b2 did not allocate any memory or copy
any part of the original object.
• It simply makes b2 refer to the same object as does b1.

b1
Width

Box object
b2 Height

Depth
Assigning Object Reference Variables
• Although b1 and b2 both refer to the same object, they are not
linked in any other way.
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
• Here, b1 has been set to null, but b2 still points to the original
object.
Adding a Method to a class
import java.util.*;
class Box {
class Box {
int width;
int height;
int depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}}
class BoxDemo3 {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
Box mybox1 = new Box();
Box mybox2 = new Box();
System.out.println("Enter the values for first Box:");
mybox1.width = sc.nextInt();
mybox1.height = sc.nextInt();
mybox1.depth = sc.nextInt();
System.out.println("Enter the values for Second Box:");
mybox2.width = sc.nextInt();
mybox2.height = sc.nextInt();
mybox2.depth = sc.nextInt();
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}}
Returning a Value
// Now, volume() returns the volume of a box.
import java.util.*;
class Box {
int width;
int height;
int depth;
double volume() { // compute and return volume
return width * height * depth;
} }
class BoxDemo4 {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
System.out.println("Enter the values for first Box:");
mybox1.width = sc.nextInt();
mybox1.height = sc.nextInt();
mybox1.depth = sc.nextInt();
System.out.println("Enter the values for Second Box:");
mybox2.width = sc.nextInt();
mybox2.height = sc.nextInt();
mybox2.depth = sc.nextInt();
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume(); // get volume of second box
System.out.println("Volume is " + vol); } }
Adding a Method That Takes Parameters
// This program uses a parameterized method.
import java.util.*;
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}}
class BoxDemo5 {
public static void main (String args[]) {
double a, b, c;
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
Scanner sc= new Scanner(System.in);
System.out.println(“enter three values”);
a= sc.nextDouble();
b= sc.nextDouble();
c= sc.nextDouble();
// initialize each box
mybox1.setDim(a, b, c);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol); } }
Constructors
• Constructors are required to create objects for a class. Constructors
are used to initialize the instance variables of an object.
• Constructor declaration looks like method declaration. It must have
the same name as that of the class and have no return type.
• Constructors can be classified into two types, default constructors
and parametarized constructors.
• If you don't define a constructor, then the compiler creates a
default constructor. Default constructors do not contain any
parameters. Default constructors are created only if there are no
constructors defined by us.
• Prametarized constructors are required to pass parameters on
creation of objects. We can overload constructors with different
datatypes as its parameters.
• Use 'this()' to communicate from one constructor to another
constructor in the same class.
• Use 'super()' to communicate with super class constructor.
Constructors
/* Here, Box uses a constructor to initialize the dimensions of a box. */
import java.util.*;
class Box {
double width;
double height;
double depth;
Box() { // This is the constructor for Box.
System.out.println("Constructing Box");
Scanner sc=new Scanner(System.in);
System.out.println("Enter weight, height and depth");
width = sc.nextDouble();
height = sc.nextDouble();
depth = sc.nextDouble(); }
double volume() { // compute and return volume
return width * height * depth;
}}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box(); // declare, allocate, and initialize Box objects
Box mybox2 = new Box();
double vol;
vol = mybox1.volume(); // get volume of first box
System.out.println("Volume is " + vol);
vol = mybox2.volume(); // get volume of second box
System.out.println("Volume is " + vol); } }
Parameterized Constructors
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */
import java.util.*;
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}}
class BoxDemo7 {
public static void main(String args[]) {
double a, b, c;
Scanner sc= new Scanner(System.in);
System.out.println(“enter three values”);
a= sc.nextDouble();
b= sc.nextDouble();
c= sc.nextDouble();
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(a, b, c);
System.out.println(“enter another three values”);
a= sc.nextDouble();
b= sc.nextDouble();
c= sc.nextDouble();
Box mybox2 = new Box(a, b, c);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol); } }
Overloading Methods
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
Scanner sc= new Scanner(System.in);
double result, d;
int a,b;
ob.test();
System.out.println(“enter a value”);
a= sc.nextInt();
ob.test(10);
System.out.println(“enter another value”);
b= sc.nextInt();
ob.test(a, b);
System.out.println(“enter a double value”);
d= sc.nextDouble();
result = ob.test(d);
System.out.println("Result of ob.test(d): " + result); } }
Overloading Constructors
/* Here, Box defines three constructors to initialize the dimensions of a box various ways. */
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}}
Cont..
class OverloadCons {
public static void main(String args[]) {
double a,b,c;
System.out.println(“enter three values”);
a= sc.nextDouble();
b= sc.nextDouble();
c= sc.nextDouble();
Box mybox1 = new Box(a, b, c);
Box mybox2 = new Box();
Box mycube = new Box(b);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
call by value
import java.util.*;
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a,b;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter two values”);
a= sc.nextInt();
b= sc.nextInt();
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}}
– When you pass a simple type to a method, it is passed by value.
– The parameter that receives the argument has no effect outside the
method.
call by reference
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j; }
void meth(Test o) { // pass an object
o.a *= 2;
o.b /= 2; }}
class CallByRef {
public static void main(String args[]) {
int a,b;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter two values”);
a= sc.nextInt();
b= sc.nextInt();
Test ob = new Test(a, b);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); }}
Returning Objects
A method can return any type of data, including class types that you create.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: “ + ob2.a);
}
}
Copy Constructor
• A copy constructor is a constructor that replicates or duplicates an existing
object.
• So it is called copy constructor.
• It takes parameter is a reference to an object of the same class to which
the constructor is depend.
E.g.: A a= new A();
A b= new A(a);
Create a new object ‘b’ that is a duplicate of the object ‘a’ passed to it.

class Copy{
int a, b;
public Copy(int a1, int b1){
a=a1;
b=b1; }
public Copy(Copy c) // Copy constructor
{
a=c.a;
b=c.b; }
void view() {
System.out.println("a=" +a+ "b=" +b);
} }
Copy Constructor
class CopyTest{
public static void main(String args[]) {
Copy test = new Copy(10, 15);
System.out.println("first constructor");
test.view();
Copy test1 = new Copy(test); //invoke copy constructor
System.out.println("Second constructor");
test1.view(); } }
Static keyword
• The static keyword is used in java mainly for memory
management.
• It is used with variables, methods, blocks and nested class.
• It is a keyword that are used for share the same variable or method
of a given class.
• This is used for a constant variable or a method that is the same for
every instance of a class.
• The main method of a class is generally labeled static.
• No object needs to be created to use static variable or call static
methods, just put the class name before the static variable or
method to use them.
• Static method can not call non-static method.
• Static can not refer to super.
Use of Static

• Static variable
• If any variable we declared as static is known as static variable.
• Static variable is used for fulfill the common requirement. For
Example company name of employees,college name of students
etc. Name of the college is common for all students.
• The static variable allocate memory only once in class area at the
time of class loading.
• E.g.: static int i;
• Java static methods:
• Static methods are also similar to static variables, you can access
them with reference to class name, without creating object.
• Inside static methods, you cannot access instance variables or
instance methods. You can only access static variables or static
methods.
• Example of class method:
public static int abs(int a)
Use of Static
import java.util.Scanner;
class Static {
static int a=5;
static int b;
static void math(int c)
{
System.out.println("\nValue of A = " +a);
System.out.println("Value of B = " +b);
System.out.println("Value of C = " +c);
}
static
{
b=a*4;
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int a;
System.out.print("\nEnter a value to perform the given task : " );
a=s.nextInt();
math(a); } }
import java.util.*;
class Static1{
static int rollno;
static String name;
static String college ="IINTM";
Static1(int r,String n){
rollno = r;
name = n; }
static void display (){
System.out.println(rollno+" "+name+" "+college); }
public static void main(String args[]){
int roll;
String name;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Name");
name=sc.nextLine();
System.out.println("Enter roll No:");
roll=sc.nextInt();
Static1 s1 = new Static1(roll,name);
display(); }
static {
System.out.println("Static block will execute first");
} }
Command-Line Arguments
• When you want to pass information into a program when you
run it.
• This is done by passing command-line arguments to main( ).
• A command-line argument is the information that directly
follows the program’s name on the command line when it is
executed.
• Command-line arguments are stored as strings in the String
array passed to main( ).
• Compile this program with class name. java like as normal
program.
• Execute this program by java class name and command-line
arguments.
Command-Line Arguments
class test {
public static void main(String args[])
{
System.out.println("you entered" + args.length + "arguments.");
System.out.println(" First Name:\t" + args[0]);
System.out.println(" Middle Name:\t" + args[1]);
System.out.println( "Last Name:\t" + args[2]);
} }
Second Example----------------------------------------------
class CommandLine {
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}}
This keyword
• The keyword this is useful when you need to refer to instance of the
class from its method.
• The keyword helps us to avoid name conflicts. As we can see in the
program that we have declare the name of instance variable and
local variables same.
• Now to avoid the confliction between them we use this keyword.
Keyword this can be used inside any method to refer to the current
object and it always a reference to the object on which the method
was invoked.
• In the example, this.length and this.breadth refers to the instance
variable length and breadth while length and breadth refers to the
arguments passed in the method.
• We have made a program over this. After going through it you can
better understand.
class Rectangle{
int length, breadth;
void show(int length, int breadth){
this.length=length;
this.breadth=breadth;
}
int calculate(){
return(length*breadth);
}
}
public class UseOfThisOperator{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
rectangle.show(5,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is : " + area);
}
}
Inheritance

• Inheritance is a process, through which we can create a new class


from an existing class.

• Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical.


When a class extends another one class only then we  call it a
single inheritance. The below flow diagram shows that class B
extends only one class which is A. Here A is a parent class of B
and B would be  a child class of A.
• 1.Single Inheritance:
class A A

{
//code
}
class B extends A B

{
//code
}
Inheritance
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Calling of constructor
• Super class default constructor is implicitly invoked when we create the
child class object.
class x {
x()
{
System.out.println("inside super class default constructor");
}
x(int i)
{
System.out.println("inside super class parameterized constructor");
}}
class y extends x {
}
class inheritance {
public static void main(String args[])
{
y ii= new y();
}}
If the super class parameterized constructor is defined and default
constructor is not defined then compile time error arise.
If the child class parameterized constructor is called the
parent class default constructor is also called at that time.
class x
{
x()
{
System.out.println("inside super class default constructor");
}
x(int i)
{
System.out.println("inside super class parameterized constructor");
}}
class y extends x
{
y(int i) {
System.out.println("inside child class parameterized constructor");
} }
class inheritance1 {
public static void main(String args[])
{
y ii= new y(6);
}}
If the super class default constructor is not defined then inside child
class constructor call the parent class parameterized constructor.
class x
{
x(int i)
{
System.out.println("inside super class parameterized constructor");
}}
class y extends x
{
y(int i) {
super(8);
System.out.println("inside child class parameterized constructor");
} }
class inheritance1 {
public static void main(String args[])
{
y ii= new y(6);
}}
import java.util.*;
class A {
int i, j;
A(int a, int b) {
i=a;
j=b; }
void showij() {
System.out.println("i and j: " + i + " " + j);
} }
class B extends A {
int k;
B(int a, int b, int c) {
super(a,b);
k=c; }
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}}
class SimpleInheritance {
public static void main(String args[]) {
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("enter two values");
a=sc.nextInt();
b=sc.nextInt();
A superOb = new A(a,b);
System.out.println("enter three value");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
B subOb = new B(a,b,c);
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
} }
Multilevel Inheritance:
class A
{
//code
} A
class B extends A
{
//code
}
class C extends B B
{
//code
}

C
Multi-level inheritance
class x {
void show()
{
System.out.println("Hello Java.");
}}
class y extends x {
}
class z extends y
{
z()
{
super.show();
}
}
public class Demoinheritance extends z
{
public static void main(String args[])
{
z obj = new z();
}
}
Multiple Inheritance:
• Not supported by Java.
• Diamond Problem…But supported by C++ To
Overcome this problem we have the concept of Interface..

C D

A
Hierarchical Inheritance:
class A
{
//code
}
class B extends A
{
//code A
}
class C extends A
{
//code
}
class D extends A C B D

{
//code
}
class A {
void DisplayA() {
System.out.println("I am in A"); } }
class B extends A {
void DisplayB() {
System.out.println("I am in B"); } }
class C extends A {
void DisplayC() {
System.out.println("I am in C"); } }
public class MainClass {
public static void main(String args[]) {
System.out.println("Calling for subclass C");
C c = new C();
c.DisplayA();
c.DisplayC();
System.out.println("Calling for subclass B");
B b = new B();
b.DisplayA();
b.DisplayB();
}}
Super
• Whenever a subclass needs to refer to its immediate superclass, it can
do so by use of the keyword super.
• super has two general forms.
• The first calls the superclass’ constructor.
• The second is used to access a member of the superclass that has been
hidden by a member of a subclass.
• If the super class instance variable name is the same as that of the
child class or sub-class instance variable name, then super keyword is
used inside the sub-class to access the super class instance variable.
class x{
int i=9; }
class y extends x {
int i=90;
void showsuper() {
System.out.println(i);
System.out.println(super.i);
} }
class super1 {
public static void main(String args[]) {
y a =new y();
a.showsuper();
} }
Method Overriding
 When a method in a subclass has the same name and type
signature as a method in its super class, then the method in the
subclass is said to override the method in the super class.

 When an overridden method is called from within a subclass, it


will always refer to the version of that method defined by the
subclass.

class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}}
Cont…
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Dynamic Method Dispatch
• Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time,
rather than compile time.
• Superclass reference variable can refer to a subclass
object. Java uses this fact to resolve calls to overridden
methods at run time.
• When an overridden method is called through a
superclass reference, Java determines which version of
that method to execute based upon the type of the
object being referred to at the time the call occurs.
• Overridden methods are another way that Java
implements the “one interface, multiple methods” aspect
of polymorphism.
• This determination is made at run time. When different
types of objects are referred to, different versions of an
overridden method will be called.
Dynamic Method Dispatch
// Using run-time polymorphism.
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}}
final

• Final is the keyword which is used to prevent overriding.


• To disallow a method from being overridden, specify
final as a modifier at the start of its declaration.
• Methods declared as final cannot be overridden.

class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}}
final to Prevent Inheritance

• To prevent a class from being inherited.


• To do this, precede the class declaration with final.
• Declaring a class as final implicitly declares all of its methods as
final, too.
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
• As the comments imply, it is illegal for B to inherit A since A is
declared as final.
abstract
• If the class is declared as abstract, we can not create object of
that class.
• The abstract method mean a method which has only declaration.
• The body of abstract method is not defined in abstract class but
defined in child class.
• Reference of a abstract class can be created but object can’t.
x ab; // possible
ab = new x(); //compilation error.
• The methods of abstract class may or may not be abstract.
• If any of the methods of a class is abstract then the class has to
be abstract as well.
• The abstract method are declared inside the abstract class but
defined in their child class.
• If any of the child class does not define the abstract method of
its super class, then that child class has to be declared as an
abstract class.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}}
class B1 {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
abstract
abstract class x
{
int i=10;
public abstract void display();
{
System.out.println("HELLO");
}}
class y extends x
{
int i;
public void display()
{
System.out.println("You are welcome in World of JAVA");
}}
class Demoabstract {
public static void main(String args[])
{
x a=new y();
a.display();
System.out.println(a.i);
}}
Interface

The interface declaration is same as class declaration.


The interface is designed to support multiple inheritance.
public interface x {
}
The interface is implicitly abstract in nature.
It can not be instantiated.
In interface all the methods are public and abstract by
default.
The methods have to be overridden in their corresponding
child class.
The methods belonging to an interface are looked up at
runtime.
In interface the variables are implicitly public, static and final.
The variable declared in an interface become globally
available to all the classes implementing them.
If we are not overriding methods present in the interface
then a compilation error will generate.
Interface..

interface A{
void display();
}
interface B extends A{
void show();
}
class C implements B{
public void display(){
System.out.println("interface A");
}
public void show(){
System.out.println("Interface B");
}
}
class D
{
public static void main(String arr[])
{
C c=new C();
c.display();
c.show();
}}
import java.util.*;
interface IntStack {
void push(int item);
int pop(); }
class FixedStack implements IntStack {
private int stck[];
private int tos;
FixedStack(int size) {
stck = new int[size];
tos = -1; }
public void push(int item) {
if(tos==stck.length-1)
System.out.println("Stack is full.");
else
stck[++tos] = item; }
public int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0; }
else
return stck[tos--]; } }
class IFTest {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int size1, size2;
System.out.println("Enter the size of stack1 and stack2");
size1=sc.nextInt();
size2=sc.nextInt();
FixedStack mystack1 = new FixedStack(size1);
FixedStack mystack2 = new FixedStack(size2);
int a;
System.out.println("Enter elements of stack");
for(int i=0; i<size1; i++) {
a=sc.nextInt();
mystack1.push(a); }
System.out.println("Enter elements of Second stack");
for(int i=0; i<size2; i++) {
a=sc.nextInt();
mystack2.push(a); }
System.out.println("Stack in mystack1:");
for(int i=0; i<size1; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<size2; i++)
System.out.println(mystack2.pop());
}}
Interface
• An interface is not a substitute for multiple inheritance.
• The difference is that the interface approach only
enables you only inherit method descriptions not
implementations.
• If a class implements multiple interface that class must
provide all of the functionality for the methods defined
in the interface.
• Interface are used to define standard behavior that can
be implemented by any class any where in the class
hierarchy.
Example to implement multiple inheritance
import java.util.*;
import java.io.*;
interface Exam {
void percent_cal(); }
class Student {
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2) {
name=n;
roll_no=r;
mark1=m1;
mark2=m2; }
void display() {
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2); }
}
class Result extends Student implements Exam {
Result(String n, int r, int m1, int m2) {
super(n,r,m1,m2);
}
public void percent_cal() {
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}
}
public class Multipleq
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println ("Enter Name of Student");
String name=sc.nextLine();
System.out.println ("Enter RollNo of Student");
int rollno= sc.nextInt();
System.out.println ("Enter Marks of Subject1");
int marks1=sc.nextInt();
System.out.println ("Enter Marks of Subject2");
int marks2=sc.nextInt();
Result R = new Result(name,rollno,marks1,marks2);
R.display();
R.percent_cal();
}
}
Nested Interface
• An interface which is declared inside another interface or class is called
nested interface.
• They are also known as inner interface.
• Since nested interface cannot be accessed directly, the main purpose of
using them is to resolve the namespace by grouping related interfaces (or
related interface and class) together.  
• This way, we can only call the nested interface by using outer class or outer
interface name followed by dot( . ), followed by the interface name.
interface MyInterfaceA
{       
void display();       
interface MyInterfaceB{          
void myMethod();       }   }         
class NestedInterfaceDemo1  implements MyInterfaceA.MyInterfaceB
{       
public void myMethod()
{         
System.out.println("Nested interface method");      }              
public static void main(String args[])
{           
MyInterfaceA.MyInterfaceB obj=  new NestedInterfaceDemo1();      
obj.myMethod();       

}
Difference Between Abstract class and Interface
Packages Introduction
• The main feature of OOP is its ability to support
the reuse of code:
– Extending the classes (via inheritance)
– Extending interfaces
• The features in basic form limited to reusing
the classes within a program.
• What if we need to use classes from other
programs without physically copying them into
the program under development ?
• In Java, this is achieved by using what is
known as “packages”, a concept similar to
“class libraries” in other languages.
143
Packages
• A java package is a group of similar types of
classes, interfaces and sub-packages.
• Package in java can be categorized in two form,
built-in package and user-defined package.
• The benefits of organising classes into packages
are:
– The classes contained in the packages of other
programs/applications can be
reused.
– In packages classes can be unique compared with
classes in other packages. That two classes in two
different packages can have the same name. If there
is a naming clash, then classes can be accessed with
their fully qualified name.
– Classes in packages can be hidden if we don’t want
other packages to access them.
– Packages also provide a way for separating “design”
144
from coding.
Java Foundation Packages
• Java provides a large number of classes groped into
different packages based on their functionality.
• The six foundation Java packages are:
– java.lang
• Contains classes for primitive types, strings, math functions,
threads, and exception
– java.util
• Contains classes such as vectors, hash tables, date etc.
– java.io
• Stream classes for I/O
– java.awt
• Classes for implementing GUI – windows, buttons, menus etc.
– java.net
• Classes for networking
– java.applet
• Classes for creating and implementing applets

145
Using System Packages
• The packages are organised in a hierarchical structure.
For example, a package named “java” contains the
package “awt”, which in turn contains various classes
required for implementing GUI (graphical user interface).
java
lang “java” Package containing
“lang”, “awt”,.. packages;
String Can also contain classes.
awt
Graphics awt Package containing
Font classes
Classes containing
Image
methods
146 …
Advantages of using a package in Java
• These are the reasons why you should use packages in Java:
• Reusability: While developing a project in java, we often feel
that there are few things that we are writing again and again in
our code. Using packages, you can create such things in form
of classes inside a package and whenever you need to perform
that same task, just import that package and use the class.
• Better Organization: Again, in large java projects where we
have several hundreds of classes, it is always required to group
the similar types of classes in a meaningful package name so
that you can organize your project better and when you need
something you can quickly locate it and use it, which improves
the efficiency.
• Name Conflicts: We can define two classes with the same
name in different packages so to avoid name collision, we can
use packages.
Creating Packages
• Java supports a keyword called “package” for creating
user-defined packages. The package statement must
be the first statement in a Java source file (except
comments and white spaces) followed by one or more
classes.
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
• Package name is “myPackage” and classes are
considered as part of this package; The code is saved
in a file called “ClassA.java” and located in a directory
148 called “myPackage”.
Creating Sub Packages
• Classes in one or more source files can be part of the same
packages.
• As packages in Java are organised hierarchically, sub-
packages can be created as follows:
– package myPackage.Math
– package myPackage.secondPakage.thirdPackage
• Store “thirdPackage” in a subdirectory named “myPackage\
secondPackage”. Store “secondPackage” and “Math” class in a
subdirectory “myPackage”.

149
Accessing a Package
• As indicated earlier, classes in packages can be
accessed using a fully qualified name or using a
short-cut as long as we import a corresponding
package.
• The general form of importing package is:
– import package1[.package2][…].classname
– Example:
• import myPackage.ClassA;
• import myPackage.secondPackage
– All classes/packages from higher-level package can
be imported as follows:
• import myPackage.*;

150
Protection and Packages
• All classes (or interfaces) accessible to all others
in the same package.
• Class declared public in one package is
accessible within another. Non-public class is not
• Members of a class are accessible from a
difference class, as long as they are not private
• protected members of a class in a package are
accessible to subclasses in a different class

151
Visibility - Revisited
• Public keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
• Private fields or methods for a class only visible
within that class. Private members are not visible
within subclasses, and are not inherited.
• Protected members of a class are visible within
the class, subclasses and also within all classes
that are in the same package as that class.

152
Visibility Modifiers
Accessible to: public protected Package private
(default)

Same Class Ye s Ye s Ye s Ye s

Class in package Ye s Ye s Ye s No

Subclass in Ye s Ye s No No
different package

Non-subclass Ye s No No No
different package

153
Adding a Class to a Package
• Consider an existing package that contains a
class called “Teacher”:
package pack1;
public class Teacher
{
// class body
}

• This class is stored in “Teacher.java” file within


a directory called “pack1”.
• How do we a new public class called “Student”
to this package.
154
Packages and Name Clashing
• When packages are developed by different
organizations, it is possible that multiple packages will
have classes with the same name, leading to name
package pack2;
package pack1;
classing.
class Teacher class Student

class Student class Courses

• We can import and use these packages like:


– import pack1.*;
– import pack2.*;
– Student student1; // Generates compilation error
155
Handling Name Clashing
• In Java, name classing is resolved by accessing
classes with the same name in multiple
packages by their fully qualified name.
• Example:
import pack1.*;
import pack2.*;
pack1.Student student1;
pack2.Student student2;
Teacher teacher1;
Courses course1;

156
Extending a Class from Package

• A new class called “Professor” can be


created by extending the “Teacher” class
defined the package “pack1” as follows:
import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}

157
Package Example
package emppack;
public class Company {
String compname, address;
public Company(String c, String a)
{
compname=c;
address=a;
}
public void display()
{
System.out.println("Company Details");
System.out.println("Company Name:"+ compname);
System.out.println("Company Address:"+ address);
}}

158
Package Example
package emppack;
public class Employee
{
int empid;
String empname, empaddr;
public Employee(int i, String n, String a){
empid=i;
empname=n;
empaddr=a;
}
public void displayinfo()
{
System.out.println("Employee Details");
System.out.println("Employee ID:"+empid);
System.out.println("Employee Name:"+empname);
System.out.println("Employee Address"+empaddr);
}
} 159
import emppack.Employee;
import emppack.Company;
import java.util.*;
class PackageDemo {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter company name");
String cname=sc.nextLine();
System.out.println("Enter company Address");
String caddr=sc.nextLine();
System.out.println("Enter Employee name");
String ename=sc.nextLine();
System.out.println("Enter Employee Address");
String eaddr=sc.nextLine();
System.out.println("Enter EmployeeId");
int eid=sc.nextInt();
Company c= new Company(cname,caddr);
Employee e=new Employee(eid,ename, eaddr);
c.display();
e.displayinfo(); } }
160
Summary

• Packages allow grouping of related classes


into a single united.
• Packages are organised in hierarchical
structure.
• Packages handle name classing issues.
• Packages can be accessed or inherited
without actual copy of code to each
program.
161

You might also like