123

Java Basics by Kamalakar Dandu

Embed Size (px)

DESCRIPTION

Java Basics by Kamalakar Dandu

Citation preview

Page 1: Java Basics by Kamalakar Dandu
Page 2: Java Basics by Kamalakar Dandu

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

Course Objectives

Page 3: Java Basics by Kamalakar Dandu

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

Page 4: Java Basics by Kamalakar Dandu

COURSE CONTENTS

Unit 1 : Object-oriented programming conceptsObject Oriented ParadigmClasses, Objects, variables & methodsAbstraction, encapsulation, inheritance, polymorphismInterfaces

Unit 2 : Fundamental concepts of Java programming languageHistory & characteristics of java.Primitive data types and objectsVariables (Instance and Class)Arrays and StringsControl StructuresMethods (Instance and Class)Packages & InterfacesA small sample application program

Page 5: Java Basics by Kamalakar Dandu

COURSE CONTENTS

Unit 3 : Exception handlingConcept of Exception HandlingException TypesUncaught ExceptionsClaiming, Throwing and Handling Exceptions (using try-catch blocks)Using the finally clause in the try-catch blockCreating User Exception

Unit 4 : MultithreadingConcept of MultithreadingWriting threads by extending the Thread Class Writing threads by implementing the Runnable interfaceLife cycle of thread statesThread priorities and thread groupsThread synchronization and resource conflicts

Page 6: Java Basics by Kamalakar Dandu

COURSE CONTENTS

Unit 5 : CollectionsMapsSetsTreesVectorsListsIterators & EnumerationsHash Tables, Hash Maps.

Unit 6 : IOs StreamsInputStreamsOutputStreamObject StreamsFile StreamsPipe StreamsBuffered StreamsFile Locking (nio package)

Page 7: Java Basics by Kamalakar Dandu

COURSE CONTENTS

Unit 7 : Util PackageString TokenizeDateCalendarIntroduction to java.util.jar & java.util.zip packages.

Unit 8 : Other Important ConceptsCompiler Options.javadoc tool.Security Over view.

Page 8: Java Basics by Kamalakar Dandu

COURSE CONTENTS

Unit 9 : IDEIntroduction 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 & AppletAWT Component, Container, Panel, Window, Frame, CanvasAWT ControlsMenusEventsListenersAdapter classes

Page 9: Java Basics by Kamalakar Dandu

COURSE CONTENTS

Day Wise

Day

Session

Topic

1 S1

S2

S3

S4

Object-oriented programming concepts

Fundamental concepts of Java programming language

Writing application programs using Java

Lab Session – Executing a simple Java Program

2 S1

S2

S3

S4

Exception handling

Lab Session – Exercises on Exception handling

Multithreading

Lab Session – Exercises on Multithreading

Page 10: Java Basics by Kamalakar Dandu

COURSE CONTENTS

Day Wise

Day Session Topic

3 S1

S2

S3

S4

Java Collections

Lab Session – Exercises on Java Collection

Java IOs

Lab Session – Exercises on Java IOs

4 S1

S2

S3

S4

Security Overview

Javadoc utility, Introduction IDE & debugging techniques

Lab Session – Exercises on Code Debugging

Lab Session – Exercises on Code Debugging

Page 11: Java Basics by Kamalakar Dandu

COURSE CONTENTS

Day Wise

Day Session

Topic

5 S1

S2

S3

S4

S5

Introduction to AWT & Component Hierarchy)

Frames

Lab Session – Exercises on Frames

Events & Listeners

Lab Session – Exercises on java.awt.event Package

6 S1

S2

S3

S4

Menus

Lab Session – Exercises on Menus

Applets & Applet communications

Lab Session – Exercises on Applets

Page 12: Java Basics by Kamalakar Dandu

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.

Session Objectives

Page 13: Java Basics by Kamalakar Dandu

Java 2 Platform

Page 14: Java Basics by Kamalakar Dandu

J2EE

anyhttp

server

BrowserBrowser

ContainersContainers

EJB ServerEJB Server

DataData

JDBCJDBC

EntityEntityBeanBean

HOMEHOME

REMOTEREMOTE

DeviceDevice

HTTPHTTP

JVMJVM

JDBCJDBC

HTML, XMLHTML, XML

any OS

ServletServletoror

JSPJSP RMI/IIOPRMI/IIOP

Session Session BeanBean

ContextContext

SecuritySecurity

TransactionsTransactions

ConcurrencyConcurrency

Page 15: Java Basics by Kamalakar Dandu

The Platform

Application ServerApplication Server

To

ols

To

ols

Man

agem

ent

Man

agem

ent

IntegrationIntegration

Content MgmtContent Mgmt

Wireless/MobileWireless/Mobile

DataData

CommerceCommerce

Cache / Proxy / FwallCache / Proxy / Fwall

CollaborationCollaboration

Page 16: Java Basics by Kamalakar Dandu

Where does J2EE Fit?

Application ServerApplication Server

To

ols

To

ols

Man

agem

ent

Man

agem

ent

IntegrationIntegration

Content MgmtContent Mgmt

Wireless/MobileWireless/Mobile

DataData

CommerceCommerce

Cache / Proxy / FwallCache / Proxy / Fwall

CollaborationCollaboration

J2EEJ2EE

J2EEJ2EE

J2EEJ2EE

Page 17: Java Basics by Kamalakar Dandu

Fundamental Concepts of Java Programming Language

Page 18: Java Basics by Kamalakar Dandu

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

Page 19: Java Basics by Kamalakar Dandu

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

Page 20: Java Basics by Kamalakar Dandu

Primary Goals of the Java Programming Language

The following features fulfill these goals• The Java virtual machine (JVM)• Garbage collection• Code security

Page 21: Java Basics by Kamalakar Dandu

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

Page 22: Java Basics by Kamalakar Dandu

The Java Virtual Machine

JVM provides definitions for the• Instruction set (central processing until [CPU])• Class file format• Stack• Garbage-collection• Memory area

Page 23: Java Basics by Kamalakar Dandu

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.

Page 24: Java Basics by Kamalakar Dandu

Garbage Collection Allocated memory that is no longer needed should be

deallocated In other languages, deallocation is the programmer’s

responsibility

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

Page 25: Java Basics by Kamalakar Dandu

Java Runtime Environment

Performs three main tasks• Loads code• Verifies code• Executes code

Page 26: Java Basics by Kamalakar Dandu

Java Runtime Environment

compile

.java

.class

NETWORK

Runtime

Class loader

J ITcode

generator

Hardware

Runtime

Interpreter

Byte codeverifier

• Loading code

• Verifying code

• Executing code

Page 27: Java Basics by Kamalakar Dandu

Object Oriented Programming Concepts

Page 28: Java Basics by Kamalakar Dandu

Class and Object

Understand what an object mean and what it contain

Page 29: Java Basics by Kamalakar Dandu

An Object

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

Account 1

Green TapeRecorder

Account 2

Account 3

Account 4

Red TapeRecorder

Page 30: Java Basics by Kamalakar Dandu

Identity

ME My Twin

OneApple

OneApple

Page 31: Java Basics by Kamalakar Dandu

Reference and Object

My BPLRed TapeRecorder

BPL Tape Recorder

Red Tape Recorder

Page 32: Java Basics by Kamalakar Dandu

Parts of an Object

Properties State Methods Constructors Access Rights Destructor

Page 33: Java Basics by Kamalakar Dandu

Properties and State

Account 1 Account 1 Account 1

Open Black Listed Closed

•Account no

•Name

•Balance

Page 34: Java Basics by Kamalakar Dandu

Methods and Access

Deposit

Withdraw

Interest

Page 35: Java Basics by Kamalakar Dandu

Constructor

ConstructorButtons, Motor

All other parts

Tape Recorder

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

Page 36: Java Basics by Kamalakar Dandu

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

Page 37: Java Basics by Kamalakar Dandu

Inheritance and Aggregation

Understand “is a” and “has a” relations

Page 38: Java Basics by Kamalakar Dandu

Inheritance - “is a”

Account

Savings Account Current Account

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

IS A

Page 39: Java Basics by Kamalakar Dandu

Aggregation - “has a”

Engine

Car

HAS A

Page 40: Java Basics by Kamalakar Dandu

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

Page 41: Java Basics by Kamalakar Dandu

Abstract Class

Four LeggedAnimal

Cat Rat

Page 42: Java Basics by Kamalakar Dandu

Interface

Radio

Tape

Radio

Tape

Radio

Tape

Volume is common2-in-1

Page 43: Java Basics by Kamalakar Dandu

Java Language Specifications

Page 44: Java Basics by Kamalakar Dandu

Comments

Three permissible styles of comment in a Java technology program are

// comment on one line

/* comment on one

or more lines */

/** documenting comment */

Page 45: Java Basics by Kamalakar Dandu

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;

}

Page 46: Java Basics by Kamalakar Dandu

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

Page 47: Java Basics by Kamalakar Dandu

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

Examplesidentifierusernameuser_name_sys_varl$change

Page 48: Java Basics by Kamalakar Dandu

Primitive Types

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

Page 49: Java Basics by Kamalakar Dandu

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.

Page 50: Java Basics by Kamalakar Dandu

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‘ A tab‘\u????’ A specific Unicode character (????)

is replaced with exactly four hexadecimal digits.

Page 51: Java Basics by Kamalakar Dandu

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 !” ;

Page 52: Java Basics by Kamalakar Dandu

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”

Page 53: Java Basics by Kamalakar Dandu

Integral - byte,short,int, and long

Each of the integral data types have the following range

-----------------------------------------------------------Integer Name or RangeLength Type-----------------------------------------------------------8 bits byte -27 …

27 –1

16 bits short -215 …

215 –1

32 bits int -231 …

231 –1

64 bits long -263 …

263 –1-----------------------------------------------------------

Page 54: Java Basics by Kamalakar Dandu

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 A simple floating-point value (a double)

6.02E23 A large floating-point value

2.718F A simple float size value

123.4E+306D A large double value with redundant D

Page 55: Java Basics by Kamalakar Dandu

Floating Point - float and double

Floating point data types have the following ranges:-------------------------------------------Float length Name or Type-------------------------------------------32 bits float

64 bits double

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

Page 56: Java Basics by Kamalakar Dandu

Java Coding Conventions

Classes

class AccountBook

class ComplexVariable

Interfaces

interface Account

Methods

balanceAccount ()

addComplex ()

Page 57: Java Basics by Kamalakar Dandu

Java Coding Conventions

Variables

currentCustomer

ConstantsHEAD_COUNTMAXIMUM_SIZE

Page 58: Java Basics by Kamalakar Dandu

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 membersmyBirth.day = 26;myBirth.month = 11;yourBirth.year = 1960;

Page 59: Java Basics by Kamalakar Dandu

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

Page 60: Java Basics by Kamalakar Dandu

Creating an Object - Memory Allocation and Layout

A declaration allocates storage only for a reference

MyDate today;

today = new MyDate() ;

today ????

Page 61: Java Basics by Kamalakar Dandu

Assignment of Reference Variables

Consider the following code fragment:

int x = 7;

int y = x;

String s = “Hello”;

String t = s;

Hello

S

T

Page 62: Java Basics by Kamalakar Dandu

Writing applications programs using Java

Page 63: Java Basics by Kamalakar Dandu

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.

Page 64: Java Basics by Kamalakar Dandu

Logical Expressions

The Boolean operators supported are! - NOT && - AND

^ - XOR || - OR

The Bitwise operators are~ - Complement & - AND

^ - XOR | - OR

Page 65: Java Basics by Kamalakar Dandu

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

}

Page 66: Java Basics by Kamalakar Dandu

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

Page 67: Java Basics by Kamalakar Dandu

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

Page 68: Java Basics by Kamalakar Dandu

Left-Shift Operator (<<)

128 << 1 equates to 128*21 = 256

16 << 2 equates to 16*22 = 64

Page 69: Java Basics by Kamalakar Dandu

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.

Page 70: Java Basics by Kamalakar Dandu

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

Page 71: Java Basics by Kamalakar Dandu

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.

Page 72: Java Basics by Kamalakar Dandu

Branching Statements

The if, else statementsif (boolean expression) {

statement or block;}

if (condition is true) { statement or block;} else {

statement or block;}

Page 73: Java Basics by Kamalakar Dandu

Branching Statements

The switch StatementThe switch statement syntax is:

switch (expr1) {

case expr2:

statements;

break;

case expr3:

statements;

break;

default:

statements;

break;

}

Page 74: Java Basics by Kamalakar Dandu

Looping Statements

The for statement

for (init_expr; boolean testexpr; alter_expr) {

statement or block;

}

Page 75: Java Basics by Kamalakar Dandu

Looping Statements

The While loop

while (boolean) {

statement or block;

}

Page 76: Java Basics by Kamalakar Dandu

Looping Statements

The do/while statement

do {

statement or block;

}

while (boolean test)

Page 77: Java Basics by Kamalakar Dandu

Special Loop Flow Control

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

// legal statement

Page 78: Java Basics by Kamalakar Dandu

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

Page 79: Java Basics by Kamalakar Dandu

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

Page 80: Java Basics by Kamalakar Dandu

Initializing Arrays

An array element is initialized Create an array with initial values

String names [] = {

“Georgianna”,

“Jen”,

“Simon”

};

Example : ArrayOfStringDemo.java

Page 81: Java Basics by Kamalakar Dandu

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

Page 82: Java Basics by Kamalakar Dandu

Multi-Dimensional Arrays

Non-rectangular arrays of arraystwoDim[0] = new int[2];

twoDim[1] = new int[4];

twoDim[2] = new int[6];

twoDim[3] = new int[8];

Array of four arrays of five integers eachint twoDim[][] = new int[4][5];

Example : ArrayOfArraysDemo2 .java

Page 83: Java Basics by Kamalakar Dandu

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]);

Page 84: Java Basics by Kamalakar Dandu

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];

Page 85: Java Basics by Kamalakar Dandu

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

Page 86: Java Basics by Kamalakar Dandu

StringsStrings 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()

Page 87: Java Basics by Kamalakar Dandu

ConstructorsMethod used to initialize an objectMethod name same as the class nameJava provides the default constructor for a classWe can have overloaded constructors

class Employee {int no;String name;Employee() {

no=100;name=“Rajesh”;

}}

Page 88: Java Basics by Kamalakar Dandu

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; }}

Page 89: Java Basics by Kamalakar Dandu

Class (static) MethodsA 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); }}

Page 90: Java Basics by Kamalakar Dandu

Inheritance - ‘extends’ keyword- The “is a” relationship is achieved through inheritance

- ‘extends’ keyword is used to inherit a classclass 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.

Page 91: Java Basics by Kamalakar Dandu

Inheritance - Method Overloading and Overriding

class Employee {

void showDetails() { }

}

class Manager extends Employee {

void showDetails() { }

void showDetails(int no) { }

}

Page 92: Java Basics by Kamalakar Dandu

The final keyword

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

Page 93: Java Basics by Kamalakar Dandu

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

Page 94: Java Basics by Kamalakar Dandu

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();

}

Page 95: Java Basics by Kamalakar Dandu

Interfaces Interfaces are useful for

• Declaring methods that one or more classes are expected to implement

• Determining an object’s 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

Page 96: Java Basics by Kamalakar Dandu

Advanced Access Control

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

Modifier Same Class Same Package SubclassUniverse

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

public yes yes yes yes

protected yes yes yes

default (package) yes yes

private yes

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

Page 97: Java Basics by Kamalakar Dandu

StringString

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

Constructors :-

Page 98: Java Basics by Kamalakar Dandu

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

Methods :-

Cont...Example : ControllingCase.java

Page 99: Java Basics by Kamalakar Dandu

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

Methods :-

Cont...

Page 100: Java Basics by Kamalakar Dandu

subString(int,int) - Creates a String from int to int(end) indexOf(Char) - 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

Methods :-

Page 101: Java Basics by Kamalakar Dandu

StringbufferStringbuffer

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

Constructors :-

Page 102: Java Basics by Kamalakar Dandu

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)

Methods :-

Cont...

Page 103: Java Basics by Kamalakar Dandu

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

Methods :-

Cont...

Example : StringBufferVsStringDemo.java

Page 104: Java Basics by Kamalakar Dandu

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.

Page 105: Java Basics by Kamalakar Dandu

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 -- generates First.class file.- java First

Page 106: Java Basics by Kamalakar Dandu

Lab SessionQ. which of the following variable names are invalid, and why?

Minimum First.name n1+ n2 &name double 3rd_row n$ Row1 float Sum Total Row Total Column-total

Q. Shown below is a Floyd’s triangle.12 34 5 6…………………………………..79 ……………………91

Write a program to print this triangle? (FloydTriangle.java)

Page 107: Java Basics by Kamalakar Dandu

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"); } } }

Page 108: Java Basics by Kamalakar Dandu

Lab Session

Write the segment of the program that creates the array as follows.

1 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1

Page 109: Java Basics by Kamalakar Dandu

Solution

Example : FloydTriangle.java

Page 110: Java Basics by Kamalakar Dandu

Lab Session

The annual examination results of 5 students are tabulated as follows.write the main method in order to determine the followinga) 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;}

Page 111: Java Basics by Kamalakar Dandu

Consider a college running 4 departments (MPC, BPC, HEC, CEC) the subject of each of the departments is given below.MPC

Lang 1Lang 2MathematicsPhysicsChemistry

BPCLang 1Lang 2BiologyPhysicsChemistry

CECLang 1Lang 2CommerceEconomicsCivics

HECLang 1Lang 2HistoryEconomicsCivics

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

Lab Session

Page 112: Java Basics by Kamalakar Dandu

Marks

Science MarksArts Marks

HEC Marks CEC Marks MPC Marks BPC Marks

MarksArts MarksScience Marks

Abstract Classes

Solution

HEC MarksCEC MarksMPC MarksBPC Marks

Final Classes

Page 113: Java Basics by Kamalakar Dandu

For More Examples See Examples/Basics

Language Basics Code Samples http://developer.java.sun.com/developer/

codesamples/basics.html

Java Coding Convensionshttp://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

Page 114: Java Basics by Kamalakar Dandu

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.

Page 115: Java Basics by Kamalakar Dandu

Exercise (contd..)

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

Page 116: Java Basics by Kamalakar Dandu

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.

Page 117: Java Basics by Kamalakar Dandu

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.

Page 118: Java Basics by Kamalakar Dandu

Exercise 4 (contd…)

Grade Average marks

A > 80 %

B >= 70 and < 80%

C >= 60 and < 70%

D < 60%

Page 119: Java Basics by Kamalakar Dandu

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”

Page 120: Java Basics by Kamalakar Dandu

Exercise (contd..) 7. The SU has 4 departments. A student’s marks sheet 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 Maths, Physics, Chemistry, lang1, lang2BPC Biology, Physics, Chemistry, lang1, lang2 HEC History, Economics, Civics, lang1, lang2 CEC 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

Page 121: Java Basics by Kamalakar Dandu

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

Page 122: Java Basics by Kamalakar Dandu

Exercise (contd..)

9. And then stored into the array of Student objects

10. 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.

Page 123: Java Basics by Kamalakar Dandu

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

ThankQ…