Sie sind auf Seite 1von 123

Course Objectives

TITLE : Basic Java OBJECTIVES :


On completion of the course the participant will be able to: 1. Write and run Java programs in the Java Virtual Machine. 2. Use strings and arrays in Java. 3. Apply good object-oriented programming techniques. 4. Use access control to hide implementation details. 5. Create a reusable class library using packages. 6. Handle errors using exceptions. 7. Use Thread class and Runnable interface for creating Multi-threaded applications. 8. Use API docs J2SE 1.4.x. 9. Use Java Collections. 11. Understand the Java security model. 12. Document your programs using javadoc tool. 13. Use AWT for creating GUI application programs and applets

PREREQUISITES : Programming experience in at least one procedural language. Preferably C, C++. TARGET AUDIENCE : ELTP Trainees METHODOLOGY : Usage of slides Exercises to be solved in Lab Assignments and Quizzes

COURSE CONTENTS
Unit 1 : Object-oriented programming concepts Object Oriented Paradigm Classes, Objects, variables & methods Abstraction, encapsulation, inheritance, polymorphism Interfaces Unit 2 : Fundamental concepts of Java programming language History & characteristics of java. Primitive data types and objects Variables (Instance and Class) Arrays and Strings Control Structures Methods (Instance and Class) Packages & Interfaces A small sample application program

COURSE CONTENTS
Unit 3 : Exception handling Concept of Exception Handling Exception Types Uncaught Exceptions Claiming, Throwing and Handling Exceptions (using try-catch blocks) Using the finally clause in the try-catch block Creating User Exception Unit 4 : Multithreading Concept of Multithreading Writing threads by extending the Thread Class Writing threads by implementing the Runnable interface Life cycle of thread states Thread priorities and thread groups Thread synchronization and resource conflicts

COURSE CONTENTS
Unit 5 : Collections Maps Sets Trees Vectors Lists Iterators & Enumerations Hash Tables, Hash Maps. Unit 6 : IOs Streams InputStreams OutputStream Object Streams File Streams Pipe Streams Buffered Streams File Locking (nio package)

COURSE CONTENTS
Unit 7 : Util Package String Tokenize Date Calendar Introduction to java.util.jar & java.util.zip packages. Unit 8 : Other Important Concepts Compiler Options. javadoc tool. Security Over view.

COURSE CONTENTS
Unit 9 : IDE Introduction to IDE. Using Templates. Creating Classes, Interfaces, Packages from IDE. Compiling & running a java program from the IDE. Debugging Techniques. Debugging Java Programs from IDE. Unit 10 : AWT & Applet AWT Component, Container, Panel, Window, Frame, Canvas AWT Controls Menus Events Listeners Adapter classes

COURSE CONTENTS

Day Wise
Day Session 1 S1 S2 S3 S4 S1 S2 S3 S4 Topic Object-oriented programming concepts Fundamental concepts of Java programming language Writing application programs using Java Lab Session Executing a simple Java Program Exception handling Lab Session Exercises on Exception handling Multithreading Lab Session Exercises on Multithreading

COURSE CONTENTS

Day Wise
Day Session 3 S1 S2 S3 S4 S1 S2 S3 S4 Topic Java Collections Lab Session Exercises on Java Collection Java IOs Lab Session Exercises on Java IOs Security Overview Javadoc utility, Introduction IDE & debugging techniques Lab Session Exercises on Code Debugging Lab Session Exercises on Code Debugging

COURSE CONTENTS

Day Wise
Day Session 5 S1 S2 S3 S4 S5 S1 S2 S3 S4 Topic Introduction to AWT & Component Hierarchy) Frames Lab Session Exercises on Frames Events & Listeners Lab Session Exercises on java.awt.event Package Menus Lab Session Exercises on Menus Applets & Applet communications Lab Session Exercises on Applets

Session Objectives Day 1


OBJECTIVES : On completion of this session the participant will be able to: -Answer what is Java Programming Language. -get an overview of J2EE. -Understand the primary Goals of the Java Programming Language. -Explain the JVM Architecture. -Implement OOAD Methodology. -Understand the useage of String & StringBuffer. -Implement java code security.

Java 2 Platform

J2EE
JDBC HTML, XML

Browser
HTTP Servlet or JSP RMI /IIOP Security Transactions Concurrency

Data
HOME REMOTE

Entity Bean

Device
any http server Session Bean

JDBC

Containers

JVM

Context

EJB Server

any OS

The Platform
Cache / Proxy / Fwall Commerce

Tools

Integration Collaboration Content Mgmt Wireless/Mobile Data Application Server

Management

Where does J2EE Fit?


Cache / Proxy / Fwall J2EE Commerce

Tools

Integration Collaboration Content Mgmt J2EE Wireless/Mobile Data Application Server J2EE

Management

Fundamental Concepts of Java Programming Language

What Is the Java Programming Language

Java is

A Programming language A development environment A deployment environment

Similar in syntax to C++; similar in semantics to Smalltalk Used for developing both applets and applications

Primary Goals of the Java Programming Language

Provide an interpreted environment for


Improved Speed of development Code portability

Enable users to run more than one thread of activity Support dynamically changing programs during runtime Furnish better security

Primary Goals of the Java Programming Language


The following features fulfill these goals

The Java virtual machine (JVM) Garbage collection Code security

The Java Virtual Machine


Provides hardware platform specifications Reads compiled byte codes which are platform independent Is implemented as software Is implemented in a Java technology development tool or a Web browser

The Java Virtual Machine

JVM provides definitions for the


Instruction set (central processing until [CPU]) Class file format Stack Garbage-collection Memory area

The Java Virtual Machine

Bytecodes that maintain proper type discipline form the code The majority of type checking is done when the code is compiled Every SunTM approved implementation of the JVM must be able to run any compliant class file.

Garbage Collection
Allocated memory that is no longer needed should be deallocated In other languages, deallocation is the programmers responsibility Garbage collection

Checks for and frees memory no longer needed Is done automatically Can vary dramatically across JVM implementations

Java Runtime Environment

Performs three main tasks Loads code Verifies code Executes code

Java Runtime Environment


Runtime compile Class loader Byte code verifier .java .class
NETWORK

Interpreter Runtime

JIT code generator

Loading code Verifying code Executing code

Hardware

Object Oriented Programming Concepts

Class and Object


Understand what an object mean and what it contain

An Object
Everything is an object: If you want to model it and use it in your program.
Account 3

Account 1

Red Tape Recorder

Account 2 Green Tape Recorder Account 4

Identity

One Apple One Apple

ME

My Twin

Reference and Object


BPL Tape Recorder My BPL Red Tape Recorder Red Tape Recorder

Parts of an Object
Properties State Methods Constructors Access

Rights Destructor

Properties and State


Account 1
Open

Account 1
Black Listed

Account 1
Closed

Account no Name Balance

Methods and Access

Deposit Interest Withdraw

Constructor

Buttons, Motor All other parts Constructor

Tape Recorder

A Destructor is invoked just before the object is deleted, as a last chance

Equality and Similarity


A B C D

A and B are equal. B and C are similar C and D are neither similar nor equal. If they are equal they are the same object

Inheritance and Aggregation


Understand is a and has a relations

Inheritance - is a
Account IS A Savings Account Current Account

Savings Account will have everything from account, as does the Current Account

Aggregation - has a
Engine HAS A

Car

Polymorphism
Is

a consequence of virtual functions Function to be called is decided at run time based on object This makes a function call behave differently with different objects

Abstract Class
Four Legged Animal

Cat

Rat

Interface
Radio Radio

Radio Tape

Tape Volume is common Tape 2-in-1

Java Language Specifications

Comments

Three permissible styles of comment in a Java technology program are


// comment on one line /* comment on one or more lines */ /** documenting comment */

Semicolons, Blocks, and Whitespace

A statement is a single-line of code terminated by a semicolon(;)


totals = a + b + c + d + e + f;

A block is a collection of statements bounded by opening and closing braces


{ x = y + 1; y = x + 1; }

Semicolons, Blocks and Whitespace

A block can be used in a class definition


public class Date { int day; int month; int year; }

Block statements can be nested Any amount of whitespace is allowed in a Java program

Identifiers

Are names given to a variable, class or method Can start with a letter, underscore(_), or dollar sign($) Are case sensitive and have no maximum length

Examples identifier username user_name _sys_varl $change

Primitive Types

The Java programming language defines eight primitive types Logical boolean Textual char Integer byte, short, int and long Floating double and float

Logical - boolean

The boolean data type has two literals, true and false For example the statement
boolean truth = true ;

declares the variable truth as boolean type and assigns it a value of true.

Textual - char and String


char Represents a 16-bit Unicode character Must have its literal enclosed in single quotes( ) Uses the following notations:
a \t \u????

A tab A specific Unicode character (????) is replaced with exactly four hexadecimal digits.

Textual - char and String


String Is not a primitive data type; it is a class Has its literal enclosed in double quotes ( )
The quick brown fox jumped over the lazy dog.

Can be used as follows:


String greeting = Good Morning !! \n ; String err_msg = Record Not Found ! ;

Integral - byte,short,int, and long

Uses three forms - decimal, octal or hexadecimal 2 The decimal value is two. 077 The leading zero indicates an octal value 0xBAAC The leading 0x indicates a hexadecimal value Has a default int Defines long, by using the letter L or l

Integral - byte,short,int, and long

Each of the integral data types have the following range


----------------------------------------------------------Integer Name or Range Length Type ----------------------------------------------------------8 bits byte -27 27 1 16 bits 32 bits 64 bits short int long -215 215 1 -231 231 1 -263 263 1 -----------------------------------------------------------

Floating Point - float and double


Default is double Floating point literal includes either a decimal point or one of the following E or e (add exponential value) F or f (float) D or d (double)
3.14 6.02E23 2.718F 123.4E+306D A simple floating-point value (a double) A large floating-point value A simple float size value A large double value with redundant D

Floating Point - float and double

Floating point data types have the following ranges: ------------------------------------------Float length 32 bits 64 bits

------------------------------------------float double

Name or Type

-------------------------------------------

Java Coding Conventions

Classes
class AccountBook class ComplexVariable

Interfaces
interface Account

Methods
balanceAccount () addComplex ()

Java Coding Conventions

Variables
currentCustomer

Constants
HEAD_COUNT MAXIMUM_SIZE

Understanding Objects

Reviewing the history of objects Creating a new type, such as Date


public class Date { int day; int month; int year; }

Declaring a variable
Date myBirth, yourBirth

Accessing members
myBirth.day = 26; myBirth.month = 11; yourBirth.year = 1960;

Creating an Object

Declaration of primitive types allocates memory space Declaration of nonprimitive types does not allocate memory space Declared variables are not the data itself, but references (or pointers) to the data

Creating an Object - Memory Allocation and Layout


A

declaration allocates storage only for a reference


MyDate today; today = new MyDate() ;

today

????

Assignment of Reference Variables


Consider the following code fragment: int x = 7; int y = x; String s = Hello; Hello String t = s;

S T

Writing applications programs using Java

Variables and Scope


Local variables are Variables which are defined inside a method and are called local, automatic, temporary, or stack variables. Created when the method is executed and destroyed when the method is exited. Variables that must be initialized before they are used or compile-time errors will occur.

Logical Expressions

The Boolean operators supported are


! - NOT ^ - XOR && - AND || - OR

The Bitwise operators are


~ - Complement ^ - XOR | & - AND - OR

Short-Circuit Logical Operators


The operators are && (AND) and ||(OR) Operators can be used as follows:
String unset = null; if ((unset != null) && (unset.length() > 5)) { // do something with unset }

String Concatenation With +

The + operator Performs String concatenation Produces a new String For example:
String salutation = Dr.; String name = Pete + Seymour; String title = salutation + name;

One argument must be a String object Non-strings are converted to String objects automatically

Right-Shift Operators >> and >>>

Arithmetic or signed right shift (>>) is used as follows:


128 >> 1 equates to 128/21 = 64 256 >> 4 equates to 256/24 = 16 -256 >> 4 equates to -256/24 = -16

The sign bit is copied during the shift. Logical or unsigned right shift operator (>>>) is Used for bit patterns Not copied during the shift

Left-Shift Operator (<<)


128 << 1 equates to 128*21 = 256 16 << 2 equates to 16*22 = 64

The = = Operator Versus equals () Method

The equals () and = = methods determine if reference values refer to the same object. The equals () method is overridden in classes in order to return true if the contents and type of two separate objects match.

Casting

If information is lost in an assignment the programmer must confirm the assignment with a typecast. The assignment between short and char requires an explicit cast.
long bigValue = 99L; int squashed = (int) (bigValue); long bigval = 6;// 6 is an int type, OK int smallval = 99L;// 99L is a long, illegal float z = 12.414F;// 12.414F is Float, OK float zl = 12.414;// 12.414 is double, illegal

Promotion and Casting of Expressions

Variables are automatically promoted to a longer form (such as int to long) Expression is assignment compatible if the variable type is at least as large (the same number of bits) as the expression type.

Branching Statements
The if, else statements if (boolean expression) { statement or block; } if (condition is true) { statement or block; } else { statement or block; }

Branching Statements
The switch Statement
The switch statement syntax is: switch (expr1) { case expr2: statements; break; case expr3: statements; break; default: statements; break; }

Looping Statements
The for statement for (init_expr; boolean testexpr; alter_expr) { statement or block; }

Looping Statements
The While loop while (boolean) { statement or block; }

Looping Statements
The do/while statement do { statement or block; } while (boolean test)

Special Loop Flow Control


break [label] ; continue [label]; label: statement;//where statement must be any // legal statement

Declaring Arrays

Group data objects of the same type Declare arrays of primitive or class types
char s[]; Point p[]; char [] s; Point [] p;

Create space for a reference Remember an array is an object not memory reserved for primitive types

Creating Arrays
Use the new keyword to create an array object
s = new char [20]; p = new point [100]; p[0] = new point(); p[1] = new point(); . . .

Example : ArrayDemo.java

Initializing Arrays
An

array element is initialized Create an array with initial values


String names [] = { Georgianna, Jen, Simon };

Example : ArrayOfStringDemo.java

Multi-Dimensional Arrays

Arrays of arrays int twoDim [][] = new int [4][] ; twoDim [0] = new int[5]; twoDim [1] = new int[5]; int twoDim [][] = new int [][4]; illegal Array of four arrays of five integers each int twoDim [][] = new int[4][5];

Example : ArrayOfArraysDemo .java

Multi-Dimensional Arrays

Non-rectangular arrays of arrays


twoDim[0] twoDim[1] twoDim[2] twoDim[3] = = = = new new new new int[2]; int[4]; int[6]; int[8];

Array of four arrays of five integers each


int twoDim[][] = new int[4][5];

Example : ArrayOfArraysDemo2 .java

Array Bounds
All array subscripts begin at 0
int list [] = new int [10]; for (int i = 0; i < list.length; i++) system.out.println(list[i]);

Copying Arrays

Cannot resize an array Can use the same reference variable to refer to an entirely new array
int elements [] = new int[6]; elements = new int[10];

Copying Arrays
The System.arraycopy () method
//original array int elements[] = { 1,2,3,4,5,6 }; : //new larger array int hold[] = { 10,9,8,7,6,5,4,3,2,1 }; //copy all of the elements array to the hold //array, starting with the 0th index System.arraycopy (elements, 0, hold, 0, elements.length);

Example : ArrayCopyDemo .java

Strings
Strings are objects that are immutable Using Strings : String name=Rajesh; String name = new String(Rajesh); String fullname = name + Kumar; name = name + Kumar; Important methods of string class : charAt(), substring(), length(), toUpperCase(), toLowerCase(), trim(), valueOf()

Constructors
Method used to initialize an object Method name same as the class name Java provides the default constructor for a class We can have overloaded constructors class Employee { int no; String name; Employee() { no=100; name=Rajesh; } }

Class (static) Variables


Is shared among all instances of a class Can be marked either as public or as private Can be accessed from outside the class if marked as public without an instance of the class.
public class Count { private int serialNumber; private static int counter = 0; public Count () { counter++; serialNumber = counter; } }

Class (static) Methods


A static method can be invoked without any instance of the class to which it belongs public class GeneralFunction { public static int addUp (int x, int y) { return x + y; } } public class UseGeneral { public void method () { int a = 9 int b = 10 int c = GeneralFunction.addUp(a, b); System.out.println(addUp() gives + c); } }

Inheritance - extends keyword


- The is a relationship is achieved through inheritance - extends keyword is used to inherit a class class Employee{ } class Manager extends Employee { } - Constructors are not inherited - A subclass method can override the method of a super class. - Only multi-level inheritance is possible, multiple inheritance is achieved using interfaces.

Inheritance - Method Overloading and Overriding


class Employee { void showDetails() { } } class Manager extends Employee { void showDetails() { } void showDetails(int no) { } }

The final keyword


A final class cannot be subclassed A final method cannot be overridden A final variable is a constant

Abstract Classes

A class which declares the existence of methods but not the implementation is called an abstract class. A class can be declared as abstract by marking it with the abstract keyword.
public abstract class Drawing { public abstract void drawDot {int x, int y); public void drawLine (int x1, int y1, int x2, int y2) { // draw using the drawDot () method repeatedly. } }

An abstract class can contain non-abstract methods and variables

Interfaces

An interface is a variation on the idea of an abstract class. In an interface, all the methods are abstract. Multiple inheritance can be achieved by implementing such interfaces The syntax is
public interface Transparency { public static final int OPAQUE = 1; public static final int BITMASK = 2; public static final int TRANSLUCENT = 3; public int getTransparency(); }

Interfaces

Interfaces are useful for Declaring methods that one or more classes are expected to implement Determining an objects programming interface without revealing the actual body of the class Capturing similarities between unrelated classes without forcing a class relationship Describing function-like objects that can be passed as parameters to methods invoked on other objects

Advanced Access Control


--------------------------------------------------------------------------------------------------Modifier Same Class Same Package Subclass Universe --------------------------------------------------------------------------------------------------public yes yes yes yes protected yes yes yes yes

default (package) yes

private yes ---------------------------------------------------------------------------------------------------

String
Constructors : String(

char[]) String(char[], int Start, int No) String(byte[]) String(byte[], int Start, int No) String(String)

Methods : Length(

) - Returns the number of characters charAt(int) - Returns char at the given index getChars(int St, int End, char[] Dest, int StDes) toCharArray( ) - Returns character array getBytes(int St, int End, byte[] Dest, int StDes) equals(String) - Compares two Strings,returns
boolean.
equalsIgnoreCase(

) - For ignoring the case

Example : ControllingCase.java Cont...

Methods : compareTo(

) - Returns integer startsWith(String) - Returns boolean,case sensitive endsWith(String)- Returns boolean,case sensitive trim( ) - Removes blank spaces on either sides replace(char Old, char New) - For replacing Old
chars
concat(String)

- Creates a new String by adding subString(int) - Creates a String from int to the end

Cont...

Methods : subString(int,int) indexOf(Char)

- Creates a String from int to int(end)

- Returns int,index of first occurence lastIndexOf(char) - Returns int,index of last occurence indexOf(String) - Returns int,index of first occurence lastIndexOf(String)- Returns int,index of last
occurence

Stringbuffer
Constructors : Stringbuffer(

) - 16 bytes of buffer by default String buffer(int) - For specifying the size String buffer(String) - For specifying the size

Methods : Length(

) - Returns the number of characters capacity( ) - Returns capacity setLength (int len) - Sets the new length charAt(int) - Returns character at the index getChars(int St, int End, char[] Dest, int StDes)

Cont...

Methods : setCharAt(int,

char) - Sets the char at the int append(String)-Adds the string to the current string insert(int, String) - Inserts the string at the index toString( ) - Returns string reverse( ) - Reverses the string

Example : StringBufferVsStringDemo.java Cont...

Points to Note
Use

StringBuffer wear the string values constantly change. Because a new string object is created for every change of value for a String class.

A Sample Java Application


public class First { public static void main(String[] args) { int no=4; System.out.println("Welcome to Java Programming"); System.out.println("Number :"+no); } } Compiling and Executing : - javac First.java -- java First generates First.class file.

Lab Session
Q. which of the following variable names are invalid, and why? Minimum double float First.name 3rd_row Sum Total n1+ n2 &name n$ Row1 Row Total Column-total

Q. Shown below is a Floyds triangle. 1 2 3 4 5 6 .. 79 91 Write a program to print this triangle? (FloydTriangle.java)

Solution

class FloydTriangle { public static void main(String []args) { int j; for(int i=1;i<6;i++) { for(j=1;j<=i;j++) System.out.print(j+"\t"); System.out.print("\n\n"); } } }

Lab Session
Write the segment of the program that creates the array as follows. 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1

Solution

Example : FloydTriangle.java

Lab Session
The annual examination results of 5 students are tabulated as follows. write the main method in order to determine the following a) Find out the total marks obtained by each student. b) The highest marks in each subject and roll no of the student who secured it. Use the following class to create the objects class Student{ int rollNo; String name; int sub1, sub2,sub3; }

Lab Session
Consider a college running 4 departments (MPC, BPC, HEC, CEC) the subject of each of the departments is given below. CEC MPC Lang 1 Lang 1 Lang 2 Lang 2 Commerce Mathematics Economics Physics Civics Chemistry BPC Lang 1 Lang 2 Biology Physics Chemistry HEC Lang 1 Lang 2 History Economics Civics

Requirement : Capture the marks of a student of any given department.

Solution
Marks

Arts Marks

Science Marks

HEC Marks

CEC Marks

MPC Marks

BPC Marks

Marks Arts Marks Science Marks

Abstract Classes HEC Marks CEC Marks MPC Marks BPC Marks

Final Classes

For More Examples See Examples/Basics


Language Basics Code Samples http://developer.java.sun.com/developer/code samples/basics.html

Java Coding Convensions http://java.sun.com/docs/codeconv/html/CodeC

Exercise: Programming through a story.

Objective: This is a story based exercise. The exercise enables the participants to pause at different stages and review the work they had done and the changes that need to be carried out to meet new requirements, that crop up from time to time. The Objective is to develop an object oriented system, using Java. The participant is expected to visualize various approaches to solve a problem, evaluate the approaches and develop a solution using the best option. The participant is required to refer to the Java language specifications to study the facilities offered by the Java API.

Exercise (contd..)
Note:

The participant is required to look into the best practices of Java (PPT version), while doing the exercise.

Exercise (contd..)
1.

A student joins the Satyam University. He sits at the workspace allotted to him. He runs the Hello.java program by keying in java Hello and he sees the welcome message 2. However, he wishes to be welcomed by name. He modifies the program. 3. experiments by overloading the main method.

Exercise (contd..)
4.

In the next program [4], the student enters the marks he has scored in 5 subjects and the program outputs the average marks. Grading on a scale of A to D is done with the following range of values for the grade.

Exercise 4 (contd)
Grade A B C D Average marks > 80 % >= 70 and < 80% >= 60 and < 70% < 60%

Exercise (contd..)
5.

Before grading the students, the program checks whether the student is above a minimum age which is stipulated in another class. 6. The other class has facilities to set and get the minimum age. The other class should reside in a package called stipulations

Exercisehas 4 departments. A students marks sheet 7. The SU (contd..)


is based on the department to which the student belongs. The 4 departments along with the subjects offered by them are: Department Subjects offered

MPC BPC
HEC CEC

Maths, Physics, Chemistry, lang1, lang2 Biology, Physics, Chemistry, lang1, lang2
History, Economics, Civics, lang1, lang2 Commerce, Economics, Civics, lang1, lang2

A student belongs to one of the 4 types of students viz. MPCStudent/BPCStudent/HECStudent/CECStudent. Hence, a student object belonging to a particular class should have its class implement the corresponding MarksInterface

Exercise (contd..)

8. SU gets the input data for students in the below format: #StudentNumber;StudentFirstName; StudentFirstName subjectName=Marks;.. For the current exercise, the input data is treated as held in the form of a String object, rather than getting it from a file. The data has to be extracted from the String object, the student objects have to be created and stored in an array of Student objects. Initially, the extracted data is to be printed onto the console

Exercise (contd..)
9. 10.

And then stored into the array of Student objects The next requirement is that the first and last names should be concatenated and displayed. One of the developers suggests that a StringBuffer class could be used. Weigh the pros and cons of using the StringBuffer and write a new class for carrying out the concatenation.

The

remainder part of the story exercises will be continued in the next session. ThankQ

Das könnte Ihnen auch gefallen