Java Programming
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
• Comments
• Identifiers
• Keywords
• Literals
– Integer Literals
– Floating Point Literals
– Boolean Literals
– Character Literals
– String Literals
• 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
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?
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
• 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
– 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.
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
L 5.4
Example: Method
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.
void test(int a)
{
System.out.println("a: " + a);
}
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.
void test(int a)
{
System.out.println("a: " + a);
}
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
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.
• 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.
// 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 {
• 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.
• 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.
– 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 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;
bike01.printDescription();
bike02.printDescription();
bike03.printDescription();
}
}
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();
• super(parameter-list);
• super.member
Dynamic Method Dispatch
Using Abstract Classes
Using final to Prevent Overriding
Using final to Prevent Inheritance
Interfaces
• java.lang
Cont..
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
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.*;
• The table rows are retrieved in sequence. Within a row its column
values can be accessed in any order.