Java Programming

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 177

Java Programming

Design Goals
• Java technology must enable the development
of
– secure,
– high performance,
– and highly robust applications on multiple
platforms in heterogeneous, distributed networks.
• must be architecture neutral, portable, and
dynamically adaptable.
■Simple
■ Secure
■ Portable
■ Object-oriented
■ Robust
■ Multithreaded
■ Architecture-neutral
■ Interpreted
■ High performance
■ Distributed
Program Structure

• The source code for an Java program consists of one or more


compilation units. Each compilation unit can contain only the
following
– a package statement
– import statements
– class declarations
– interface declarations
• When Java source code is compiled, the result is Java
bytecode.
• Java bytecode consists of machine-independent instructions
that can be interpreted efficiently by the Java runtime system.
JVM

• The JVM is an abstract computing machine,


having an instruction set that uses memory.
Virtual machines are often used to implement
a programming language. The JVM is the
cornerstone of the Java programming
language. It is responsible for Java's cross-
platform portability and the small size of its
compiled code.
• The Solaris JVM is used to execute Java
applications. The Java compiler, javac, outputs
bytecodes and puts them into a .class file. The
JVM then interprets these bytecodes, which can
then be executed by any JVM implementation,
thus providing Java's cross-platform portability.
The next two figures illustrate the traditional
compile-time environment and the new
portable Java compile-time environment
Lexical Issues

• Comments
• Identifiers
• Keywords
• Literals

– Integer Literals
– Floating Point Literals
– Boolean Literals
– Character Literals
– String Literals

• Operators and Miscellaneous Separators


• The Java language has three styles of comments:
• // text :- All characters from // to the end of the line are
ignored.

• /* text */ :-All characters from /* to */ are ignored.

• /** text */ :- These comments are treated specially when


they occur immediately before any declaration.

• They are illegal in any other place in the code.


• These comments indicate that the enclosed text should be
included in automatically generated documentation as a
description of the declared item.
Identifiers

• Identifiers must start with a letter, underscore


("_"), or dollar sign ("$");
• subsequent characters can also contain digits
(0-9)
• legal
– The characters "A" through "Z"
– The characters "a" through "z"
– All Unicode characters with a character number
above hex 00C0
Keywords
Literals
Literals are the basic representation of any integer, floating point, boolean, character, or string value.

• Integer Literals
– Integers can be expressed in decimal (base 10),
hexadecimal (base 16), or octal (base 8) format
– A leading 0 (zero) on an integer literal means it is
in octal; a leading 0x (or 0X) means hexadecimal.
– A literal can be forced to be long by appending an
L or l to its value.
The following are all legal integer literals:
2, 2L , 0777 ,0xDeadBeef
Floating Point Literals

• A floating point literal can have the following


parts: a decimal integer, a decimal point ("."), a
fraction (another decimal number), an exponent,
and a type suffix. The exponent part is an e or E
followed by an integer, which can be signed
• 3.1415, 3.1E12 , .1e12, 2E12
• 2.0d or 2.0D :- double
• 2.0f or 2.0F or 2.0 :-float
• Boolean Literals
– Has true and false value
• Character Literals
– A character literal is a character (or group of characters
representing a single character) enclosed in single quotes.
• String Literals
• A string literal is zero or more characters
enclosed in double quotes.
• Each string literal is implemented as a String
object (not as an array of characters)
"" ( the empty string )
"\""
"This is a string"
"This is a \ two-line string"
Operators and Miscellaneous Separators
Data Types
• Numeric Types
– Integer Types
– Floating Point Types
– Character Types
• Boolean Types
• Arrays
• Integers are similar to those in C and C++
Type Conversion and Casting
• an automatic type conversion will take place if
the following two conditions are met:
■ The two types are compatible.
■ The destination type is larger than the source
type.
For example,
– the int type is always large enough to hold all valid
byte values, so no explicit cast statement is
required.
• The numeric types, including integer and
floating-point types, are compatible with each
other.
• The numeric types are not compatible with
char or boolean.
• char and boolean are not compatible with
each other.
Casting Incompatible Types
• want to assign an int value to a byte variable?
• a byte is smaller than an int
• called a narrowing conversion
• Form : (target-type) value

int a;
byte b;
// ...
b = (byte) a;
// 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);
}
}
Why the output is?

• When the value 257 is cast into a byte variable,


the result is the remainder of the division of 257
by 256
• value is reduced modulo 256, which in this case is
67.
Type Promotion

• Java automatically promotes each byte or short operand to int


when evaluating an expression.

• This means that the sub expression a * b is performed using


integers—not bytes
Promotion example
Arrays

• Arrays in the language are first class objects.


They replace pointer arithmetic.
• All objects (including arrays) are referred to
by pointers that cannot be damaged by being
manipulated as numbers.
• Arrays are created using the new operator:
char s[] = new char[30];
Demo
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
// An improved version of the previous program.
class AutoArray
{
public static void main(String args[]) {

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };

System.out.println("April has " + month_days[3] + " days.");


}
}
Multidimensional Arrays
• int twoD[][] = new int[4][5];
Manually fixing other dimension
Want o/p like below

• Program?
Control and Looping
• While
• Do-while
• For
• Java 5.0 introduced a new “enhanced” form of the for loop
– that is designed to be convenient for processing data structures
– for example, a list is a data structure that consists simply of a
sequence of items.
– The enhanced for loop can be used to perform the same
processing on each of the enum constants that are the possible
values of an enumerated type.
• To give a concrete example, suppose that the following
enumerated type has been defined to represent the days of
the week:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY }
for ( Day d : Day.values() )
{
System.out.print( d );
System.out.print(" is day number ");
System.out.println( d.ordinal() );
}
o/p
• MONDAY is day number 0
• TUESDAY is day number 1
• WEDNESDAY is day number 2
• THURSDAY is day number 3
• FRIDAY is day number 4
• SATURDAY is day number 5
• SUNDAY is day number 6
if Statement
switch
playing cards

• How to print a random card name such


as ”Queen of Clubs”
Using random function in java

•Math. random() is used to return a pseudorandom double type number


greater than or equal to 0.0 and less than 1.0.
•The default random number always generated between 0 and 1.
• If you want to specific range of values, you have to multiply the returned
value with the magnitude of the range.
Using random function in java

•Math. random() is used to return a pseudorandom double type number


greater than or equal to 0.0 and less than 1.0.
•The default random number always generated between 0 and 1.
• If you want to specific range of values, you have to multiply the returned
value with the magnitude of the range.

How to create a  deck of 52 playing cards?


Creating deck of playing cards
Creating deck of playing cards

How to shuffle these cards in a deck?


Shuffling the deck
Strings
• string: An object storing a sequence of text
characters.
• Indexes:
• Characters of a string are numbered with 0-
based indexes:
• String name = "Ultimate";
String methods

• These methods are called using the dot notation:

• String starz = "Yeezy & Hova ";


• System.out.println(starz.length()); // 12
String method examples

• Methods like substring and toLowerCase build and


return a new string, rather than modifying the
current string.
Suggests a baby name based on parents'
names.
Suggests a baby name based on parents'
names and gender.
Example Output:
Parent 1 first name? Danielle
Parent 2 first name? John
Child Gender? f
Suggested baby name: JODANI
Parent 1 first name? Danielle
Parent 2 first name? John
Child Gender? Male
Suggested baby name: DANIJO
Comparing strings
• Relational operators such as < and == fail on
objects
• The equals() method :
• Technically this is a method that returns a
value of type boolean ,the type used in logical
tests.
String test methods

String name = console.next();


if(name.endsWith("Kweli"))
{
System.out.println("Pay attention.");
}
else if(name.equalsIgnoreCase("NaS"))
{
System.out.println(" never.");
}
Type char
• A primitive type representing single characters
• Each character inside a String is stored as a char
value
• Literal char values are surrounded with
apostrophe (single-quote) marks, such as 'a' or '4'
or '\n' or '\'‘
• It is legal to have variables, parameters, returns
of type char
• char values can be concatenated with strings.
The charAt method
• The chars in a String can be accessed using the
charAt method.
String food = "cookie";

char firstLetter = food.charAt(0); // 'c‘

System.out.println(firstLetter + " is for " + food);

• You can use a for loop to print or examine


each character.
String major = "CSE";
for (int i = 0; i < major.length(); i++) {
char c = major.charAt(i);
System.out.println(c);
}
char vs. String
• "h" is a String 'h' is a char
• String is an object; it contains methods
• char is primitive; you can't call methods on it
char vs. int
• All char values are assigned numbers internally by the
computer, called ASCII values.
Examples:
'A' is 65, 'B' is 66, ' ' is 32
'a' is 97, 'b' is 98, '*' is 42
• Mixing char and int causes automatic conversion to int.
– 'a' + 10 is 107 , 'A' + 'A' is 130
• To convert an int into the equivalent char, type-cast it.
– (char) ('a' + 2) is 'c'
Comparing char values
• You can compare char values with relational
operators:
• 'a' < 'b' and 'X' == 'X' and 'Q' != 'q'
• An example that prints the alphabet:
Comparing char values
• You can compare char values with relational
operators:
• 'a' < 'b' and 'X' == 'X' and 'Q' != 'q'
• An example that prints the alphabet:

Write a program to test the given string if plural or


singular
StringBuffer class
• java StringBuffer class is used to create mutable
(modifiable) string.

• The StringBuffer class in java is same as String class


except it is mutable i.e. it can be changed.
• Constructor:
– StringBuffer()
– StringBuffer(String str)
– StringBuffer(int capacity)

– Eg: StringBuffer sb=new StringBuffer("Hello ");
– StringBuffer sb=new StringBuffer();
methods
• append() eg: sb.append("Java");

• insert() eg:sb.insert(index,"Java")

• replace() eg:sb.replace(beginindex,endindex,string)

• reverse()

• delete() eg:sb.delete(beginindex,endindex)
StringBuilder class
• Java StringBuilder class is used to create
mutable (modifiable) string.
• The Java StringBuilder class is same as
StringBuffer class except that it is non-
synchronized
• Constructor:
– StringBuilder()
– StringBuilder(String str)
eg:eg:StringBuilder sb=new StringBuilder("Hello ");
– StringBuilder(int length)
•StringBuffer is synchronized and therefore thread-safe.
StringBuilder is compatible with StringBuffer API but with no
guarantee of synchronization.

•Because it's not a thread-safe implementation, it is faster and it is


recommended to use it in places where there's no need for thread
safety.
Class Definition

A class contains a name, several variable declarations


(instance variables) and several method declarations. All are
called members of the class.
General form of a class:
class classname {
type instance-variable-1;

type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }

type method-name-m(parameter-list) { … }
}

L 4.7
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }

L 4.8
Methods

• General form of a method definition:


type name(parameter-list) {
… return value;

}
• Components:
1) type - type of values returned by the method. If a method
does not return any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
4) return value indicates what value is returned by the
method.

L 5.4
Example: Method

• Classes declare methods to hide their internal data


structures, as well as for their own internal use: Within a
class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
L 5.5
Parameterized Method

• Parameters increase generality and applicability of a


method:
• 1) method without parameters
int square() { return 10*10; }
• 2) method with parameters
int square(int i) { return i*i; }
• Parameter: a variable receiving value at the time the
method is invoked.
• Argument: a value passed to the method when it is
invoked.
L 5.6
Static Methods
• Place a keyword “static” before the return
type in the method’s declaration
• can call any static method by specifying the
name of the class in which the method is
declared, followed by a dot (.) and the method
name
Example :Math Class
• Class Math provides a collection of methods
that enable you to perform common
mathematical calculations.
• For example, you can calculate the square root
of 900.0 with the static method call
Constructor

• A constructor initializes the instance variables of an object.


• It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default
return type of a class
• constructor is the same class
• When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.

L 5.1
Example: Constructor

class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}

L 5.2
Parameterized Constructor

class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
L 5.3
Method Overloading
• It is legal for a class to have two or more methods
with the same name.

• However, Java has to be able to uniquely associate


the invocation of a method with its definition
relying on the number and types of arguments.

• Therefore the same-named methods must be


distinguished:

1) by the number of arguments, or


2) by the types of arguments

• Overloading and inheritance are two ways to


implement polymorphism.
L 7.1
Example: Overloading
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}

void test(int a)
{
System.out.println("a: " + a);
}

void test(int a, int b)


{
System.out.println("a and b: " + a + " " + b);
}

double test(double a)
{
System.out.println("double a: " + a); return a*a;
}
}
L 7.2
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): "
}
}
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}

L 7.3
Method Overloading
• It is legal for a class to have two or more methods
with the same name.

• However, Java has to be able to uniquely associate


the invocation of a method with its definition
relying on the number and types of arguments.

• Therefore the same-named methods must be


distinguished:

1) by the number of arguments, or


2) by the types of arguments

• Overloading and inheritance are two ways to


implement polymorphism.
L 7.1
Example: Overloading
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}

void test(int a)
{
System.out.println("a: " + a);
}

void test(int a, int b)


{
System.out.println("a and b: " + a + " " + b);
}

double test(double a)
{
System.out.println("double a: " + a); return a*a;
}
}
L 7.2
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}

L 7.3
Parameter Passing

Two types of variables:


1) simple types
2) class types

Two corresponding ways of how the arguments are


passed to methods:

1)by value a method receives a cope of the original


value; parameters of simple types

2) by reference a method receives the memory address


of the original value, not the value itself; parameters of
class types
L 7.4
Call by value
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call: “);
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}
}

L 7.5
Objects as Parameters
class Test
(Call by reference)
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}

boolean equals(Test o)
{
if(o.a == a && o.b == b)
{
return true;
}
else
{
return false;
}
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
Call by reference
• As the parameter hold the same address as the argument, changes to the
object inside the method do affect the object used by the argument:
class CallByRef {
public static void main(String args[ ]) {
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: “);
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
}
}

L 7.6
class Test {
Returning Objects
int a;
Test(int i) {
a = i;
} Output:
Test incrByTen() { ob1.a: 2
Test temp = new Test(a+10); ob2.a: 12
return temp; ob2.a after second increase: 22
}
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);
}
Introduction to Wrapper Classes
Java provides 8 primitive data types.
• They are called “primitive” because they are not
created from classes.
• Java provides wrapper classes for all of the
primitive data types.
•A wrapper class is a class that is “wrapped around”
a primitive data type.
• The wrapper classes are part of java.lang so to use
them, there is no import statement required.
Wrapper Classes
• Wrapper classes allow you to create objects to
represent a primitive.

• Wrapper classes are immutable, which means that once you


create an object, you cannot change the object’s value.

• To get the value stored in an object you must call a method.

• Wrapper classes provide static methods that are very useful


Wrapper classes
• Character
• String
• Byte
• Integer
• Long
• Double
• Float
• Short
Character Testing and Conversion With The
Character Class
• The Character class allows a char data type to
be wrapped in an object.
• The Character class provides methods that
allow easy testing, processing, and conversion
of character data
The Character Class
Creating a Wrapper Object
• To create objects from these wrapper classes,
you can pass a value to the constructor:

Integer number = new Integer(7);

• You can also assign a primitive value to a


wrapper class object:
The Parse Methods
• A string containing a number, such as “127.89,
can be converted to a numeric data type.
• Each of the numeric wrapper classes has a static
method that converts a string to a number.
• The Integer class has a method that converts a
String to an int
• The Double class has a method that converts a
String to a double
• The parse methods all throw a
NumberFormatException if the String object does
not represent a numeric value
The toString Methods

• Each of the numeric wrapper classes has a


static toString method that converts a umber
to a string.
• The method accepts the number as its
argument and returns a string representation
of that number.
– int i = 12;
– double d = 14.95;
– String str1 = Integer.toString(i);
– String str2 = Double.toString(d);
MIN_VALUE and MAX_VALUE

• The numeric wrapper classes each have a set


of static final variables
– MIN_VALUE and
– MAX_VALUE
• These variables hold the minimum and
maximum values for a particular data type.
Array of Objects
Public static void main(String[]args)
{
Student[]studentArray=newStudent[7];
for(inti=0;i<studentArray.length;i++)
{
studentArray[i]=newStudent();
} public class Student
{
}
}
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables and
methods.

• Encapsulation, safely sealing data within the capsule of


the class Prevents programmers from relying on details of
class implementation, so you can update without worry

• Helps in protecting against accidental or wrong usage.

• Keeps code elegant and clean (easier to maintain)


Access Modifiers: Public, Private, Protected

• Public:
– Keyword applied to a class, makes it available / visible
every where . Applied to a method or variable,
completely visible.
• Default(Novisibilitymodifierisspecified):
– It behaves like public inits package and private in other
packages.
• Default Public key word applied to aclass, makes it
available / visible every where. 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.
Garbage Collection
finalize() Method
public class TestGarbage1
{  
 public void finalize()
{
System.out.println("object is garbage collected");
}  
 public static void main(String args[]){  
  TestGarbage1 s1=new TestGarbage1();  
  TestGarbage1 s2=new TestGarbage1();  
  s1=null;  
  s2=null;  
  System.gc();  
 }  
}  
Inheritance
• Definitions: A class that is derived from another class is called
a subclass (also a derived class, extended class, or child class). The
class from which the subclass is derived is called a superclass (also
a base class or a parent class).

• When you want to create a new class and there is already a class that
includes some of the code that you want, you can derive your new
class from the existing class.

• A subclass inherits all the members (fields, methods, and nested


classes) from its superclass.

• Constructors are not members, so they are not inherited by subclasses


public class Bicycle {

// the Bicycle class has three fields


public int cadence;
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int startCadence, int startSpeed,
int startGear) {
gear = startGear;
cadence = startCadence; public void setGear(int newValue) {
speed = startSpeed; gear = newValue;
} }

// the Bicycle class has four methods public void applyBrake(int decrement) {
public void setCadence(int newValue) { speed -= decrement;
cadence = newValue; }
}
public void speedUp(int increment) {
speed += increment;
}

}
public class MountainBike extends Bicycle {

// the MountainBike subclass adds one field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}

// the MountainBike subclass adds one method


public void setHeight(int newValue) {
seatHeight = newValue;
}
}
• The inherited fields can be used directly, just like any other fields.

• You can declare a field in the subclass with the same name as the one in the superclass,
thus hiding it (not recommended).

• You can declare new fields in the subclass that are not in the superclass.

• The inherited methods can be used directly as they are.

• You can write a new instance method in the subclass that has the same signature as the one in
the superclass, thus overriding it.

• You can write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it.

• You can declare new methods in the subclass that are not in the superclass.

• You can write a subclass constructor that invokes the constructor of the superclass, either
implicitly or by using the keyword super.
Casting Objects
• public MountainBike myBike = new MountainBike();
– MountainBike is descended from Bicycle and Object. Therefore,
a MountainBike is a Bicycle and is also an Object
– it can be used wherever Bicycle or Object
– The reverse is not necessarily true: a Bicycle may be a MountainBike, but it
isn't necessarily.

• Object obj = new MountainBike();//implicit casting


– then obj is both an Object and a MountainBike

• MountainBike myBike = obj; //error


– because obj is not known to the compiler to be a MountainBike

• MountainBike myBike = (MountainBike)obj; //explicit


Overriding and Hiding Methods
• An instance method in a subclass with the same signature and return
type as an instance method in the superclass overrides the
superclass's method.
• Static Methods

– If a subclass defines a static method with the same signature as a static


method in the superclass, then the method in the subclass hides the one in
the superclass

– The version of the overridden instance method that gets invoked is the one
in the subclass.

– The version of the hidden static method that gets invoked depends on
whether it is invoked from the superclass or the subclass.
public class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat");
}

public static void main(String[] args) {


Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
} The static method in Animal
} The instance method in Cat
Polymorphism
• Subclasses of a class can define their own
unique behaviors and yet share some of the
same functionality of the parent class.

public void printDescription(){


System.out.println("\nBike is " + "in gear " + this.gear
+ " with a cadence of " + this.cadence +
" and travelling at a speed of " + this.speed + ". ");
}
public class MountainBike extends Bicycle {
private String suspension;

public MountainBike(
int startCadence,
int startSpeed,
int startGear,
String suspensionType){
super(startCadence,
startSpeed,
startGear);
this.setSuspension(suspensionType);
}
public void setSuspension(String suspensionType) {
this.suspension = suspensionType;
public String getSuspension(){
}
return this.suspension;
}
public void printDescription() {
super.printDescription();
System.out.println("The " + "MountainBike has a" +
getSuspension() + " suspension.");
}
}
public class RoadBike extends Bicycle{
// In millimeters (mm)
private int tireWidth;

public RoadBike(int startCadence,


int startSpeed,
int startGear,
int newTireWidth){
super(startCadence,
startSpeed,
startGear);
this.setTireWidth(newTireWidth);
}

public int getTireWidth(){ public void setTireWidth(int newTireWidth){


return this.tireWidth; this.tireWidth = newTireWidth;
} }

public void printDescription(){


super.printDescription();
System.out.println("The RoadBike" + " has " + getTireWidth() +
" MM tires.");
}
}
public class TestBikes {
public static void main(String[] args){
Bicycle bike01, bike02, bike03;

bike01 = new Bicycle(20, 10, 1);


bike02 = new MountainBike(20, 10, 5, "Dual");
bike03 = new RoadBike(40, 20, 8, 23);

bike01.printDescription();
bike02.printDescription();
bike03.printDescription();
}
}

Bike is in gear 1 with a cadence of 20 and travelling at a speed of 10.

Bike is in gear 5 with a cadence of 20 and travelling at a speed of 10.


The MountainBike has a Dual suspension.

Bike is in gear 8 with a cadence of 40 and travelling at a speed of 20.


The RoadBike has 23 MM tires.
A Superclass Variable Can Reference a Subclass Object

class Box {
double width;
double height; class BoxWeight extends Box {
double depth; double weight;
// construct clone of an object
BoxWeight(double w, double h,
double d, double m) {
Box(double w, double h, double d) { width = w;
width = w; height = h;
height = h; depth = d;
depth = d; weight = m;
} }
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class RefDemo
{
public static void main(String args[])
{
BoxWeight weightbox = new BoxWeight( 5.0, 7.0, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();

// assign BoxWeight reference to Box reference


plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
Using super
• Whenever a subclass needs to refer to its immediate
super class, it can do so by use of the keyword super
• Two forms
– The first calls the super class’ constructor.
– The second is used to access a member of the super class
that has been hidden by a member of a subclass.

• super(parameter-list);
• super.member
Dynamic Method Dispatch
Using Abstract Classes
Using final to Prevent Overriding
Using final to Prevent Inheritance
Interfaces

access interface name {


return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
• Interface can contain variables initialized with
value
• For implementing class these variables are
constants like final
• Interface can be extended

Nested and Inner Classes
• defining a class within another class
• The scope of a nested class is bounded by the scope of its
enclosing class
• class B is defined within class A, then B is known to A, but
not outside of A.
• A nested class has access to the members, including
private members, of the class in which it is nested
• The enclosing class does not have access to the members
of the nested class
• While nested classes are not used in most day-to-day
programming, they are particularly helpful when handling
events in an applet
• An inner class is a non-static nested class.
• It has access to all of the variables and methods of its outer
class
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) { Output from this application is shown here:
Outer outer = new Outer(); display: outer_x = 100
outer.test();
} }
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
void showy()
{
System.out.println(y); // error, y not known here!
} class InnerClassDemo {
} public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
// This program will not compile. }
Packages
• Java provides a mechanism for partitioning the class name space
into more manageable chunks
• The package is both a naming and a visibility control mechanism.
• Java uses file system directories to store packages.
• Avoiding naming conflicts
• Package in java can be categorized in two form, built-in package
and user-defined package
• Defining a Package
– package pkg;
• can create a hierarchy of packages
– package pkg1[.pkg2[.pkg3]];
– package java.awt.image;
// A simple package
class AccountBalance {
package MyPack;
public static void main(String args[]) {
class Balance {
Balance current[] = new Balance[3];
String name;
current[0] = new Balance("K. J. Fielding", 123.23);
double bal;
current[1] = new Balance("Will Tell", 157.02);
Balance(String n, double b) {
current[2] = new Balance("Tom Jackson", -12.33);
name = n;
for(int i=0; i<3; i++) current[i].show();
bal = b;
}
}
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
How to compile java package
Javac -d classes directory java filename
•Eg:
Javac -d classes /home/Balance.java(linux)
Or
Javac -d classes c:/home Balance.java (windows)

Dot is used to store in the working directory

The -d switch specifies the destination where to put the generated


class file
How to run java package program
• Eg: java mypack.Balance
• Hero Honda motor bike company is planning for “Bikes for
the Future” in which they are going to launch Low Cost to
high cost bikes with Ultra Low emission to Low Emission
vehicles. The bikes are also designed to run under Petrol.
The Cubic capacity varies from 99.2cc to 120.9cc. Create a
class BikeDesign with data members like bike model, cost
and no. of gears as class variables. Store the details of
bikes using array of objects. Write a java program that
accepts inputs as cost and number of gears and displays
the model of the bike with all its features. ( Abstract Class
is Mandatory).
Exception Handling
• Java exception is an object that describes an exceptional
(that is, error) condition that has occurred in a piece of
code.
• Exceptions can be generated by the Java run-time
system, or they can be manually generated by your code.
• System-generated exceptions are automatically thrown
by the Java run-time system.
• To manually throw an exception, use the keyword throw.

• try, catch, throw, throws, and finally


try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}

• Any code that absolutely must be executed before a


method returns is put in a finally block.
Exception Types
• All exception types are subclasses of the built-
in class Throwable.
• RuntimeException :Exceptions of this type are
automatically defined for the programs
• division by zero and invalid array indexing.
• Error:Stack overflow is an example of error
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}

• Java run-time system detects the attempt to


divide by zero, it constructs a new exception
object and then throws this exception.
• the execution of Exc0 stops
class Exc2
{
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Multiple catch Clauses
• can specify two or more catch clauses
• each catching a different type of exception
• When an exception is thrown, each catch
statement is inspected in order, and the first
one whose type matches that of the exception
is executed.
Java’s Built-in Exceptions
unchecked exception

• java.lang
Cont..

unchecked exceptions because the


compiler does not check to see if a method handles or throws these exceptions
Checked
User Defined Exceptions
class UserDefinedException
{
//MyException.java static void compute(int num) throws MyException {
class MyException extends Exception { System.out.println("Called computer(" + num + "]");
private int detail; if (num < 10)
{
MyException(int a) { System.out.println("Number Is Less Than 10");
detail = a; }
} else
throw new MyException(num);
public String toString() { }
return "MyException[" + detail + "}";
public static void main(String args[]) {
} try {
} compute(9);
compute(10);

} catch (MyException me) {


System.out.println("Caught " + me);
}
}}
Methods in Throwable class
• String toString( ) : Gives you a String object and description of the exception.
This  method is called by the println ( ) method when an object of Throwable is
passed to it as argument.
 
• String getMessage( ) : Gives you the description of the exception in program
 
• Throwable fillInStackTrace( ) :  Gives you aThrowable Object that contains a stack
trace.
 
• void print StackTrace( ) :  Gives you and print the stack trace.
 
• void printStackTrace(PrintStream stream) :  Return the stack trace to a specific
defined stream
 
• String getLocalizedMessage() : Return the Localized description of the exception
Database Connectivity
Load the JDBC driver.


Define the Connection URL


Establish the Connection
String username = "jay_debesee";
String password = "secret";
Connection connection =
DriverManager.getConnection(oracleURL, username, password);

Create a Statement Object

Statement statement = connection.createStatement();



Execute a Query or Update
String query = "SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet = statement.executeQuery(query);


Process the Results
while(resultSet.next()) {
System.out.println(resultSet.getString(1) + " " +
ResultSet.getString(2) + " " +
resultSet.getString("firstname") + "
resultSet.getString("lastname"));
}


Close the Connection
Basic JDBC Example
examples that connect to the Microsoft Access
Northwind database. perform a simple query.
import java.sql.*;

public class NorthwindTest


{
public static void main(String[] args)
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:Northwind";
String username = ""; // No username/password required
String password = ""; // for desktop access to MS Access.
showEmployeeTable(driver, url, username, password);
}
public static void showEmployeeTable(String driver,String url,String username,String
password) {
try {
// Load database driver if it's not already loaded.
Class.forName(driver);
// Establish network connection to database.
Connection connection =
DriverManager.getConnection(url, username, password);
System.out.println("Employees\n" + "==========");
// Create a statement for executing queries.
Statement statement = connection.createStatement();
String query ="SELECT firstname, lastname FROM employees";
// Send query to database and store results.
ResultSet resultSet = statement.executeQuery(query);
// Print results.
while(resultSet.next())
{
System.out.print(resultSet.getString("firstname") + " ");
System.out.println(resultSet.getString("lastname"));
}
connection.close();
}
catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
} catch(SQLException sqle) {
JDBC Programming
• Loading driver
• Connecting to and Querying a JDBC Data
Source
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionDemo {


public static void main(String[] argv) {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
return;
}
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");

} catch (SQLException e) { return; } finally {


try {
if(connection != null)
connection.close();
} catch (SQLException e) { e.printStackTrace(); } } }
}
Interface java.sql.ResultSet
• public interface ResultSet extends Object

• A ResultSet provides access to a table of data generated by


executing a Statement.

• The table rows are retrieved in sequence. Within a row its column
values can be accessed in any order.

• A ResultSet maintains a cursor pointing to its current row of data.


Initially the cursor is positioned before the first row.

• The 'next' method moves the cursor to the next row.


• For the getXXX methods, the JDBC driver attempts to convert
the underlying data to the specified Java type and returns a
suitable Java value

• Java types with the ResultSet.getXXX methods

• Column names used as input to getXXX methods are case


insensitive
Updating Rows in ResultSet Objects
Query Examples

CREATE TABLE shop (


article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
dealer CHAR(20) DEFAULT '' NOT NULL,
price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,
PRIMARY KEY(article, dealer));

INSERT INTO shop VALUES (1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),


(3,'C',1.69),(3,'D',1.25),(4,'D',19.95);
 

You might also like