Java Programming
Java Programming
• 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
• Constructor:
Scanner obj=new Scanner(System.in);
Important Methods
Method Description
if (logical expression)
statement
if...else statement
If else ladder
Nested if
Conditional Operator (? :)
• expression1 ? expression2 : expression3
Switch statement
While loop
do...while
For loop
• Integers are similar to those in C and C++
Arithmetic Operators and
Expressions
• If an arithmetic operator is combined with int operands,
then the resulting type is int
• If an arithmetic operator is combined with one or two
double operands, then the resulting type is double
• If different types are combined in an expression, then the
resulting type is the right-most type on the following list that
is found within the expression
byteshortintlongfloatdouble
Type Casting
• A type cast takes a value of one type and produces a value of
another type with an "equivalent" value
– If n and m are integers to be divided, and the fractional portion of the
result must be preserved, at least one of the two must be type cast to
a floating-point type before the division operation is performed
double ans = n / (double)m;
– Note that the desired type is placed inside parentheses immediately in
front of the variable to be cast
– Note also that the type and value of the variable to be cast does not
change
1-49
More Details About Type Casting
• When type casting from a floating-point to an integer type,
the number is truncated, not rounded
– (int)2.9 evaluates to 2, not 3
• When the value of an integer type is assigned to a variable of
a floating-point type, Java performs an automatic type cast
called a type coercion
double d = 5;
• In contrast, it is illegal to place a double value into an int
variable without an explicit type cast
int i = 5.5; // Illegal
int i = (int)5.5 // Correct
1-50
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?
Or
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
(Call by reference)
class Test
{
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
Returning Objects
class Test {
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);
}
Command-Line Arguments
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++){
System.out.println("args[" + i + "]: " +
args[i]);
} javac CommandLine
} java CommandLine this is a test 100 -1
} output
output
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
Recursion
• A method that calls itself is said to be
recursive class Factorial
{
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
o/p
class Factorial
{
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
Factorial of 3 is 6 }
Factorial of 4 is 24 }
Factorial of 5 is 120
class RecTest
{
int values[];
RecTest(int i) {
values = new int[i];
}
// display array -- recursively
void printArray(int i) { [0] 0
if(i==0) return; [1] 1
else printArray(i-1); [2] 2
System.out.println("[" + (i-1) + "] " + values[i-1]); [3] 3
} [4] 4
} [5] 5
class Recursion2 { [6] 6
public static void main(String args[]) {
RecTest ob = new RecTest(10);
int i;
for(i=0; i<10; i++) ob.values[i] = i;
ob.printArray(10);
}
}
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.
}
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables and
methods.
// 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.
• Object obj = new MountainBike();//implicit casting
– then obj is both an Object and a MountainBike
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();
}
}
• super(parameter-list);
• super.member
Dynamic Method Dispatch
Final
• Class (prevents from extending)
• Method(Prevents overriding ,definition is un
changeable)
• Variable (unchangeable ,constant value)
• Blank variable can be initialized only in the
constructor
Class ant{
final int no;//not initialized
ant(){ no=10;} }
• Static final variable can be initialized only in the
static block
Static final int no;//not initialized
Static { no=10;}
Using final to Prevent Overriding
Using final to Prevent Inheritance
Using Abstract Classes
Interfaces
Method Description
is used to write a byte to the current output
public void write(int)throws IOException
stream.
is used to write an array of byte to the
public void write(byte[])throws IOException
current output stream.
public void close()throws IOException is used to close the current output stream.
FileOutputStream class methods
Method Description
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
It is used to write ary.length bytes from
void write(byte[] ary):
the byte array to the file output stream.
Method Description
1) public abstract int read()throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of file.
3) public void close()throws IOException is used to close the current input stream.
read single character from file
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
read all characters from a file
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Using FileInputStream
public class FileReaderExample {
while(dataIn.available()>0) {
String k = dataIn.readUTF();
System.out.print(k+" ");
}
}
}
DataInputStream:Methods
DataOutputStream:Methods
int read(byte[] b)
void write(byte[] b, int off, int
boolean readBoolean()
len)
byte readByte()
void write(int b)
char readChar()
void writeBoolean(boolean v)
double readDouble()
void writeChar(int v)
float readFloat()
void writeBytes(String s)
int readInt()
void writeUTF(String str)
Object Streams
• support I/O of objects
• Classes:ObjectInputStream and ObjectOutputStream.
• writeObject() and readObject() methods
• readObject() method read an object from the
ObjectInputStream
import java.io.*;
public class ObjectInputStreamExample
{
public static class Person implements Serializable {
public String name = null;
public int age = 0;
}
drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Java Networking
• TCP/IP
• SOCKET Programming
• Ports
• 21-FTP,23-Telnet,25-Mail,80 for HTTP etc
• Client/Server
• Internet Addressing IPv4 & IPv6
• Java.net
• Java.rmi
Java.net
• Classes and Interfaces
• Classes listed below
• Interfaces listed below
Sockets
• A socket is one endpoint of a two-way communication link between two programs
running on the network.
• A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
• Server and client