You are on page 1of 49

Java Programming

Programming Language Levels

† Four programming language levels:


„ machine language
„ assembly language
„ high-level language
„ fourth-generation language
† Each type of CPU has its own specific
machine language
† The other levels were created to make it
easier for a human being to write programs
Language Translators

† Interpreters translate one program


statement at a time, as the program
is running.

† Compilers translate a complete


program into machine language, then
the machine language is executed as
needed.
Java Virtual Machine

† Java is both compiled and interpreted.


† Java compiler output Java bytecode.
† the platform-independent bytecode is
interpreted by the Java interpreter.
Java Virtual Machine (cont.)
First Java Program
Comments
/*
My very first java program.
*/
public class HelloWorld {
public static void main(String[]
args) {
// print message on screen
System.out.println(“Hello World”);
}
}

save this in file HelloWorld.java


Compile:
– javac HelloWorld.java => creates HelloWorld.class file
Run:
– java HelloWorld
Alternatively use some IDE (Integrated Development Environment)
Main method

/*
My very first java program.
*/
public class HelloWorld {
public static void main(String[] args) {
// print message on screen
System.out.println(“Hello World”);
}
}
† main method
† – Called when java HelloWord is run
† Argument: Array args hold command-line arguments
† – java HelloWord is colorful
† – args[0] = is
† – args[1] = colorful
Methods
public class HelloWorld {
public static void printToScreen(String
message) {
System.out.println(message);
}
public static void main(String[] args) {
printToScreen(“Hello World”);
printToScreen(“My First Java Program”);
}
}
† public : method can be called from outside this class
† static : only one copy for all objects
† void : return type (what the method returns)
† printToScreen : name of method
† String message : type and name of arguments passed in
Learning Through Errors

Four kinds of errors

† Insignificant errors
† Compile time errors (syntax)
† Run time errors (syntax)
† Semantic errors (bugs)
Insignificant Errors

public class HelloWorld {


public static void main(String[] args) {
// print message on screen
System.out.println(“Hello World”);
}
}

† Misspell/leave out red words


† Program works the same
Compilation Errors

public class HelloWorld {


public static void main(String[] args) {
// print message on screen
System.out.println(“Hello World”);
}
}

† Misspell/leave out red words


† Program won’t compile
Runtime Errors

public class HelloWorld {


public static void main(String[] args) {
// print message on screen
System.out.println(“Hello World”);
}
}
† Misspell/leave out red words
† Program will compile, but won’t run
Semantic Errors

public class HelloWorld {


public static void main(String[] args) {
// print message on screen
System.out.println(“Hello World”);
}
}
† Misspell/leave out red words
† Program works, but differently
Java Tutorial

http://java.sun.com/docs/books/tutor
ial/java/index.html
Variables, Operators, Control
Statements …..

public class BasicsDemo


{
public static void main(String[] args)
{
int sum = 0;
for (int current = 1; current <= 10; current++)
{
sum += current;
}
System.out.println("Sum = " + sum); }
}
Operators

† Arithmetic operators: +, -, *, /, &(mod)


„ i = i + 1 => ++I
„ i = i – 1 => i—
„ i = i + 5 => i += 5
† – + can be used to concatenate strings
† String s = “Hello ” + “World ” + “!”;
† Relational operators: ==, !=, <, <=, =>, >
&& (AND), || (OR), !(NOT)
† Precedence Relationship
Data Types

† Primitive † Reference
„ boolean (true, „ objects
false) „ arrays
„ char (‘a’, ‘z’) „ String (very basic)
„ int (1, 100, -8)
„ float[32bit]
(3.1415)
„ double[64bit]
(3.1415)
„ Others:
† byte, short, long
Control Statements

Statement Type Keyword

looping while, do-while, for

decision making if-else, switch-case

exception handling try-catch-finally, throw

branching break, continue, label:, return


for statement

† for (initialization; test; increment) {


† // body of loop
†}

for (int i = 0; i < 5; i++)


System.out.println(“loop no = ” + i);
while statement

† while (condition) { † do {
† // body of loop † // body of loop
† } † } while (condition);

int x = 0;
while (x < 5) {
System.out.println(“loop no = ” + x);
x++;
}
if statement

if (x == 1)
† if (condition) { System.out.println(“x =
† // statements 1”);
† } else if (condition) { else if (x == 2) {
† // more System.out.println(“x =
† statements 2”);
† } else { } else
† // else statements System.out.println(“x >
2”);
† }
switch statement
† switch (variable) { int month;
† case value1: switch (month) {
† // body case 1:
† break; System.out.println(“Jan”);
† case value2: break;
† // body case 2:
† break; System.out.println(“Feb”);
† default: break;
† // body …
† } default:
System.out.println(“N/A”);
}
Object Oriented Programming
Concepts with Java
† An object is a software bundle of related variables and
methods. Software objects are often used to model real-
world objects you find in everyday life

† Software objects interact and communicate with each


other using messages.

† A class inherits state and behavior from its superclass.


Inheritance provides a powerful and natural mechanism
for organizing and structuring software programs.

† A class inherits state and behavior from its superclass.


Inheritance provides a powerful and natural mechanism
for organizing and structuring software programs.

† An interface is a contract in the form of a collection of


method and constant declarations. When a class
implements an interface, it promises to implement all of
the methods declared in that interface.
Classes and Objects
public class Rectangle Class Declaration
{
// member variables
private int length;
private int width; Variables (Attributes)
// constructor – initializes variables
// when instance is created
public Rectangle (int x, int y)
{
length = x; Constructor
width = y;
}
public int area()
{
return (length * width); A Method
}
}
public static void main(String[] args)
{
Rectangle rect = new Rectangle (5,2); An object
int area = rect.area();
System.out.println(“area is ” + area);
}
Method Overloading

public double area(int x, double y) { … }


public double area(double x, int y) { … }

q.area(2, 3.5) calls the first method


q.area(3.5, 2) calls the second method

public Rectangle(int length, int width) { … }


public Rectangle() { … }
Static and Non-Static methods

† Static methods
„ No need to be associated with an object
System.out.println(“a”);
Math.random();

† Non-Static methods (instance methods)


„ Create an instance of the class and then call the
method
rect.area(3, 6);
Inheritance

† The Object class,


† superclass
† Subclass
† Access Control
„ Public
„ Private
„ Protected
„ No access specifier
implies public
† Overriding
class Box { class BoxWeight extends Box {
private double width, height, depth;
double weight;
// when all dimensions specified BoxWeight (double w, double h,
Box(double w, double h, double d) double d, double m)
{ {
width = w; height = h; super(w, h, d);
weight = m;
depth = d;
}
}
// when no dimensions specified BoxWeight() {
Box() { super();
width = -1; // use -1 to indicate weight = -1;
}
height = -1; // an uninitialized
depth = -1; // box }
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class DemoSuper {

public static void main(String args[]) {

BoxWeight mybox1 = new BoxWeight(2, 3, 4, 0.076);


BoxWeight mybox2 = new BoxWeight(); // default
double vol;

vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();

vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();

}
}
Creating Packages

† A package is a collection of related types providing


access protection and namespace management. Note
that types refers to classes, interfaces etc.

package graphics;

public class Circle extends Graphic implements


Draggable { . . . }
† Name Space
„ graphics.Rectangle
„ java.awt.Rectangle
Using Package Members
† Refer to the member by its long
(qualified) name
„ graphics.Rectangle
„ graphics.Rectangle myRect = new graphics.Rectangle();

† Import the package member


„ import graphics.Circle;
„ Circle myCircle = new Circle();

† Import the member's entire package


„ import graphics.*;
„ Circle myCircle = new Circle();
„ Rectangle myRectangle = new Rectangle();
Java’s Standard Library

† java.lang
„ String, Type wrappers and other classes and
interfaces that are fundamental to all java
programs.
„ Automatically imported to all programs
† java.util
† java.io
† networking
† Applets
† AWT
† …
Interfaces
† Capturing similarities among unrelated classes
without artificially forcing a class relationship

† Declaring methods that one or more classes are


expected to implement

† Revealing an object's programming interface without


revealing its class

† Modeling multiple inheritance, a feature that some


object-oriented languages support that allows a class
to have more than one superclass
Strings

† Not primitive type, but very basic

String s1 = “hello”;
String s2 = s1.substring(1, 4);
System.out.println(s2); // “ell”
System.out.println(s1.length()); //5
// to check equality of strings
if (s1.equals(s2)) doTrue();
else doFalse();

† Other string methods at


http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
Arrays

† Defined in java.util

† Contains a fixed number of objects of the same type

† Usually created as any other object


„ int[] digits = new int[10];
„ int digits[] = new int[10];

† Can also be created and initialized at the same time


„ int[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
„ this way don’t have to specify size or say “new”
Arrays of Objects

† When creating array of objects, must


„ allocate the array using “new”
„ allocate each object using “new”
† Rectangle[] rects = new Rectangle[5];
for (int ii = 0; ii < 5; ii++) {
rects[ii] = new Rectangle (ii, ii);
}
† By default
„ primitive numeric: initialized to zero
„ Objects: initialized to null
Array Operations

† To find number of elements


„ rects.length
† To access nth element
„ rects[n-1]
† Other array methods at
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html
Java References

† Java API specification


http://java.sun.com/j2se/1.4.2/docs/api/index.html

† The Java Tutorial


http://java.sun.com/docs/books/tutorial/index.html
Simple Input/Output Operations

† Source/Destination
„ a file, memory, a socket
etc.
Reading
open a stream † Character Stream and
while more information Byte Stream
read information
close the stream
† Files and Filters

† Wrapping a Stream
Writing
† Tutorial
open a stream http://java.sun.com/docs/books/tut
while more information orial/essential/io/overview.html
write information
close the stream
Character Streams
Examples of I/O Streams
Type of I/O Streams Description

Collectively called file streams, these streams


FileReader
File FileWriter
are used to read from or write to a file on the
native file system.

Buffer data while reading or writing, thereby


reducing the number of accesses required on
BufferedReader the original data source. Buffered streams are
Buffering BufferedWriter typically more efficient than similar
nonbuffered streams and are often used with
other streams.

A reader and writer pair that forms the bridge


between byte streams and character streams.
Converting
InputStreamReader An InputStreamReader reads bytes from an
between Bytes
OutputStreamWriter InputStream and converts them to characters,
and Characters
using the default character encoding or a
character encoding specified by name.
Reading Input
/* This program demonstrates
How to read input from the console
*/

import java.io.*;
import java.util.*;

class InputDemo
{
public static void main(String args[])
throws IOException
{
String inputFile;

BufferedReader br= new BufferedReader(new


InputStreamReader(System.in));
System.out.println("Enter the Input File Name");
inputFile= br.readLine();

System.out.println("Input File Name is:"+inputFile);


}

}
/* This program demonstrates
1. How to read input from the console
2. Reading data from an ASCII file
3. Writting an ASCII file*/

import java.io.*;
import java.util.*;

class ioExample
{
public static void main(String args[])
throws IOException
{
// The path must be set to the ASCII data file
FileReader fin;
FileWriter fout;
String inputFile, outputFile, s, insertString;
String month, year, name;
float percDA, DA, HRA, Deduction, Gross, Net;
int basic;

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter the Input File Name");
inputFile= br.readLine();
System.out.println("Enter the Output File Name");
outputFile= br.readLine();
System.out.println("Your input file is:"+inputFile);
System.out.println("Your output file is:"+outputFile);
// Try – Catch Block for Reading the text file to be inserted
return;
}
}
try
{
try
{
fin = new FileReader(inputFile);

}catch(FileNotFoundException e)
{
System.out.println("Error opening input file!!");
return;
}
fout = new FileWriter(outputFile);

BufferedReader brin = new BufferedReader(fin);

s = brin.readLine();
StringTokenizer st = new StringTokenizer(s);
month = st.nextToken();
year = st.nextToken();
percDA = Float.parseFloat(st.nextToken());
insertString = "Pay Slip for "+month+" "+year;
fout.write(insertString);

// While loop (next slide) to be inserted here

fin.close();
fout.close();

}catch(ArrayIndexOutOfBoundsException e)
{System.out.println("Exception"+e);
}
// While Loop
while((s = brin.readLine()) != null)
{
System.out.println(s);
StringTokenizer st1 = new StringTokenizer(s);

name = st1.nextToken();
basic = Integer.parseInt(st1.nextToken());
HRA = Float.parseFloat(st1.nextToken());
Deduction = Float.parseFloat(st1.nextToken());

DA = basic*percDA/100;
Gross =basic+DA+HRA;
Net = Gross - Deduction;

insertString = "\n"+ name + " "+Float.toString(Gross)+" "+Float.toString(Net

fout.write(insertString);

}
Sample Input File

September 2007 50.6


M.Jenamani 12000 5000 3000
D.Chakravarty 13000 6000 5000
P.Das 18000 7000 8000
Exception Handling

† The Java programming language uses


exceptions to handle errors and other
exceptional events. This lesson describes
when and how to use exceptions.
† An exception is an event that occurs during
the execution of a program that disrupts
the normal flow of instructions.
† Advantages of exception handling
„ Separating Error-Handling Code from "Regular"
Code
„ Propagating Errors Up the Call Stack
„ Grouping and Differentiating Error Types
Today’s Assignments

† Run all the java example given in this


presentation.

† The last program represents a simple


payroll system. But it is not truly
object oriented. Give it an object
orientation by adding a class called
employee. Change the rest of the
program accordingly.

You might also like