500
The Centre for Technology enabled Teaching & Learning DTEL DTEL(Department for Technology Enhanced Learning) 1 Teaching Innovation - Entrepreneurial - Global

sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

The Centre for Technology enabled Teaching & Learning

DTELDTEL(Department for Technology Enhanced Learning)

1Teaching Innovation - Entrepreneurial - Global

Page 2: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

DEPARTMENT OF COMPUTER TECHNOLOGY

Java Programming

SHRI DATTA MEGHE POLYTECHNIC

2

AUTHOR:

MRS. HARSHITA KUNAL WANKHEDE

Page 3: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CONTENT: JAVA PROGRAMMING

CHAPTER 1: 1

CHAPTER 2:2

CHAPTER 3:3

Introduction to Java

Classes, Object and Methods

Interfaces and Packages

Multithreaded Programming and Exception

DTEL DTEL

CHAPTER 4:4

3

CHAPTER 5:5

CHAPTER 6:6

Multithreaded Programming and Exception handling

Java Applets and Graphics Programming

Streams and File

Page 4: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

SYLLABUS GENERAL OBJECTIVE

1

2

The student will be able to:

Use of programming language constructs.

Designing & Implementing application program & applet

Designing Classes, inheritance, polymorphism, wrapper

class, vector, interface, package.

DTEL DTEL 4

3Designing & Implementing application program & applet

program.

4Implementing error handling code, creating own exception.

Page 5: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-1 Introduction to Java

Topic 1: 1

Topic 2: 2

Topic 3: 3

Fundamentals of Object Oriented Programming

Java Features

Constant, Variables and Data Types

Operator and Expression

DTEL DTEL

Topic 4:4

5

Topic 5:5

Operator and Expression

Decision making and Branching

Topic 6:6 Decision making and Looping

Page 6: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-1 SPECIFIC OBJECTIVE / COURSE OUTCOME

1

The student will be able to:

To understand the features, Data types, Decision making

and looping , constructs of java language.

Differentiate between primitive data types and class

DTEL DTEL 6

2Differentiate between primitive data types and class

data types and implement conversion between them.

Page 7: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Fundamentals of Object Oriented Programming

�Object and Classes

�Data abstraction and encapsulation

�Inheritance

�Polymorphism

DTEL DTEL

7

7

�Polymorphism

�Dynamic Binding

Page 8: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Fundamentals of Object Oriented Programming

Types of Inheritance

DTEL DTEL

8

8

Page 9: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Fundamentals of Object Oriented Programming

Types of Inheritance

DTEL DTEL

9

9

Java does not directly implement the multiple inheritance. This is implemented using the concept of interface.

Page 10: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Fundamentals of Object Oriented Programming

Types of Inheritance

DTEL DTEL

10

10

Page 11: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Fundamentals of Object Oriented Programming

Polymorphism

Shape

Draw()

DTEL DTEL

11

11

Circle

Draw()

Rectangle

Draw()

Triangle

Draw()

Page 12: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Features of Java

�Java is simple

�Java is object-oriented

�Java is complied & interpreted

�Java is Platform independent

�Java is portable

�Java is distributed

�Java is robust

DTEL DTEL

12

12

�Java is robust

�Java is secure

�Java’s performance

�Java is multithreaded

�Java is dynamic

Page 13: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Process of java compilation and interpretation

Java compiler

Java interpreter

.java file .class file

Description

Text Editor

Source code

Byte code

Programmer

Hardware and Operating System

DTEL DTEL

13

13

.java file

NotepadDOS EditorTextpad

.class file

javac JavaAppletViewer

Page 14: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-IMPORTANT POINTS

�Java is a free editor language. Programmer can write or edit Java program in Notepad, Dos editor or Textpad. But we cannot compile or interpret java program in the given editor.

�File extension of java program should be is .java

�Java is a case sensitive language.

DTEL DTEL

14

14

Eg: “Java” or “JAVA” are different

Page 15: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Execution Process

Java compiler (javac)

Java interpreter (java)

.java

Java program

.class file

�Java compiler (javac) is used to compile any java file.

� Java compiler will generate class files after successful compilation process of

Output file

Description

DTEL DTEL

15

15

� Java compiler will generate class files after successful compilation process of

compiler.

�JVM is an interpreter for bytecode.

�Java interpreter(java) is used to generate output from the given class file.

Page 16: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Compilation Process Description

�Java compiler (javac) is used to compile any java file.

�Java compiler will generate class files after successful compilation process of compiler.

�The generated class files are binary coded files & size of each class file is small as compared to executable file.

�Therefore class files are also called as magic code files.

DTEL DTEL

16

16

�Such files are useful to copy on the disk, CDROM and over the network/internet.

�Java files are converted in terms of special code(binary) when compiled this binary code is known as Bytecode.

�Bytecode is highly optimized set of instructions designed to be executed by java run-time system, which is called the Java virtual machine(JVM)

�JVM is an interpreter for bytecode.

Page 17: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Execution Process

�Java interpreter(java) is used to generate output from the given class file.

�During execution process java interpreter will search the given class file name in the current directory, if the given class file name is present in the current directory then it will compare file name present in a file.

Description

DTEL DTEL

17

17

�If the class file name and class name is exactly matched then it will execute the main function present in a class.

Page 18: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Example

class Program1

{

public static void main(String args[])

{

System.out.println(“SDMP”);

}

}

Steps to run above program

DTEL DTEL

18

18

C:\>javac Program1.java

C:\>java Program1

Page 19: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Output

DTEL DTEL

19

19

Page 20: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Explanation

�In the above example returntype of main is declared as void because main function is not returning any value.

�Any function which is declared as static, is called as static function such functions are accessible directly through its class name i.e. without using any object we can access static functions.

�Since, java interpreter calls the main function by using classname therefore it is necessary to declare main function as static.

�Java interpreter access the main function from outside of file therefore it is

DTEL DTEL

20

20

�Java interpreter access the main function from outside of file therefore it is necessary to mention access specifier of main as public, if the access specifier of main is declared as private, then java interpreter will not able to access the main function

�Println is a function, which is used to perform output operation on the output screen. It is declared in PrintStream class. out is a object of type PrintStream declared as static present in System class therefore we can access out object of System class by using its class name.

Page 21: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Working with println

class Program2

{

public static void main(String args[])

{

System.out.println("Welcome");

System.out.println("To");

System.out.print("SDMP");

}

}

Example

DTEL DTEL

21

21

}

OUTPUT

Page 22: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Working with println

class Program3

{

public static void main(String args[])

{

System.out.print("Welcome");

System.out.print("To");

System.out.println("SDMP");

}

}

Example

DTEL DTEL

22

22

}

OUTPUT

Page 23: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Working with println

class Program4

{

public static void main(String args[])

{

System.out.print("Welcome");

System.out.println("To");

System.out.println("SDMP");

}

}

Example

DTEL DTEL

23

23

}

OUTPUT

Page 24: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Constant Description

�Value of object cannot be changed.�Use math values such as PI.�for values which will not change for a given program.�Constants are declared using final keyword.�Keyword final indicates once you assign some value to a variable value does

not change throughout the program.�Constants are declared in uppercase.�Declaration syntax:

final type CONSTANT_NAME = expression;�final is a Java keyword, makes a constant.

DTEL DTEL

24

24

�final is a Java keyword, makes a constant.�type must be known by compiler.�CONSTANT_NAME must be valid identifier.�expression evaluated .�should be placed at beginning of class or method.Eg-: final double PI=3.14;

Page 25: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Variable Description

�A variable is a location in memory where values can be stored and

referenced.

�Variables are associated with types, which have particular data sizes and a

restricted set of valid operations that can be performed on them.

�Variable declarations assign an identifier, a type, and may declare an initial

value. Many types have a default value. For example, an uninitialized integer

defaults to 0.

DTEL DTEL

25

25

address

a value

(a default value)

a name (identifier)

a type

Page 26: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Variable Declaration Syntax Description

�Syntax:type variable_name;

ortype variable_name = expression;

�Note�type must be known to the compiler�variable_name must be a valid identifier�expression is evaluated and assigned to variable_name location�In the first form, a default value is given (0, false, or null, depending on type)

DTEL DTEL

26

26

type)

Page 27: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Naming Rules

�Variable names are case-sensitive..

�A variable's name can be any legal identifier.

� an unlimited length sequence of Unicode letters and digits, beginning with

a letter, the dollar sign "$", or the underscore character "_“

� The convention, however, is to always begin your variable names with a

letter, not "$" or "_“

�White space is not permitted

DTEL DTEL

27

27

Page 28: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types

�byte, short, int, and long

for integer values of various sizes

�float and double

for real (rational) values of differing accuracy

�boolean

for logical (true/false) values

�char

for individual characters

Description

DTEL DTEL

28

28

Page 29: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types

• byte:

� An 8-bit integer. It has a minimum value of -128 and a maximum value of 127

(inclusive)

• short:

�–A 16-bit integer. It has a minimum value of -32,768 and a maximum value of

32,767 (inclusive)

Integer Category

DTEL DTEL

29

29

Page 30: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types

• int:

�A 32-bit integer. It has a minimum value of -2,147,483,648 and a maximum value

of 2,147,483,647 (inclusive)

•long:

� A 64-bit integer. It has a minimum value of -9,223,372,036,854,775,808 and a

maximum value of 9,223,372,036,854,775,807 (inclusive)

Integer Category

DTEL DTEL

30

30

Page 31: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types Float Category

•float:

� A 32-bit floating point

• double:

�A 64-bit floating point

DTEL DTEL

31

31

Page 32: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types Boolean & Character

• boolean:

� It has only two possible values: true and false

� This data type represents one bit of information.

• char:

� A 16-bit character

� It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or

65,535 inclusive).

DTEL DTEL

32

32

Page 33: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types

class Program5{public static void main(String args[]){int i=27;System.out.println(“value=“+i);}}

Example

DTEL DTEL

33

33

Page 34: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types

class Program6{public static void main(String args[]){int i=27;System.out.println(“value=“+i+i);}}

Example

DTEL DTEL

34

34

Page 35: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types Example

class Program7{public static void main(String args[]){int i=27;System.out.println("value="+(i+i));}}

DTEL DTEL

35

35

Page 36: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types

class Program3

{

public static void main(String args[])

{

int i=7;

System.out.println("value= "+i+" square= "+i*i);

}

}

Example

DTEL DTEL

36

36

Page 37: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-DATATYPES Example

class percentage

{

public static void main(String args[])

{

int sub1=70,sub2=60,sub3=80,sub4=90;

double per;

per=(sub1+sub2+sub3+sub4)/4;

System.out.println("Marks of subject1="+sub1);

System.out.println("Marks of subject2="+sub2);

DTEL DTEL

37

37

System.out.println("Marks of subject2="+sub2);

System.out.println("Marks of subject3="+sub3);

System.out.println("Marks of subject4="+sub4);

System.out.println("Percentage="+per);

}

}

Page 38: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types Example

class Program10

{

public static void main(String args[])

{

System.out.println(3>2);

System.out.println(2>3);

int a=10,b=20;

System.out.println(a>b);

}

}

DTEL DTEL

38

38

}

Page 39: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types Example

class Program11{public static void main(String args[]){int a=5, b=2;boolean check;check=a>b;System.out.println(check);}}

DTEL DTEL

39

39

}

Page 40: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Primitive Types Example

class Program12{public static void main(String args[]){boolean check;check=true;System.out.println(check);check=!check;System.out.println(check);check=!check;

DTEL DTEL

40

40

check=!check;System.out.println(check);}}

Page 41: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Variables: Scope Description

�Each variable has a scope i.e. the area in the source code where it is

“visible.”

�If you use a variable outside its scope, the compiler reports a syntax error.

�Variables can have the same name when their scopes do not overlap.

�Example

{

int a=.....;

……

}

for(int a=..)

DTEL DTEL

41

41

for(int a=..)

{

……

}

Page 42: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Local Variables Description

�Local variables are declared inside a constructor or a method.

�Local variables lose their values and are destroyed once the constructor or the

method is exited.

�The scope of a local variable is from its declaration down to the closing brace of

the block in which it is declared.

DTEL DTEL

42

42

Page 43: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Identifiers Description

�An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).

�Names given to variables, objects, methods�Must not be a Java keyword�May begin with a letter or the underline character �It cannot start with a digit. �An identifier cannot be true, false, or null.�An identifier can be of any length. �Case-sensitive�Followed by any number of characters, digits, or _ (note, no blanks)

DTEL DTEL

43

43

�Followed by any number of characters, digits, or _ (note, no blanks)

Page 44: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Literals Description

A constant value in a program is denoted by a literal. Literals represent numerical (integer or

floating-point), character, boolean or string values.

Datatypes Values

boolean true or false

int 14, 796, 2147361, 4, 19, -5, 0, 1000

long ends with “L”

65L 23412396432L

float ends with “f” or “F”

DTEL DTEL

44

44

float ends with “f” or “F”

6.23f 5.96F 1e-32f

double 2.0146e123 3.1415926

char Contained in single quotes

‘b’ ‘&’ ‘*’

Escape sequences (similar to c++)

‘\”’ ‘\n’ ‘\t’ ‘\’’

Strings “Hi Mom” “Enter the number : “

Page 45: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Escape Sequences Description

�An escape sequence is a sequence of two characters beginning with the

character \

�A way to represents special characters/symbols

\n Start a new output line

\t Tab character

DTEL DTEL

45

45

Page 46: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Comments Description

� In Java, comments are preceded by two slashes (//) in a line, or enclosed

between /* and */ in one or multiple lines.

� When the compiler sees //, it ignores all text after // in the same line.

� When it sees /*, it scans for the next */ and ignores any text between /*

and */.

DTEL DTEL

46

46

Page 47: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Reserved Words Description

� Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program.

� For example, when the compiler sees the word class, it understands that the word after class is the name for the class.

DTEL DTEL

47

47

Page 48: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Keywords Description

abstract continue for new switch

assert default goto package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum instanceof return transient

DTEL DTEL

48

48

case enum instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const float native super while

Page 49: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Modifiers Description

� Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used.

� Examples of modifiers are public and static.� Other modifiers are private, final, abstract, and protected.� A public datum, method, or class can be accessed by other programs. � A private datum or method cannot be accessed by other programs.

DTEL DTEL

49

49

Page 50: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Statements Description

� A statement represents an action or a sequence of actions.

� The statement System.out.println("Welcome to Java!"); is a statement to

display the greeting "Welcome to Java!" Every statement in Java ends with a

semicolon (;).

DTEL DTEL

50

50

Page 51: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Type casting Description

•The process of converting one data type to another is called type casting

•Forces a value of one data type to be used as a value of another type

•Syntax

Targetvariable=(targetdatatype)sourcevariable;

class Program13

{

public static void main(String args[])

{

byte b;

DTEL DTEL

51

51

byte b;

short s=12;

b=s;

System.out.println(b);

System.out.println(s);

}

}

Page 52: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Type casting

class Program14

{

public static void main(String args[])

{

byte b;

short s=12;

b=(byte)s;

System.out.println(b);

System.out.println(s);

}

CAPACITY=1 BYTE

CAPACITY=2 BYTE

bs

Example

DTEL DTEL

52

52

}

}

CAPACITY=2 BYTE

Page 53: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Type casting Description

class Program15{public static void main(String args[]){byte b=21;short s;int i;s=b;i=s;System.out.println(b);

DTEL DTEL

53

53

System.out.println(b);System.out.println(s);System.out.println(i);}}

Page 54: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Type casting Description

class Program16{public static void main(String args[]){int i=21;short s;byte b;s=(short)i;b=(byte)s;System.out.println(b);

DTEL DTEL

54

54

System.out.println(b);System.out.println(s);System.out.println(i);}}

Page 55: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Type casting Description

class Program17{public static void main(String args[]){int i=65;char ch=(char)i;System.out.println(i);System.out.println(ch);}}

DTEL DTEL

55

55

}

Page 56: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Type casting Description

class Program18{public static void main(String args[]){float a=3.14;System.out.println(a);}}

Default datatype used to store any

DTEL DTEL

56

56

Default datatype used to store any floating constant number is double, which is of 8 bytes, therefore type casting is necessary to assign any floating constant number in float variable as given below(in next slide)

Page 57: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Type casting Description

class Program19{public static void main(String args[]){float a=(float)3.14;System.out.println(a);}}

DTEL DTEL

57

57

Page 58: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Type casting

class Program19{public static void main(String args[]){float a=3.14F;System.out.println(a);}}

Description

DTEL DTEL

58

58

}

Page 59: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Command Line Argument Description

�A Java application can accept any number of arguments from the command

line.

�The user can enter command-line arguments when invoking the application.

�When running the java program from java command, the arguments are

provided after the name of the class separated by space.

�Example:

class Program20

{

public static void main(String args[])

{

DTEL DTEL

59

59

{

for(int i=0;i<=args.length-1;i++)

System.out.println(args[i]);

}

}

Page 60: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Data Storage Problem

class Program21{public static void main(String args[]){long l=214748364796;System.out.println(l);}}

Description

Default datatype used to

store any integer constant

number is int which is of 4

bytes having range varies

from 2147483647 to

-2147483648 therefore,

java interpreter will not

able to store above integer

DTEL DTEL

60

60

} able to store above integer

constant given in the

program i.e.

214748364796. Hence,

above program will give

error.

Page 61: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Data Storage Problem Description

To solve the above problem we have to change default memory of Java interpreter from 4 bytes to 8 bytes as given below

class Program22{public static void main(String args[]){long l=214748364796L;

DTEL DTEL

61

61

long l=214748364796L;System.out.println(l);}}

Page 62: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Operators Description

�Operators are special symbols that perform specific operations on one,

two, or three operands, and then return a result.

�Operators with higher precedence are evaluated before operators with

relatively lower precedence.

�Arithmetic Operators

S.N. Operator Meaning Example

1 + Addition a = b + c;

DTEL DTEL

62

62

1 + Addition a = b + c;

2 - Subtraction a = b - c;

3 * Multiplication a = b * c;

4 / Division a = b / c;

5 % Modulus division(Remainder) a = b % c;

Page 63: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Arithmetic Operators Description

Integer Arithmetic Operations

Symbol Operation Example

+ Addition 45 + 5 = 50

- Subtraction 657 – 57 = 600

DTEL DTEL

63

63

* Multiplication 700 * 3 = 2100

/ Division 10 / 3 = 3

% Remainder 10 % 3 = 1

Page 64: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Arithmetic Operators

class Arithmetic{public static void main(String args[]){System.out.println("5+2="+(5+2));System.out.println("5-2="+(5-2));System.out.println("5*2="+5*2);System.out.println("5/2="+5/2);

Description

DTEL DTEL

64

64

System.out.println("5/2="+5/2);System.out.println("5%2="+5%2);}}

Page 65: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Arithmetic Operators Description

WAP to print sum of the number

class sum{public static void main(String args[]){int a=10;System.out.println("sum="+(a+a));}

DTEL DTEL

65

65

}}

Page 66: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Operators Description

�Relational Operators

The result is boolean, always

< less than

> greater than

== equal to

<= less than or equal to

>= greater than or equal to

!= not equal to

�Logical Operators

DTEL DTEL

66

66

�Logical Operators

�Binary operators

logical AND: && (two boolean operands w/ short circuit)

logical OR: || (two boolean operands w/ short circuit)

� Unary operator

logical NOT: ! (single boolean operand)

Page 67: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Logical OperatorsLogical Operators Truth Table

Truth Table for Operator !

Truth Table for Operator &&

Operand !Operand

true false

false true

DTEL DTEL

67

67

Operand1 Operand2 Operand1 && Operand2

false false false

false true false

true false false

true true true

Page 68: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Logical OperatorsLogical Operators Truth Table

Truth Table for Operator ||

Operand1 Operand2 Operand1 ||

Operand2

false false false

false true true

true false true

true true true

DTEL DTEL

68

68

true true true

Page 69: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Assignment operator = Description

�Assignment operators are used to assign the value of an expression to a variable.

�Assignment operator, ‘=‘ is used in the program for assignment.�A = 36;

Sets a = to the constant 36 at execution time

�int A =36;

Sets A = to the constant 36 at compile time

Initializes A to 36 at the time memory is set aside for it

+= c += 7 c = c + 7 10 to c

DTEL DTEL

69

69

-= d -=4 d = d – 4 1 to d

*= e *= 5 e = e * 5 20 to e

/= f /= 3 f = f / 3 2 to f

%= g %= 9 g = g % 9 3 to g

int c = 3, d = 5, e = 4, f = 6, g = 12;

Page 70: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Increment and Decrement Operators Description

x++; // Same as x = x + 1;

++x; // Same as x = x + 1;

x––; // Same as x = x - 1;

suffix

prefix

suffix

DTEL DTEL

70

70

––x; // Same as x = x - 1; prefix

Page 71: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Increment and Decrement Operators Description

++ preincrement ++a Increment a by 1 then use the new

value

++ postincrement a++ Use the current value of a then

increment by 1

-- predecrement --b Decrement b by 1 then use the new

DTEL DTEL

71

71

-- predecrement --b Decrement b by 1 then use the new

value

-- postdecrement b-- Use the current value of b then

decrement by 1

Page 72: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Conditional Operators Description

�The character pair ?: is a ternary operator of Java, which is used to construct

conditional expressions of the following form:

Syntax:- expr1?expr2:expr3

Where expr1,expr2 and expr3 are expressions

The operator ?: work as follows

�First expr1 is evaluated.

�If it is nonzero(true), then the expression expr2 is evaluated and becomes the

value of the conditional expression.

�If expr1 is false, expr3 is evaluated and its value becomes the value of the

conditional expression.

DTEL DTEL

72

72

conditional expression.

�Note that only one of the expressions(either expr2 or expr3) is evaluated.

�For example, consider the following statements:

x=10; y=15;

a=(x>y)?x:y; a=(10>15)?10:15; a=15Condition ? exp1 : exp2

Ret

urn

ed

Ret

urn

edIf true

If false

Page 73: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Conditional Operators

class conditional

{

public static void main(String arg[])

{

int x=25,y=22;

System.out.println("x="+x);

System.out.println("y="+y);

x=(y>25)?y:50;

Description

DTEL DTEL 73

x=(y>25)?y:50;

System.out.println("x=(y>25)?y:50");

System.out.println("Now,x="+x);

}

}

Page 74: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Bitwise operators Description

� bitwise AND: & (two integer operands)

� bitwise OR: | (two integer operands)

� bitwise exclusive OR: ^ (two integer operands)

� left shift <<

� right shift >>

� Bitwise AND assignment &=

� Bitwise OR assignment !=

�Unary operator

�bitwise NOT: ~ (single integer operand)

�Following table shows the bitwise logical operators and result when applied on

DTEL DTEL

74

74

�Following table shows the bitwise logical operators and result when applied on

single bit.A B A&B A|B A^B ~A

0 0 0 0 0 1

0 1 0 1 1 1

1 0 0 1 1 0

1 1 1 1 0 0

Page 75: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Left shift operator Description

�It shifts all the bits in a value to the left, a specified number of times.

�It is denoted by “<<“

�Syntax:- value<<num;

�Example:

class Program23

{

public static void main(String args[])

{

int a=2,i;

i=a<<2;

DTEL DTEL

75

75

i=a<<2;

System.out.println("a="+a);

System.out.println("i="+i);

}

}

8 4 2 1

2 is represented as 0 0 1 0

8 is represented as 1 0 0 0

Page 76: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Right shift operator Description

�It shifts all the bits in a value to the right, a specified number of times.

�It is denoted by “>>“

�Syntax:- value>>num;

�Example:

class Program24

{

public static void main(String args[])

{

int a=16,i;

i=a>>2;

DTEL DTEL

76

76

i=a>>2;

System.out.println("a="+a);

System.out.println("i="+i);

}

} 16 8 4 2 1

16 is represented as 1 0 0 0 0

4 is represented as 0 0 1 0 0

Page 77: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-LECTURE 6:-Example of bitwise operator Description

public class Test {

public static void main(String args[]) {

int a = 60; /* 60 = 0011 1100 */

int b = 13; /* 13 = 0000 1101 */

int c = 0;

c = a & b; /* 12 = 0000 1100 */

System.out.println("a & b = " + c );

c = a | b; /* 61 = 0011 1101 */

c = a << 2; /* 240 = 1111 0000 */

System.out.println("a << 2 = " + c );

c = a >> 2; /* 15 = 1111 */

System.out.println("a >> 2 = " + c );

c = a >>> 2; /*15 = 0000 1111 */

System.out.println("a >>> 2 = " + c );

} }

DTEL DTEL 77DTEL DTEL

77

77

c = a | b; /* 61 = 0011 1101 */

System.out.println("a | b = " + c );

c = a ^ b; /* 49 = 0011 0001 */

System.out.println("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */

System.out.println("~a = " + c );

} }

Page 78: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Special Operators Description

Java supports following special operators

1. instanceof operator

The instanceof is object reference operator and returns true if the object on

the left hand side is an instance of the class given on the right hand side.

Example:

class X

{

public static void main(String args[])

{

X x=new X();

DTEL DTEL

78

78

X x=new X();

if(x instanceof X)

System.out.println("x is an instance of X");

}

}

Page 79: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Special Operators Description

2. Dot operator

The dot operator(.) is used to access the instance variables and methods of

class objects

For example:

Student s= new Student();

s.name=“ABC”;

s.display();

DTEL DTEL

79

79

Page 80: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-OPERATOR PRECEDENCE Description

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

DTEL DTEL

80

80

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

Page 81: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Mathematical Functions Description

Rounding Methods defined by Math class

max():static int max(int x, int y) Returns the maximum of x and y.static long max(long x, long y) Returns the maximum of x and y.static float max(float x, float y) Returns the maximum of x and y.static double max(double x, double y) Returns the maximum of x and y.

min():static int min(int x, int y) Returns the minimum of x and y.

DTEL DTEL

81

81

static int min(int x, int y) Returns the minimum of x and y.static long min(long x, long y) Returns the minimum of x and y.static float min(float x, float y) Returns the minimum of x and y.static double min(double x, double y) Returns the minimum of x and y.

Page 82: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Mathematical Functions Example

class minmax{public static void main(String args[]){int x=10,y=20;int z=Math.min(x,y);System.out.println("Minimum value out of 10 & 20 is:"+z);int w=Math.max(x,y);System.out.println("Maximum value out of

DTEL DTEL

82

82

System.out.println("Maximum value out of 10 & 20 is:"+w);}}

Page 83: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Mathematical Functions Description & Example

Exponential Functions

sqrt();static double sqrt(double arg) Returns the square root of arg.

Example:

class squareroot{public static void main(String args[])

DTEL DTEL

83

83

public static void main(String args[]){double x=2.1;double z=Math.sqrt(x);System.out.println("Square root of 2.1 is "+z);}}

Page 84: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Mathematical Functions Description & Example

Exponential Functions

pow();static double pow(double y, double x) Returns y raised to the x;for example, pow(2.0, 3.0)returns 8.0.

Example:

class power{

DTEL DTEL

84

84

{public static void main(String args[]){double a=2,b=3;double z=Math.pow(a,b);System.out.println("2 to the power 3 is "+z);}}

Page 85: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Mathematical Functions Description

Exponential Functions

exp();static double exp(double arg) Returns e to the arg.

Example:

class exponential{public static void main(String args[])

DTEL DTEL

85

85

public static void main(String args[]){double a=1;double z=Math.exp(a);System.out.println("Exponential of 1 is "+z);}}

Page 86: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Mathematical Functions Description & Example

Rounding Methods defined by Math class

abs():static int abs(int arg) Returns the absolute value of arg.static long abs(long arg) Returns the absolute value of arg.static float abs(float arg) Returns the absolute value of arg.static double abs(double arg) Returns the absolute value of arg.

Example:class Absolute{

DTEL DTEL

86

86

{public static void main(String args[]){double a=1.500;double z=Math.abs(a);System.out.println("Absolute of 1.500 is "+z);double b=1.50012;double w=Math.abs(b);System.out.println("Absolute of 1.50012 is "+w);}}

Page 87: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Mathematical Functions Description & Example

Rounding Methods defined by Math class

round():static int round(float arg) Returns arg rounded up to the nearest int.static long round(double arg) Returns arg rounded up to the nearest long.

Example:

class Round

DTEL DTEL

87

87

{public static void main(String args[]){double a=1.50,b=1.49;double z=Math.round(a);System.out.println("Round of 1.50 is "+z);double w=Math.round(b);System.out.println("Round of 1.49 is "+w);}}

Page 88: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Decision Making & Branching Description

�When the program does not follow sequential flow & jumps to another part

of the code it is called branching.

�Two types of branching

�Conditional branching:-It is based on particular condition.

�Unconditional branching:-It takes place without any decision.

DTEL DTEL

88

88

Page 89: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Decision Making or Control statements

Entry

Description

1. Simple if statement

If the condition is true the statement

under if statement will be executed

otherwise the statement after if

statement will be executed.

�Syntax of simple if statement

if (condition)

statement;

or

Flow chart of Simple if statement

conditionfalse

true

DTEL DTEL

89

89

or

if (condition)

{

statement1;

statement2;

statement3;

}

true

Statements under ‘if’

statement

Statements after ‘if’

statement

Page 90: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Decision Making or Control statements Description

2. The ‘if-else’ statement

If the condition is true then the

statement under if statement will be

executed otherwise the statement under

else statement will be executed. In both

cases the statement after if –else

statement will be executed.

�Syntax of ‘if-else’ statement

if(condition)

Flow chart of if-else’ statement

conditionfalse

trueStatements

under ‘else’

Entry

DTEL DTEL

90

90

if(condition)

{

statements for condition is true;

}

else

{

statements for condition is false;

}

Statements after the blocks;

true

Statements under ‘if’

statement

Statements after ‘if’

statement

under ‘else’

statement

Page 91: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-IF-ELSE Example

class Divisible{public static void main(String args[]){int num=15;if(num%5==0)System.out.println("Number is divisible by 5");elseSystem.out.println("Number is not divisible by 5");}}

DTEL DTEL 91

}

Page 92: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Decision Making or Control statements Description

3. Nested if-else structure

When a series of decisions are involved more than one if else statement are

used in nested form.

�Syntax of Nested if-else structure

If (condition1) //first ‘if’

{

statement1;

if(condition2) //second ‘if’

{

statement2;

statement3;

DTEL DTEL

92

92

statement3;

}

else //second ‘else’

{

statement4;

statement5;

}

}

else //first ‘else’

{

statement6;

}

Statements after the if-else;

Page 93: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Decision Making or Control statements Description

�Here, if the condition1 is true

statement1 is executed else

statement6 is executed.

�Means, any one of the statement1

and statement6 is executed.

�Statement2 and statement3 are

executed only when both condition1

and condition2 are true.

�Statement4 and stetement5 are

Flow chart of Nested if-else structure

condition1

Statement1

Statement6

condition2

Entry

false

true

false

DTEL DTEL

93

93

�Statement4 and stetement5 are

executed when condition1 is true

and condition2 is false.

�We can say that in any case,

maximum three statements are

executed at a time and at least one.

�This hierarchy can be extended in

any deep structure.

Statement2

Statement3

condition2

Statement4

Statement5

Statements after the

blocks

true

Page 94: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Decision Making or Control statements Description

4. The if-else ladder

The if-else ladder is another way of

putting the ‘if’s together when multi-

path decisions are involved. A multi-

path decision is a chain of ‘if’s in which

statements are associated with each

‘else’ is an ‘if’. This construct is known

as if-else ladder.

Syntax of if-else ladder

if (condition1)

statement1;

else

if(condition2)

statement2;

else

if(condition3)

DTEL DTEL

94

94

The conditions are evaluated from top of

the ladder to the bottom.

if(condition3)

statement3;

else

statement4;

Page 95: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Decision Making or Control statements Description

class greatest{

public static void main(String args[]){

int a=40,b=30,c=20;if(a>b && a>c)System.out.println(a+" is greatest");else if(b>a && b>c)System.out.println(b+" is greatest");elseSystem.out.println(c+" is greatest");

DTEL DTEL

95

95

System.out.println(c+" is greatest");}

}

Page 96: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Decision Making or Control statements

The very familiar example of this construct is to find the grade of the

student according to marks. Such as,

For example examination board is giving grade according to marks

as below:

Example

Marks Grade

Above 75 Distinction

60 to 74 First class

50 to 59 Second class

DTEL DTEL

96

96

This can be done by applying the if-else ladder as,

50 to 59 Second class

40 to 49 Pass class

Below 40 Fail

Page 97: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Decision Making or Control statements

//program to find grade according to marks

class IfElseLadder

{

public static void main(String args[])

{

float marks = 62.12f;

System.out.println("Marks : "+marks);

System.out.print("Your grade is : ");

if(marks >= 75)

System.out.print("Distinction");

Example

if(marks >= 60)

System.out.print("First class");

else

if(marks >= 50)

System.out.print("Second class");

else

if(marks >= 40)

System.out.print("Pass class");

else

System.out.print("Fail");

DTEL DTEL

97

97

System.out.print("Distinction");

else

System.out.print("Fail");

} }

Page 98: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Decision Making or Control statements Description

The switch-case statement:-

� Switch is the multi-way selection statement.

�It tests the value of the variable or expression(int, char) against the list of case

values and when match is found, a block of statements associated with that case

are executed.

� It is applicable when it is impossible to write the ‘if’ statement many times in the

programs.

� Generally, it is used to create the menu driven program to select from the multiple

DTEL DTEL

98

98

� Generally, it is used to create the menu driven program to select from the multiple

choices.

Page 99: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Decision Making or Control statements Description

Syntax of switch-case statement Flow chart of switch-case statement

switch(variable)

{

case value-1:

statements-1;

break;

case value-2:

statements-2;

break;

- - - - - - - - -

variable

Statements-1 Statements-2 Default block

defaultValue 2

Value 1

Entry

DTEL DTEL

99

99

- - - - - - - - -

- - - - - - - - -

default:

default block;

}

statement-out;

Statements-1 Statements-2 Default block

Statements-out

Page 100: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-The switch-case statement

class NumDisplay

{

public static void main(String args[])

{

int x = 6;

System.out.println("x = "+x);

System.out.print("It is ");

switch(x)

{

Example

break;

case 4: System.out.println("Four");

break;

case 5: System.out.println("Five");

break;

case 6: System.out.println("Six");

break;

default: System.out.println("No. not

correct");

DTEL DTEL

100

100

{

case 1: System.out.println("One");

break;

case 2: System.out.println("Two");

break;

case 3: System.out.println("Three");

correct");

}

}

}

Page 101: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-The switch-case statement Example

class switchcheck

{

public static void main(String args[])

{

char grade='A';

switch(grade)

{

case 'A':

System.out.println("Your Performane is

Excellent");

break;

case 'D':

System.out.println("Your Performane is

Satisfactory");

break;

default:

System.out.println("Invalid grade");

break;

}

}

DTEL DTEL

101

101

Excellent");

break;

case 'B':

System.out.println("Your Performane is

Good");

break;

case 'C':

System.out.println("Your Performane is

Better");

}

}

Page 102: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Conditional /ternary /?: operator Description

�Java supports another conditional operator that is known as the

ternary operator "?:" and basically is used for an if-then-else as shorthand as

boolean expression ? operand1 : operand2;

�The "?:" operator evaluates an expression which may also be an operand and

returns operand1 if the expression is true; otherwise returns operand2, if the

expression is false.

�We can understand this thing with the help of a diagram shown as:

If false

DTEL DTEL

102

102

�If we analyze this diagram then we find that, operand1 is returned, if the

expression is true; otherwise operand2 is returned in case of false expression.

Expression ? Op1 : Op2

Ret

urn

ed

Ret

urn

edIf true

Page 103: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Decision making and looping Description

�A Loop is the cycle of execution.

�It is what we can call repeatedly executing the same block of code until the

termination condition is met.

�In the process of looping, a sequence of statement is executed until some

condition of termination of the loop is satisfied.

�Java is having three different loop statements.

1. while loop

2. do-while loop

3. for loop

DTEL DTEL

103

103

3. for loop

Page 104: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The while loop Description

�The structure of the while loop is given below.

initialization;

while (condition)

{

//body of the loop;

}

�The ‘while’ is an entry controlled loop structure.

�That is, before the program control enters the loop, the loop condition is

checked.

�It can also be called as pre-test loop.

DTEL DTEL

104

104

�It can also be called as pre-test loop.

�If the condition given is evaluated to true then the body of the loop is

executed until the condition satisfies to true.

�When the condition becomes false, the loop is terminated.

�Then statements written after the loop are executed.

�If condition doesn’t become true anytime then loop will go into infinite

iteration execution.

Page 105: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The while loop Description & Example

Flowchart of while loop statement Example of while loop

Initialization

conditionfalse

//Program to find addition of 10 natural numbers.

class WhileAdd

{

public static void main(String args[])

{

int a = 0, sum = 0;

while(a<=10)

{

sum = sum + a;

DTEL DTEL

105

105

Body of the loop

Statements after the

loop

truesum = sum + a;

a++; //or a = a+1;

}

System.out.println(“Addition is ”+sum);

}

}Program to find addition of 10 natural numbers

Page 106: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The while loop Example

class reverse{public static void main(String args[]){int num=123,r;while(num!=0){r=num%10;num=num/10;System.out.print(r);}

DTEL DTEL

106

106

}}}

Page 107: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The while loop Example

class palindrome{public static void main(String args[]){int num=121,n=num,reverse=0,remainder;while(num>0){remainder=num%10;reverse=reverse*10+remainder;num=num/10;}

DTEL DTEL

107

107

}if(reverse==n)System.out.println(n+" is a Palindrome number");elseSystem.out.println(n+" is not a Palindrome number");}}

Page 108: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The while loop Example

class fibonacci1{public static void main(String args[]){int f1=1,f2=1,f3,n=1;System.out.println(f1);System.out.println(f2);while(n<10){f3=f1+f2;

DTEL DTEL

108

108

f3=f1+f2;System.out.println(f3);f1=f2;f2=f3;n++;}}}

Page 109: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The do-while loop Description

�Sometimes in the program it is desirable to execute your loop at least once.

�The do-while loop can be applied in this case.

�It is post-test loop.

�That is, the loop is executed first and then the loop condition is checked.

�The condition is written at the end of the loop.

�This is also called as exit-controlled loop.

�That is, exit of the program control from loop is decided by loop condition.

�The syntax of do-while loop statement is,

do

{

DTEL DTEL

109

109

{

//body of the loop;

}

while(condition);

Page 110: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The do-while loop Description

�On reaching the do statement, the body of the loop is executed first.

�Then the loop condition written in ‘while’ is checked.

�If it is true then program control will proceed to execute next iteration of the loop

else next statements are executed.

�When the condition becomes false, the loop gets terminated.

�Remember, there is a terminating semicolon given at the end of the while

statement.

DTEL DTEL

110

110

Page 111: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The do-while loop Description & Example

Flowchart of do-while loop statement Example of do-while loop

Initialization

Body of the loop

//Program squares of numbers

class DoWhileSquare {

public static void main(String args[]) {

int num = 1;

do {

System.out.print("Square of ");

System.out.print(num+" : ");

System.out.println(num*num);

num++;

}

while(num<=10);

}}

DTEL DTEL

111

111

condition

Statements after the

loop

true

false

Flowchart of while loop statement

}}

Program using simple do-while loop

Page 112: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The for loop Description

�The ‘for’ loop is another entry-controlled loop, that provides a more concise

loop control structure.

�That is, initialization, condition and increment/decrement can be done in the

single loop statement as given below.

for(initialization; condition; increment/decrement)

{

Body of the loop;

}

DTEL DTEL

112

112

Page 113: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The for loop Description

Flowchart of the ‘for’ loop This loop control structure works as below.

1. Initialization part is executed first. Here, we can

do the initialization of the loop control variables.

This statement is executed only once i.e. before

the start of execution of the loop.

2. In the second stage, the condition given is

tested. If it is evaluated to true, then body of the

loop is executed. Generally, the condition is

related with the loop counter. But it is not

necessary to give condition related to loop

Initialization

condition

false

true

DTEL DTEL

113

113

necessary to give condition related to loop

counter only. The condition is tested for each

iteration of the loop. When it becomes false the

loop gets terminated.

3. After completion of execution of the body of

the loop, increment / decrement statement is

executed. Any action we can write in this

statement. Then again control gets transferred to

the condition to execute the next iteration.

Body of the loop

Increment/decrement

Statements after the

loop

Page 114: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The for loop Example

Example of the ‘for’ loop

class ForFact

{

public static void main(String args[])

{

int fact = 1, num=5;

for(int i = num ;i>0; i--)

fact = fact * i;

DTEL DTEL

114

114

fact = fact * i;

System.out.print ln("Factorial of 5= "+ fact);

}

}

Page 115: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The for loop Example

class star

{

public static void main(String args[])

{

int i,j;

for(i=0;i<4;i++)

{

for(j=i;j<4;j++)

{

DTEL DTEL

115

115

{

System.out.print("*");

}

System.out.println();

}

}

}

Page 116: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The for loop Example

class prime{public static void main(String args[]){int i,j,num;num=10;for(i=1;i<=num;i++){for(j=2;j<i;j++){if(i%j==0)

DTEL DTEL

116

116

if(i%j==0)break;}if(j==i||j==1)System.out.println(i);}}}

Page 117: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The for loop Example

class Prime1

{

public static void main(String args[])

{

int N=5,i,flag=0;

for(i=2;i<N;i++)

{

if(N%i==0)

{

DTEL DTEL

117

117

{

System.out.println(N+"is not a prime number");

flag=1;

}

}

if(flag==0)

System.out.println(N+"is a prime number");

}

}

Page 118: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-The for loop

class fibonacci

{

public static void main(String args[])

{

int n1=1,n2=1,n3;

System.out.println(n1);

System.out.println(n2);

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

Example

DTEL DTEL

118

118

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

{

n3=n1+n2;

System.out.println(n3);

n1=n2;

n2=n3;

}

}

}

Page 119: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Comparison of three loop structures Description

while do-while for

x=0

while(x<10)

{

- - - - -;

- - - - -;

x++;

}

x=0;

do

{

- - - - -;

- - - - -;

x++;

}

for(x=0;x<10;x++)

{

- - - - -;

- - - - -;

}

DTEL DTEL

119

119

} }

while(x<10);

Page 120: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Jump statements Description

�Sometimes while executing the loop it is necessary to skip some part of the

loop or exit from the loop when certain conditions are met.

�In these cases the jump statements are used.

�There are two jump statements related to loop structures.

1. break statement.

2. continue statement.

break statement.

�The ‘break’ can also be used in the loop control structures.

DTEL DTEL

120

120

�The ‘break’ can also be used in the loop control structures.

�It is used to jump out of the loop when this statement is encountered inside

the loop.

Page 121: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-The break statement Example

var while

var<20

Print

var

var=var

+1

if(var>

15)

10 10<20

true

10 10+1=1

1

11>15

false

11 11<20

true

11 11+1=1

2

12>15

false

12 12<20

true

12 12+1=1

3

13>15

false

13 13<20 13 13+1=1 14>15

class BreakDemo

{

public static void main(String args[ ])

{

int var=10;

while(var<20)

{

System.out.println(var);

var=var+1;

if(var>15)

break;

}

System.out.println(“Loop completed…”);

DTEL DTEL

121

121

13 13<20

true

13 13+1=1

4

14>15

false

14 14<20

true

14 14+1=1

5

15>15

false

15 15<20

true

15 15+1=1

6

16>15

True

break

System.out.println(“Loop completed…”);

}

}

Page 122: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:- Labeled loops Description

Using break as a form of goto / labeled loops

�The general form of the labeled break statement is,

break label;

Here, label is the name of a label that identifies a block of code.

�When this form of break executes, control is transferred out of the named block

of code.

�The labeled block of code must enclose the break statement.

DTEL DTEL

122

122

Page 123: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:- Labeled loops Example

x=0 y=0;

0<10

if(y==5) false print 0 &

y=y+1

x=0 y=1

1<10

if(y==5) false print 1 &

y=y+1

x=0 y=2

2<10

if(y==5) false print 2 &

y=y+1

x=0 y=3 if(y==5) false print 3 &

class BreakNested

{

public static void main(String args[ ])

{

outer:

for(int x=0; x<10; x++)

{

System.out.println(“This is ”+x+“: ”);

for(int y=0;y<10;y++)

{

if(y==5)

break outer;

DTEL DTEL

123

123

x=0 y=3

3<10

if(y==5) false print 3 &

y=y+1

x=0 y=4

4<10

if(y==5) false print 4 &

y=y+1

x=0 y=5

5<10

if(y==5) true Print

program

finished

break outer;

System.out.println(“ ”+y+“ ”);

}

}

System.out.println(“Program finished..”);

}

}

Page 124: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:- The continue statement Description

The continue statement

General form of the ‘continue’ is:

continue;

When the ‘continue’ is encountered in

the loop the program control skips all the

further statements after that in the loop

and proceed to execute the next

iteration.

Flowchart of continue statement

Initialization

Statement 1

conditionfalse

true

DTEL DTEL 124

iteration. Statement 1

Statement 2

Statement 3

continue

Page 125: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:- The 'continue' statement Example

i=0 0%2==0 true continue

i=0+1=1 1%2==0 false Print 1

i=1+1=2 2%2==0 true continue

i=2+1=3 3%2==0 false Print 3

i=3+1=4 4%2==0 true continue

i=4+1=5 3%2==0 false Print 5

| | |

class ContinueDemo

{

public static void main(String args[ ])

{

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

{

if(i%2 == 0)

continue;

System.out.println(i+“ ”);

}

}

DTEL DTEL

125

125

i=8+1=9 9%2==0 false Print 9}

}

Page 126: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Labeled loops Description & Example

Using continue as a form of goto / labeled

loops

continue may specify a label to describe

which enclosing loop to continue.

// Using continue with a label

class ContinueLabel

{

public static void main(String args[ ])

{

System.out.print(“ ” + (i * j));

}

}

System.out.println( );

}

}

DTEL DTEL

126

126

{

outer: for(int i=0; i<10; i++)

{

for(int j=0; j<10; j++)

{

if(j > i)

{

System.out.println( );

continue outer;

}

Page 127: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Return Description & Example

� The return statement is used to explicitly

return from a method.

� That is, it causes program control to

transfer back to the caller of the

method.As such, it is categorized as a

jump statement.

� At any time in a method the return

statement can be used to cause execution

to branch back to the caller of the

method. Thus, the return statement

immediately terminates the method in

class Return{public static void main(String args[]){boolean t = true;System.out.println("Before the return.");if(t) return; // return to callerSystem.out.println("This won't execute.");}}

DTEL DTEL

127

127

immediately terminates the method in

which it is executed.

� The example illustrates this point. Here,

return causes execution to return to the

Java run-time system, since it is the run-

time system that calls main( ).

Page 128: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-2 Classes, Object and Methods

Topic 1: 1

Topic 2: 2

Topic 3: 3

Classes, Object and Methods

Inheritance

Visibility Control

DTEL DTEL

Topic 4:4

128

Array, Strings, Vector and Wrapper Classes

Page 129: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-2 SPECIFIC OBJECTIVE / COURSE OUTCOME

1

The student will be able to:

To create classes, objects and make use of arrays and strings.

They will also learn the concepts of inheritance and garbage

DTEL DTEL 129

2They will also learn the concepts of inheritance and garbage

collection.

Page 130: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Class Description

�A class is a user-defined data type with the template that serves to define its properties.

�A class is declared by the keyword class. Class definition form is given below.

�SYNTAX

class class-name

{

data-type instance-variable1;

data-type instance-variable2;

- - - - -;

data-type instance-variableN;

data-type method-name1(parameter-list)

{

//body of the method1

DTEL DTEL

130

130

//body of the method1

}

data-type method-name2(parameter-list)

{

//body of the method2

}

- - - - -;

data-type method-nameN(parameter-list)

{

//body of the methodN

}

}

Page 131: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Class, Object & Method Description

�Classes create objects and use methods to communicate between them.

�In Java, the data items are called as fields and functions are called as methods.

�An object is instance of class.

�General Form of Object Declaration:

classname object_name = new classname();

�General Form of Method Declaration:

Access specifier returntype methodname(parameters)

{

( body of method)

DTEL DTEL

131

131

( body of method)

}

Page 132: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Example

Example 1 showing declaring class & object

class Data

{

public int a;

}

class Myclass1

{

public static void main(String args[])

{

int a=100

d1

DTEL DTEL

132

132

{

Data d1=new Data();

d1.a=100;

System.out.println(d1.a);

}

}

4 bytes

Page 133: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Explanation Description

�In the above example Data is a class containing single integer data member

which is declared as public.

�Default access specifier of data member and member functions of class is

always public.

�Main program is present in a class named as Myclass1.

�Main program can access data member i.e. ‘a’ variable of Data class by using

object of Data class, it is necessary to create any object by using new operator.

�d1 is a object of type Data which will allocate 4 bytes of memory during

runtime.

DTEL DTEL

133

133

runtime.

�d1 can access ‘a’ variable as it is declared as public.

�Hence above program will generate following output.

�After successful compilation, java compiler will generate two class files named

as Data.class and Myclass1.class

Page 134: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Reference Object Example

class Data

{

public int a,b;

public void set(int n1,int n2)

{

a=n1;

b=n2;

}

public void show()

{

Data d1=new Data();

d1.set(10,20);

Data d2=d1;

d1.show();

d2.show();

}

}

Reference object

DTEL DTEL

134

134

{

System.out.println("A="+a+"\nB="+b);

}

}

class Myclass5

{

public static void main(String args[])

{

int a=10-> 4 bytes

int b=20-> 4 bytes

8 bytes

d1d2

Reference object

Page 135: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Constructors Description

�A constructor initializes an object immediately upon creation.

�It has the same name as the class in which it resides and it is syntactically

similar to a method.

�Once defined, the constructor is automatically called immediately after the

object is created, before the new operator completes.

�Constructors look a little strange because they have no return type, not even

void. This is because the implicit return type of a class’ constructor is the class

type itself.

�Constructor is a special member function.

DTEL DTEL

135

135

�Constructor is a special member function.

�It does not have any return type,not even void.

�It does not have any return statement(returns).

�It is declared in public section.

�It has same name as class name.

�It can be overloaded.

Page 136: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Types of Constructors Example

class Data

{

public int a,b;

public Data()

//Default Constructor

{

a=b=10;

}

public Data(int n1,int n2)

public Data(Data d)

//Copy Constructor

{

a=d.a;

b=d.b;

}

public void show()

{

System.out.println("A="+a);

DTEL DTEL

136

136

public Data(int n1,int n2)

//Parameterised Constructor

{

a=n1;

b=n2;

}

System.out.println("A="+a);

System.out.println("B="+b);

}

}

Page 137: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Types of Constructors Example

class MyConstructor

{

public static void main(String

args[])

{

Data d1=new Data();

Data d2=new Data(10,20);

Data d3=new Data(d2);

d1.show();

int a=10-> 4 bytes

int b=10-> 4 bytes

d1

8 bytes

int a=10-> 4 bytes

int b=20-> 4 bytes

int a=10-> 4 bytes

int b=20-> 4 bytes

d3d2

DTEL DTEL

137

137

d1.show();

d2.show();

d3.show();

}

}

int b=20-> 4 bytes int b=20-> 4 bytes

8 bytes 8 bytes

Page 138: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Constructor Overloading Description

The previous example can be used to show constructor overloading.

DTEL DTEL

138

138

Page 139: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Garbage Collection Description

� In java, the memory allocated to an objects gets deallocated automatically,

when memory space occupied is not in use.

� This concept is known as garbage collection.

� Student s1=new Student();

� Student s2=new Student();� S1=s2;

DTEL DTEL

139

139

Page 140: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Finalize() Method Description

�Sometimes an object will need to perform some action when it is destroyed.

�By using finalization, you can define specific actions that will occur when an

object is just about to be reclaimed by the garbage collector.

�It is important to understand that finalize() is only called just prior to garbage

collection.

�The finalize() method has this general form:

protected void finalize()

{

// finalization code here

}

DTEL DTEL

140

140

}

Here, the keyword protected is a specifier that prevents access to

finalize() by code defined outside its class.

Page 141: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Dynamic Dispatch Method Description & Example

�Dynamic Dispatch method is a concept

of Java language in which reference

object of super class, can access methods

of super class and sub class.

�Example:

class A

{

public void show()

{

System.out.println("I am in A");

}

{

public void show()

{

System.out.println("I am in C");

} }

class inherit

{

public static void main(String args[])

{

A a1=new A();

B b1=new B();

DTEL DTEL

141

141

}

}

class B extends A

{

public void show()

{

System.out.println("I am in B");

}

}

class C extends B

B b1=new B();

C c1=new C();

A r;

r=a1;

r.show();

r=b1;

r.show();

r=c1;

r.show();

} }

Page 142: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Dynamic Dispatch Method Description & Example

�In the this example ,C is the sub class of

B,B is sub class of A, therefore A is

known as super class.

�By using the object of classes, we can

access corresponding method of

invoking object but we can’t access

method of super class.

�But by creating reference object link

with already created object we can

access its method.

DTEL DTEL

142

142

access its method.

Page 143: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-String Description

�String is a sequence of characters.

�Strings are constant; their values cannot be changed after they are created.

�For example:

String str = "abc"; is equivalent to:

char data[] = {'a', 'b', 'c'};

String str = new String(data);

�Constructor

The String class has several constructors defined.

DTEL DTEL

143

143

The String class has several constructors defined.

1. To create an empty string the default constructor is used. For example:

String s = new String();

It will create the instance of the string with no characters in it. If we

want to initialize the string with values we can use following constructor.

Page 144: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-String Description

2. String(char chars[])

For example:

char chars[] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’};

String s = new String(chars);

Direct initialization is also possible as,

String s = “Hello”;

3. We can specify a sub-range of a character array as an initializer

using the following constructor:

String(char chars[ ], int startIndex, int numChars)

DTEL DTEL

144

144

String(char chars[ ], int startIndex, int numChars)

Here, startIndex specifies the index at which the sub-range begins,

and numChars specifies the number of characters to use.

Here is an example:

char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

String s = new String(chars, 2, 3);

This initializes s with the characters “cde”.

Page 145: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- String Description

Following three constructors can also be used to create the strings.

4. String(String strObj)

5.String(byte asciiChars[])

6. String(byte asciiChars[], int startIndex, int numChars)

Here, ’strObj’ is another String object and ‘asciiChars’ is the array of

bytes to create the string from the given ASCII characters.

DTEL DTEL

145

145

Page 146: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-String

class Mystring2

{

public static void main(String args[])

{

String s="SDMP";

s=s+"Welcomes You";

System.out.println(s);

String s1="Institute code=";

s1=s1+127;

System.out.println(s1);

Example

DTEL DTEL

146

146

System.out.println(s1);

}

}

Page 147: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-String Class Method Description

S.N. Method Task Performed

1 char charAt(int index) Returns the character at the

specified index.

2 int

compareTo(String anotherString)

Compares two strings

3 String concat(String str) Concatenates the specified string to

the end of this string.

DTEL DTEL

147

147

the end of this string.

4 boolean equals(Object anObject) Compares this string to the specified

object.

5 boolean

equalsIgnoreCase(String anotherSt

ring)

Compares this String to another

String, ignoring case considerations.

Page 148: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- String Class Method Description

S.N. Method Task Performed

6 int indexOf(int ch) Returns the index within this

string of the first occurrence of

the specified character.

7 int lastIndexOf(int ch) Returns the index within this

string of the last occurrence of

the specified character.

DTEL DTEL

148

148

8 int length() Returns the length of this

string.

9 boolean startsWith(String prefix) Tests if this string starts with

the specified prefix.

10 boolean endsWith(String suffix) Tests if this string ends with the

specified suffix.

Page 149: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- String Class Method Description

S.N. Method Task Performed

11 String replace(char oldChar,

char newChar)

Returns a new string resulting from

replacing all occurrences of oldChar in

this string with newChar.

12 String substring(int beginIndex) Returns a new string that is a substring

of this string.

13 String toLowerCase() Converts all of the characters in this

String to lower case

DTEL DTEL

149

149

14 String toUpperCase() Converts all of the characters in this

String to upper case

15 String toString() This object (which is already a string!) is

itself returned.

16 String trim() Returns a copy of the string, with

leading and trailing whitespace omitted.

Page 150: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Example on String class methods Example

class String1

{

public static void main(String args[])

{

String s="Welcome";

System.out.println("Character at 0th

position " + s.charAt(0));

System.out.println("Index position of

character l is " + s.indexOf('l'));

System.out.println("Index position of

System.out.println("Length of string " +

s.length());

System.out.println("String in UPPERCASE "

+ s.toUpperCase());

System.out.println("String in lowercase " +

s.toLowerCase());

System.out.println("SubString staring from

index position 3 is " + s.substring(3));

System.out.println("Welcome is same as

Welcome " + s.equals("Welcome"));

DTEL DTEL

150

150

System.out.println("Index position of

character L is " + s.indexOf('L'));

System.out.println("Staring Index position

of character e is " + s.indexOf('e'));

System.out.println("Last Index position of

character e is " + s.lastIndexOf('e'));

Welcome " + s.equals("Welcome"));

System.out.println("WELCOME is same as

Welcome " + s.equals("WELCOME"));

System.out.println("WELCOME is same as

Welcome " +

s.equalsIgnoreCase("WELCOME"));

Page 151: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Example on String class methods Example

System.out.println("Whether the string

startswith Wel " + s.startsWith("Wel"));

System.out.println("Whether the string

startswith WEL " + s.startsWith("WEL"));

System.out.println("Whether the string

endsswith come " + s.endsWith("come"));

System.out.println("Whether the string

endsswith COME " + s.endsWith("COME"));

System.out.println("Relpace character e

with character o " + s.replace('e','o'));

DTEL DTEL

151

151

with character o " + s.replace('e','o'));

String s1=" Welcome to SDMP ";

System.out.println("Original String " + s1);

System.out.println("String after trim " +

s1.trim());

}

}

Page 152: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- StringBuffer Class Description

�A string buffer implements a mutable sequence of characters.

�A string buffer is like a String, but can be modified.

�At any point in time it contains some particular sequence of characters, but the

length and content of the sequence can be changed through certain method

calls

DTEL DTEL

152

152

Page 153: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- StringBuffer Class Description

�Constructor

�StringBuffer()

Constructs a string buffer with no characters in it and an initial capacity of 16

characters.

�StringBuffer(int length)

Constructs a string buffer with no characters in it and an initial capacity

specified by the length argument.

DTEL DTEL

153

153

�StringBuffer(String str)

Constructs a string buffer so that it represents the same sequence of

characters as the string argument; in other words, the initial contents of the string

buffer is a copy of the argument string.

Page 154: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Method of StringBuffer Description

S.N. Method Task Performed

1 StringBuffer append(StringBuffer

sb)

Appends the specified StringBuffer

to this StringBuffer.

2 StringBuffer insert(int offset,

String str)

Inserts the string into this string

buffer.

3 void setLength(int newLength) Sets the length of this String buffer.

4 void setCharAt(int index, char ch) The character at the specified index

of this string buffer is set to ch.

DTEL DTEL

154

154

of this string buffer is set to ch.

5 StringBuffer reverse() The character sequence contained

in this string buffer is replaced by the

reverse of the sequence.

Page 155: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Example on String Buffer Class Methods Example

class StringBuffer1

{

public static void main(String args[])

{

StringBuffer s1=new StringBuffer("Welcome");

System.out.println("Original String="+s1);

StringBuffer s2=s1.append(" to SDMP");

System.out.println("Appended String="+s2);

StringBuffer s3=s1.insert(3,"all");

System.out.println("Inserted String="+s3);

DTEL DTEL

155

155

System.out.println("Inserted String="+s3);

s1.setCharAt(1,'o');

System.out.println("Setting character in

between String="+s1);

StringBuffer s4=s1.reverse();

System.out.println("Reversed String="+s4);

}

}

W e l c o m e t o S D M P

Page 156: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Example

class Data

{

int a,b;

void setdata()

{

a=10;

b=20;

}

void setdata(int a,int b)

{

a=a;

class Mydata

{

public static void main(String arg[])

{

Data d1=new Data();

d1.setdata(100,200);

d1.showdata();

}

}

a=0

b=0

d1

DTEL DTEL

156

156

a=a;

b=b;

}

void showdata()

{

System.out.println("A="+a);

System.out.println("B="+b);

}

}

Page 157: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Explanation Description

�In the above example Data class contain three member functions to

initialize the values of data members and to show the values of data

members.

�setdata(int a,int b); containing two arguments i.e. a & b, it is used to

initialize the values of data member.

�In this example name of local variables present in setdata() member

function is exactly same as that of member variables of class.

�Therefore variables inside setdata() member function always access the

values of local variables & unable to access the member variables of class.

DTEL DTEL

157

157

values of local variables & unable to access the member variables of class.

�Hence, setdata(), member function is not able to initialize the values of

data members of class.

�To solve the above problem we have to use this keyword present in java

language.

�this is keyword which is used to represent the invoking object also it is

used to access members of class as shown in next example.

Page 158: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Example on this keyword Example

class Data

{

int a,b;

void setdata()

{

a=10;

b=20;

}

void setdata(int a,int b)

{

this.a=a;

class Mydata

{

public static void main(String arg[])

{

Data d1=new Data();

d1.setdata(100,200);

d1.showdata();

}

}

DTEL DTEL

158

158

this.a=a;

this.b=b;

}

void showdata()

{

System.out.println("A="+a);

System.out.println("B="+b);

}

}

Page 159: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- this keyword Description

�this is keyword present in java language .

�We can use this keyword within the block of constructor or method

present in class.

�this keyword represents the invoking object during runtime.

�By using this keyword we can access member variables & method of

invoking object.

DTEL DTEL

159

159

Page 160: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Method overloading Description & Example

�In Java it is possible to define two or

more methods within the same class that

are having the same name, but their

parameter declarations are different.

�In this case, the methods are said to be

overloaded, and the process is referred to

as method overloading.

�Method overloading is one of the ways of

Java implementation of polymorphism.

Example on method overloading

int area(int len, int wid) //area of rectangle

{

return(len * wid);

} }

class Shape {

public static void main(String args[]) {

Area s = new Area();

System.out.println("Area of square :

"+s.area(5));

System.out.println("Area of circle :

"+s.area(10.2));

DTEL DTEL

160

160

Example on method overloading

class Area

{

int area(int side) //area of a square

{

return(side * side);

}

double area(double radius) //area of circle

{

return(3.14 * radius * radius);

}

"+s.area(10.2));

System.out.println("Area of rect:

"+s.area(10,2));

} }

OUTPUT

Page 161: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Final Keyword Example

Example

class example1

{

public static void main(String args[])

{

final int a=10;

System.out.println(a);

int a=a*a;

System.out.println(b);

DTEL DTEL

161

161

System.out.println(b);

}

}

OUTPUT

Page 162: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Final Keyword

�Final is keyword.

�Whenever any variable is declared as

final than that variable is known as final

variable.

�Value of final variable is fixed

throughout the block of program.

�It is necessary to assign value to final

variable during declaration.

�But after declaration of final variable

we can’t change the value of final variable

Description & Example

Example

class example1

{

public static void main(String args[])

{

final int a=10;

System.out.println(a);

int b=a*a;

System.out.println(b);

}

DTEL DTEL

162

162

we can’t change the value of final variable

throughout the program (we can say that

final variable contain constant values).

}

}

OUTPUT

Page 163: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Static Keyword Example

class example1

{

int a=10;

public static void main(String args[])

{

System.out.println(a*a);

}

}

class example2

{

static int a=10;

public static void main(String args[])

{

System.out.println(a*a);

}

}

DTEL DTEL

163

163

�Since main() function is declared as

static,therefore this function can access

static data members and member

function of class.

�Default initial value of static data

member is always zero.

Page 164: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Example

class example3

{

static int a;

public static void main(String args[])

{

System.out.println(a);

a=20;

System.out.println(a);

}

}

LECTURE 3:- Static Keyword

class example4

{

static void show()

{

System.out.println("Im in static method show");

}

public static void main(String args[])

{

System.out.println("Im in main");

show();

DTEL DTEL

164

164

} show();

}

}

Page 165: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Static Block Example

class example1

{

static

{

System.out.println("Im im static block");

}

public static void main(String args[])

{

System.out.println("Im in main");

}

DTEL DTEL

165

165

}

}

Page 166: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Inheritance Description

�The mechanism of deriving a new class from existing one is called as inheritance.

�The old class or existing class is known as super class and new class is known as

subclass.

�We can call super class as base class or parent class and subclass as derived class or

child class.

�The subclass derives all of the instance variables and methods defined by super class

and add its own unique elements.

�So the elements defined in super class are reused in the subclass.

Types of Inheritance

DTEL DTEL

166

166

Types of Inheritance

Class A

Class B

Class A

Class B Class c Class D

Single Inheritance Hierarchical Inheritance

Page 167: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Inheritance Description

Class A

Class B

Class C

Class A

Class B

Class D

Class CClass B Class C

Class A

Class D

DTEL DTEL

167

167

Java does not directly implement the multiple inheritance.

This is implemented using the concept of interface.

Multilevel Inheritance Multiple Inheritance Hybrid Inheritance

Page 168: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Creating the inheritance Description & Example

The class can derived from another class by

following the syntax:

class subclassname extends superclassname

{

//Body of the class;

}

Example on Single Inheritance

class A

{

int a;

void seta()

class B extends A

{

int b;

void setb()

{

b=20;

}

void showb()

{

System.out.println("B="+b);

}

DTEL DTEL

168

168

void seta()

{

a=10;

}

void showa()

{

System.out.println("A="+a);

}

}

}

}

class Inherit2 {

public static void main(String args[]) {

B b1=new B();

b1.seta();

b1.setb();

b1.showa();

b1.showb();

} }

Page 169: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Method Overriding Description & Example

class A

{

void show()

{

System.out.println("I am in A");

}

}

class B extends A

{

void show()

{

�In this example class B is inherited from class A.

�Therefore class A is called as super class and

class B is called as sub class.

DTEL DTEL

169

169

{

System.out.println("I am in B");

}

}

class Inherit8 {

public static void main(String args[]) {

B b1=new B();

b1.show();

} }

class B is called as sub class.

�Since prototype of show() function present in

sub class is exactly same as that of prototype of

show() function present in super class, therefore

show function of class B overrides on show()

function of class A.

�Hence b1 object of class B can access show()

function of sub class only i.e. show() function of

super class is hidden for the object of sub-class.

�This concept is known as method overriding.

Page 170: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Method Overriding

In method overriding, object of sub class

can access method (overridden method) of

sub class only and enable to access

methods of super class i.e. Method of super

class is hidden for the object of sub class.

Example

class A

{

public void show()

{

Description & Example

class Inherit9

{

public static void main(String args[])

{

B b1=new B();

b1.show();

} }

No output

�In the above example class A is

called as super class and class B is

DTEL DTEL

170

170

{

System.out.println("I am in A");

} }

class B extends A {

public void show()

{

show();

System.out.println("I am in B");

} }

called as super class and class B is

called as sub class.

�Both the classes contain show()

function,therefore object of

subclass B can access show()

function of sub class only.

�In class B we can access show()

function of class A by using super

keyword.

Page 171: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Super Keyword Description & Example

�We cannot access the member function

of class without using super keyword

because both the classes contain show()

function having different logical task.

�Super is a keyword which is always used

in sub class to represent the super class.

�Using super keyword we can access

member variables, methods or function of

super class as shown in example

�Example of Super Keyword

class B extends A

{

public void show()

{

super.show();

System.out.println("I am in B");

} }

class Inherit10 {

public static void main(String args[])

{

DTEL DTEL

171

171

�Example of Super Keyword

class A

{

public void show()

{

System.out.println("I am in A");

}

}

{

B b1=new B();

b1.show();

} }

Page 172: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Variable overriding Example

class A

{

int a;

void showa()

{

System.out.println("A="+a);

}

}

class B extends A

{

int a;

class Inherit11

{

public static void main(String args[])

{

B b1=new B();

b1.setb(10,20);

b1.showa();

b1.showb();

}

}

DTEL DTEL

172

172

int a;

void setb(int n1,int n2)

{

a=n1;

a=n2;

}

void showb()

{

System.out.println("B="+a);

} }

Page 173: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Variable overriding Description

�In the above example class B extends class A, therefore class A is known as

super class & class B is known as sub class.

�Member variable of super class is exactly same as that of sub class,

therefore object of sub class cannot access member variable of super class in

sub class.

�Therefore during the execution of function both the variables i.e. ‘a’ will

represent the member variable of sub class only and enable to access

member variable of super class.

�To solve the above problem we have to use super keyword.

�Super keyword represent super class & it is used to access member

DTEL DTEL

173

173

�Super keyword represent super class & it is used to access member

variable of super class as shown in example.

Page 174: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Variable overriding Example

class A

{

int a;

void showa()

{

System.out.println("A="+a);

}

}

class B extends A

{

int a;

class Inherit12

{

public static void main(String args[])

{

B b1=new B();

b1.setb(10,20);

b1.showa();

b1.showb();

}

}

DTEL DTEL

174

174

int a;

void setb(int n1,int n2)

{

super.a=n1;

a=n2;

}

void showb()

{

System.out.println("B="+a);

} }

Page 175: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Constructor Overriding Example

class A

{

A()

{

System.out.println("I am in A");

}

}

class B extends A

{

B()

{

DTEL DTEL

175

175

{

System.out.println("I am in B");

}

}

class Inherit13

{

public static void main(String args[])

{

B b1=new B();

} }

Page 176: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Constructor Overriding Description

�In the above example class A is super class and class B is a sub class.

�Both the classes contain constructor of type default constructor.

�Whenever constructor is invoked (execute) then all the default constructors of

super classes will execute first, then corresponding constructor of sub class will

execute.

�This concept is known as constructor overriding.

�If super class & sub class contain constructor then during the execution of

constructor of object of subclass, the execution control will execute all the

default constructor of super classes and after completion of execution of default

constructor ,the execution control will execute the corresponding constructor of

DTEL DTEL

176

176

constructor ,the execution control will execute the corresponding constructor of

its own class.

Page 177: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:- Multilevel Inheritance

class A

{

A()

{

System.out.println("I am in A");

}

}

class B extends A

{

B()

{

class Inherit15

{

public static void main(String args[])

{

C c1=new C();

}

}

Example

class A

class B

class C

DTEL DTEL

177

177

{

System.out.println("I am in B");

}

}

class C extends B

{

C()

{

System.out.println("I am in C");

} }

Page 178: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Super Constructor

super(100);

b=20;

}

void showb()

{

System.out.println("B="+b);

} }

class Inherit16 {

public static void main(String args[]) {

B b1=new B();

b1.showa();

class A

{

int a;

A()

{

a=10;

}

A(int n1)

{

a=n1;

}

Example

DTEL DTEL

178

178

b1.showa();

b1.showb();

} }

}

void showa()

{

System.out.println("A="+a);

} }

class B extends A

{

int b;

B()

{

Page 179: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Super Constructor Description

�In the above example class B is derived from class A therefore class A is called

super class and class B is called as sub class.

�Constructors present in super class are called as super class constructors &

constructors present in sub class are called as sub class constructors.

�We can access super constructor in constructor of sub class .

�Before calling any super constructor it is necessary to initialize data members

of super class and then we can initialize data members of sub class i.e. super

constructor must be called first and then we can initialize other variables.

�Note:- calling statement of super constructor must be present at the

DTEL DTEL

179

179

�Note:- calling statement of super constructor must be present at the

initialization of block of constructor.

Page 180: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Final Class Description & Example

final class A

{

void showa()

{

System.out.println("I am in A");

} }

class B extends A

{

void showb()

{

System.out.println("I am in B");

�In the example class A is declared as

final therefore it is called as final class.

�Hence, class B cannot extend class A.

DTEL DTEL

180

180

System.out.println("I am in B");

} }

class Inherit17

{

public static void main(String args[])

{

B b1=new B();

b1.showa();

b1.showb();

} }

�Hence, class B cannot extend class A.

�Final is a keyword of java language.

�Whenever any class is declared as final

then that class is known as final class.

�No other class can extend final class i.e.

object of Final class is available but we

can’t extend the final class.

Page 181: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Final Class Description & Example

We can access member variables & methods of

final class by using its objects.

Example on Final Class

final class A

{

void showa()

{

System.out.println("I am in A");

}

DTEL DTEL

181

181

}

}

class Inherit18

{

public static void main(String args[])

{

A a1=new A();

a1.showa();

}

}

Page 182: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Final Method Description & Example

�Whenever any method of class is declared as

final than that method is known as final

method.

�We can extend the class containing final

method but we can’t override the final

method.

�Object of super class or sub class can access

all the member variable & methods of its

corresponding class.

Example

class A

class B extends A

{

void show()

{

System.out.println("I am in B");

}

}

class Inherit18 {

public static void main(String args[]) {

B b1=new B();

b1.show();

DTEL DTEL

182

182

class A

{

final void show()

{

System.out.println("I am in A");

}

}

b1.show();

} }

Page 183: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Final Method Example

class A

{

final void show()

{

System.out.println("I am in A");

}

}

class B extends A

{

void show1()

class Inherit18

{

public static void main(String

args[])

{

B b1=new B();

b1.show();

b1.show1();

}

}

DTEL DTEL

183

183

void show1()

{

System.out.println("I am in B");

}

}

}

Page 184: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Abstract Class Description & Example

�Abstract is a keyword present in java

language.

�When any class is declared as abstract then

main program or any other class cannot create

object of abstract class i.e. using object of

abstract class we cannot access members of

abstract class.

�We can inherit or extend any abstract class

in a sub class and by using object of sub class

we can access all the properties of abstract

class and its subclass.

class Inherit19 {

public static void main(String args[]) {

A a1=new A();

a1.showa();

} }

DTEL DTEL

184

184

class and its subclass.

�Example

abstract class A

{

void showa()

{

System.out.println("I am in A");

}

}

In the above example ,class A is an

abstract class therefore we can’t

create object of class A but we can

access data members & member

functions of class A by using its sub

class as shown in the next example.

Page 185: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Abstract Class Example

abstract class A

{

void showa()

{

System.out.println("I am in A");

}

}

class B extends A

class Inherit20

{

public static void main(String

args[])

{

B b1=new B();

b1.showa();

b1.showb();

DTEL DTEL

185

185

class B extends A

{

void showb()

{

System.out.println("I am in B");

}

}

b1.showb();

}

}

Page 186: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Abstract function Example

abstract class A

{

abstract void show();

void showa()

{

System.out.println("I am in A");

}

}

class B extends A

{

public void show()

class Inherit21

{

public static void main(String args[])

{

B b1=new B();

b1.show();

b1.showa();

b1.showb();

}

}

DTEL DTEL

186

186

public void show()

{

System.out.println("I am in show");

}

void showb()

{

System.out.println("I am in B");

}

}

Page 187: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Abstract function Description

�Complete declaration of function along with argument type &return type is

called as prototype.

�When any function is declared as abstract then such function is known as

abstract function.

�Abstract function is always present in abstract class.

�Sub class of any abstract class must have to be define body of abstract

function(called function) already declared in super class.

�Body of abstract method should be declared in public section i.e. explicit access

specifier of abstract method must be public..

DTEL DTEL

187

187

Page 188: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Array Description

�An array is contiguous or related data items that share the common name.

�This means that all elements in the array have the same data type.

�A position in the array is indicated by a non-negative integer value called as

index.

�An element at the given position is accessed by using this index.

�The size of array is fixed and can not increase to accommodate more

elements.

DTEL DTEL

188

188

Page 189: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Single Dimension Array Description & Example

Syntax:

datatype variable[]=new datatype[dimension];

OR

datatype []variable=new datatype[dimension];

Example

class Array1

{

public static void main(String args[])

{

int a[]=new int[5];

4 bytes->

Total memory=4*5=20 bytes

0 a[0]

10 a[1]

20 a[2]

30 a[3]

40 a[4]

DTEL DTEL

189

189

int a[]=new int[5];

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

{

a[i]=i*10;

}

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

{

System.out.println(a[i]);

}

}

}

Page 190: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Single Dimension Array Example

Initialization of 1 Dimension Array

class command1

{

public static void main(String args[])

{

String s[]={"ABC","XYZ","PQR","LMN"};

for(int i=0;i<=s.length-1;i++)

System.out.println(s[i]);

}

}

4 bytes->

Total memory=4*4=16 bytes

ABC a[0]

XYZ a[1]

PQR a[2]

LMN a[3]

DTEL DTEL

190

190

Page 191: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Two Dimensional Array Description & Example

Syntax

datatype variable[][]=new datatype[row][column];

OR

datatype [][]variable=new datatype[row][column];

Example

class Array2D1

{

public static void main(String args[])

{

int a[][]=new int[3][4];

int i,j;

for(i=0;i<=2;i++)

{

for(j=0;j<=3;j++)

{

System.out.print(a[i][j]+" ");

}

System.out.println();

}

}

}

DTEL DTEL

191

191

int i,j;

for(i=0;i<=2;i++)

{

for(j=0;j<=3;j++)

a[i][j]=i+j;

}

Page 192: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Two Dimensional Array Description & Example

Execution

i=0 j=0 a[0][0]=0+0=0

i=0 j=1 a[0][1]=0+1=1

i=0 j=2 a[0][2]=0+2=2

i=0 j=3 a[0][3]=0+3=3

i=1 j=0 a[1][0]=1+0=1

i=1 j=1 a[1][1]=1+1=2

DTEL DTEL

192

192

i=1 j=1 a[1][1]=1+1=2

i=1 j=2 a[1][2]=1+2=3

i=1 j=3 a[1][3]=1+3=4

i=2 j=0 a[2][0]=2+0=2

i=2 j=1 a[2][1]=2+1=3

i=2 j=2 a[2][2]=2+2=4

i=2 j=3 a[2][3]=2+3=5

Page 193: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Two Dimensional Array Example

Example on Initialization of 2 Dimension Array

class Array2D3

{

public static void main(String args[])

{

int a[][]={

{10,5,7,2},

{2,1,3,5},

{0,5,10,20}

};

int i,j;

DTEL DTEL

193

193

int i,j;

for(i=0;i<=2;i++)

{

for(j=0;j<=3;j++)

{

System.out.print(a[i][j]+" ");

}

System.out.println();

}

} }

Page 194: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Vector Description

�The package java.util contains a library of Java’s utility classes.

� One of them is Vector class.

� It implements a dynamic array which can hold the array of any type and any number.

�Capacity of the Vector can be increased automatically.

�It is used to add dissimilar type of element/object.

�Creation of Vector

Vector class defines three different constructors:

�Vector()

The first form creates a default vector, which has an initial size of 10.

DTEL DTEL

194

194

�Vector(int size)

The second form creates a vector whose initial capacity is specified by ‘size’

�Vector(int size, int incr)

The third form creates a vector whose initial capacity is specified by ‘size’ and whose

increment is specified by ‘incr’. The increment specifies the number of elements to

allocate each time when new elements are added in the vector.

Page 195: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Vector Description

S.N. Method Task Performed

1 void addElement(Object obj) Adds the specified component to the

end of this vector, increasing its size

by one

2 int capacity() Returns the current capacity of this

vector.

DTEL DTEL

195

195

3 int size() Returns the number of components

in this vector.

4 boolean contains(Object elem) Tests if the specified object is a

component in this vector.

5 Object elementAt(int index) Returns the component at the

specified index.

Page 196: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Vector Description

S.N. Method Task Performed

6 Enumeration elements() Returns an enumeration of the

components of this vector.

7 Object firstElement() Returns the first component

(the item at index 0) of this

vector.

8 Object lastElement() Returns the last component of

the vector.

DTEL DTEL

196

196

9 int indexOf(Object elem) Searches for the first

occurrence of the given

argument, testing for equality

using the equals method.

10 void insertElementAt(Object obj,

int index)

Inserts the specified object as a

component in this vector at the

specified index.

Page 197: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Vector Description

S.N. Method Task Performed

11 Object remove(int index) Removes the element at the specified

position in this Vector.

12 void

removeElementAt(int index)

Deletes the component at the specified

index.

13 Object set(int index,

Object element)

Replaces the element at the specified

position in this Vector with the specified

DTEL DTEL

197

197

Object element) position in this Vector with the specified

element.

14 void clear() Removes all of the elements from this

Vector.

Page 198: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Vector

Example on how to add element to vector & how to retrieve element from vector using

function

import java.util.*;

class Example1

{

public static void main(String args[])

{

Vector v=new Vector();

v.addElement(new Integer(10));

v.addElement(new Integer(20));

Example

DTEL DTEL

198

198

v.addElement(new Integer(20));

v.addElement(new Double(1.2));

v.addElement(new Double(5.2));

System.out.println("First Element="+(Integer)v.firstElement());

System.out.println(“Last Element="+(Double)v.lastElement());

System.out.println("Element at 2nd position="+(Double)v.elementAt(2));

}

}

Page 199: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Vector Example

Example on size() & capacity()

import java.util.*;

class Example1

{

public static void main(String args[])

{

Vector v=new Vector();

v.addElement(new Integer(10));

v.addElement(new Integer(20));

v.addElement(new Double(1.2));

DTEL DTEL

199

199

v.addElement(new Double(1.2));

v.addElement(new Double(5.2));

System.out.println("Size of vector="+v.size());

System.out.println("Capacity of vector="+v.capacity());

}

}

Page 200: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Displaying Vector Example-Method1

import java.util.*;

import java.util.Enumeration;

class Example2

{

public static void main(String args[ ])

{

Vector v=new Vector();

v.addElement(new Integer(29));

v.addElement(new Integer(54));

v.addElement(new Integer(78));

DTEL DTEL

200

200

v.addElement(new Integer(78));

v.addElement(new Integer(46));

v.addElement(new Integer(50));

int size=v.size();

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

System.out.println(v.elementAt(i));

}

}

Page 201: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Enumeration Description

�An object that implements the Enumeration interface generates a series of

elements, one at a time.

�Successive calls to the nextElement method return successive elements of the

series.

Method

�boolean hasMoreElements()

Tests if this enumeration contains more elements.

�Object nextElement()

Returns the next element of this enumeration if this enumeration object

DTEL DTEL

201

201

Returns the next element of this enumeration if this enumeration object

has at least one more element to provide.

Page 202: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Displaying Vector Example-Method2

import java.util.*;

import java.util.Enumeration;

class Example2

{

public static void main(String args[ ])

{

Vector v=new Vector();

v.addElement(new Integer(29));

v.addElement(new Integer(54));

v.addElement(new Integer(78));

v.addElement(new Integer(46));

DTEL DTEL

202

202

v.addElement(new Integer(46));

v.addElement(new Integer(50));

Enumeration vEnum=v.elements();

System.out.println("Elements in vector");

while(vEnum.hasMoreElements())

System.out.print(vEnum.nextElement()+" ");

System.out.println();

}

}

Page 203: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Displaying Vector Example

import java.util.*;

import java.util.Enumeration;

class Example2

{

public static void main(String args[ ])

{

Vector v=new Vector();

v.addElement(new Integer(29));

v.addElement(new Integer(54));

v.addElement(new String("ABC"));

v.addElement(new String("PQR"));

System.out.println(v.elementAt(i));

v.removeElementAt(1);

System.out.println("Elements in vector

after removal");

for(int i=0;i<size-1;i++)

System.out.println(v.elementAt(i));

}

}

DTEL DTEL

203

203

v.addElement(new String("PQR"));

v.addElement(new Float(4.6));

v.addElement(new Float(5.0));

int size=v.size();

System.out.println("Elements in vector");

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

Page 204: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Array Vs Vector Description

Both Array and Vector in Java are similar. Both are used for storing the data. But

there are some basic difference between Array & Vector .

1. Array is the static memory allocation , while vector is the dynamic memory

allocation.

2. Array allocates the memory for the fixed size ,in array there is wastage of

memory, while Vector allocates the memory dynamically means according to the

requirement no wastage of memory .

DTEL DTEL

204

204

requirement no wastage of memory .

3. By using Vector we can add, remove, & find the size of elements dynamically

,while it is not possible in Array.

Page 205: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Wrapper classes Description

Wrapper classes are used to convert string into inbuilt data types and vice versa.

Table shows the wrapper classes of respective data types.

Datatype Wrapper class

byte Byte

short Short

int Int

long Long

DTEL DTEL

205

205

long Long

float Float

double Double

boolean Boolean

char Char

Page 206: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Number Class Description

�The abstract class ‘Number’ is a super class that is implemented by the classes

that wrap the numeric types: byte, short, int, long, float, and double.

�‘Number’ has abstract methods that return the value of the object in each of

the different number formats.

�These methods are shown here:

�byte byteValue()

�short shortValue()

�int intValue()

�long longValue()

DTEL DTEL

206

206

�long longValue()

�float floatValue()

�double doubleValue()

Number has six concrete subclasses that hold explicit values of each numeric

type: Double, Float, Byte, Short, Integer, and Long..

Page 207: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Description

Byte, Short, Integer and Long

�The Byte, Short, Integer, and Long are wrapper classes for byte, short, int, and

long integer types, respectively.

�Their constructors are shown below:

�Byte(byte num)

�Byte(String str)

�Short(short num)

�Short(String str)

�Integer(int num)

�Integer(String str)

DTEL DTEL

207

207

�Integer(String str)

�Long(long num)

�Long(String str)

Page 208: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Description

Float & Double

�Float and Double are wrapper classes for floating

point values of type float and double, respectively.

�The constructors for class Float are shown Below:

� Float(double num);

� Float(float num);

� Float(String str);

�The constructors for Double are shown below:

� Double(double num)

� Double(String str)

DTEL DTEL

208

208

� Double(String str)

Page 209: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Description

Character

�Character is the wrapper class of data type char. It is having only

one constructor:

� Character(char ch)

Here, ‘ch’ is the character value for which the

wrapper class is to be created

DTEL DTEL

209

209

Page 210: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Description

Boolean

�It is a wrapper class for boolean data type which is mostly useful when we

pass boolean value to a method by reference.

�It contains the constants TRUE and FALSE, which define true and false

Boolean objects.

Boolean defines following constructors:

�Boolean(boolean boolValue)

�Boolean(String boolString)

�In the first version, ‘boolValue’ must be either true or false.

�In the second version, if ‘boolString’ contains the string “true” (in uppercase

DTEL DTEL

210

210

�In the second version, if ‘boolString’ contains the string “true” (in uppercase

or lowercase), then the new Boolean object will be true. Otherwise, it will be

false.

Page 211: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Description

Converting from String to---

xxxValue() method

When you need to convert the value of a wrapped numeric to a primitive, use

one of the many xxxValue() methods. All of the methods in this family are no-arg

methods. Each of the six numeric wrapper classes has six methods, so that any

numeric wrapper can be converted to any primitive numeric type.

Code:

�Integer i2 = new Integer(42); // make a new wrapper object

�byte b = i2.byteValue(); // convert i2's value to a byte primitive

DTEL DTEL

211

211

�byte b = i2.byteValue(); // convert i2's value to a byte primitive

�short s = i2.shortValue(); // another of Integer's xxxValue methods

�double d = i2.doubleValue(); // yet another of Integer's xxxValue methods

Page 212: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Example

Example on Integer Wrapper class & use of intValue() function

class Convert1

{

public static void main(String args[])

{

try

{

String S="100";

Integer I=new Integer(S);

int n=I.intValue();

DTEL DTEL

212

212

int n=I.intValue();

System.out.println(n);

}

catch(NumberFormatException e)

{

System.out.println("Fault="+e);

}

}

}

Page 213: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Description

Parsing function(String to --)

Xxx parsexxx(String) method

If you do not need to store a value in a wrapper but just want to perform a quick

operation on it, such as converting the type, you can do it by using an

appropriate static method of the appropriate wrapper class. For example, all the

wrapper classes except Character offer a static method that has the following

signature:

static <type> parse<Type>(String s)

DTEL DTEL

213

213

static <type> parse<Type>(String s)

The <type> may be any of the primitive types except char (byte, short, int, long,

float, double, or boolean), and the <Type> is the same as <type> with the first

letter uppercased;

Page 214: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Description

Parsing function(String to --)

for example:

static int parseInt (String s)

Each of these methods parses the string passed in as a parameter and returns

the corresponding primitive type.

For example, consider the following code:

DTEL DTEL

214

214

Code:

String s = "123"; int i = Integer.parseInt(s);

The second line will assign an int value of 123 to the int variable i.

Page 215: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- Wrapper classes Description

Example on Integer Wrapper class & use of parseInt() function

class Convert2

{

public static void main(String args[])

{

try

{

String S="100";

int n=Integer.parseInt(S);

System.out.println(n);

DTEL DTEL

215

215

System.out.println(n);

}

catch(NumberFormatException e)

{

System.out.println("Fault="+e);

}

}

}

Page 216: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- BufferedReader Description

public class BufferedReader extends Reader

�It is defined in java.io package.

�Read text from a character-input stream, buffering characters so as to provide

for the efficient reading of characters, arrays, and lines.

�The buffer size may be specified, or the default size may be used.

�The default is large enough for most purposes.

�Constructor

�BufferedReader(Reader in)

Create a buffering character-input stream that uses a default-sized input

buffer.

DTEL DTEL

216

216

buffer.

Page 217: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:- java.io.InputStreamReader Description

java.lang.Object

java.io.Reader

java.io.InputStreamReader

java.io ->Class InputStreamReader

�Constructor

public InputStreamReader(InputStream in)

Create an InputStreamReader that uses the default charset.

Parameters:in - An InputStream

DTEL DTEL

217

217

Parameters:in - An InputStream

Page 218: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-System

java.lang.Object

java.lang.System

java.lang ->Class System

static InputStream in

The "standard" input stream.

Method

�int read()

Read a single character.

� String readLine()

Read a line of text.

Description

DTEL DTEL

218

218

Read a line of text.

Throws: IOException - If an I/O error occurs

Page 219: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Accepting Input From User

Example to accept number & print its factorial

import java.io.*;

class Fact

{

public static void main(String args[])throws Exception

{

BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));

System.out.println("Enter a number=“);

int num=Integer.parseInt(br.readLine());

Example

DTEL DTEL

219

219

int num=Integer.parseInt(br.readLine());

int fact = 1;

for(int i = num ;i>0; i--)

fact = fact * i;

System.out.println("Factorial of number= "+ fact);

}

}

Page 220: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Accepting Input From User Example

DTEL DTEL

220

220

Page 221: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Command Line Argument Example

Write a program to accept two numbers as command line arguments and print the addition of

those numbers. S13[4M]

import java.lang.String;class add{public static void main(String args[]){int a=Integer.parseInt(args[0]);int b=Integer.parseInt(args[1]);int c=a+b;

DTEL DTEL

221

221

int c=a+b;System.out.println("Addition of two numbers="+c);}}

Page 222: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-3 Interface and Package

Topic 1: 1

Topic 2: 2

Interface

Package

DTEL DTEL 22

2

Page 223: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-3 SPECIFIC OBJECTIVE / COURSE OUTCOME

1

The student will be able to:

To create and use interface and packages.

They will also learn the package naming, conventions

DTEL DTEL 22

3

2They will also learn the package naming, conventions

and about the static import.

Page 224: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Interface Description

�An interface is basically a kind of the class. Like classes, interfaces contain methods

and variables but with the major difference.

�The difference is that interfaces define only abstract methods and final variable

fields.

�That is, interfaces do not specify any code to implement these methods and the

data fields contain only constants.

�The syntax of defining an interface is very similar to defining a class.

The general form of defining an interface is:

access interface InterfaceName

{

DTEL DTEL

224

224

{

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

.......

data-type final-varname1 = value;

data-type final-varname2 = value;

.......

return-type method-nameN(parameter-list);

data-type final-varnameN = value;

}

Page 225: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Implementing interfaces Description

�Once an interface has been defined, one or more classes can implement that

interface.

�To implement an interface, we have to include the implements clause in a class

definition, and then create the methods defined by the interface.

�The general form of a class that includes the implements clause looks like this:

access class classname [extends superclass]

[implements interface [,interface...]]

{

// class-body

}

DTEL DTEL

225

225

}

�Here, access is either public or not used.

�If a class implements more than one interface, the interfaces are separated with

a comma.

� If a class implements two interfaces that declare the same method, then the

same method will be used by clients of either interface.

�The methods that implement an interface must be declared public.

�Also, the type declaration of the implementing method must match exactly the

type declaration specified in the interface definition.

Page 226: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Interface Example

interface circle

{

double pi=3.14;

double area();

}

class Area implements circle

{

double radius=2;

public double area()

{

class aoc

{

public static void main(String args[])

{

Area a=new Area();

System.out.println(“Area of circle=

“+a.area());

}

}

DTEL DTEL

226

226

{

return(pi*radius*radius);

}

}

Page 227: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Interface Example

class A

int a;

int b;

interface B

void set();

void show();

Implement the following inheritance

DTEL DTEL

227

227

class C

Note:Java does not directly implement the multiple inheritance.

This is implemented using the concept of interface.

Page 228: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Interface Example

class A

{

int a,b;

}

interface B

{

void set();

void show();

}

class C extends A implements B

public void show()

{

System.out.println("A="+a);

System.out.println("B="+b);

}

}

class myinterface4 {

public static void main(String args[]) {

C c1=new C();

c1.set();

DTEL DTEL

228

228

class C extends A implements B

{

public void set()

{

a=10;

b=20;

}

c1.set();

c1.show();

} }

Page 229: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Interface Example

interface A

void show1();

void show2();

interface B

void show3();

Implement the following inheritanceinterface A

{

void show1();

void show2();

}

interface B extends A

{

void show3();

}

class C implements B

DTEL DTEL

229

229

void show3();

class C

class C implements B

{

public void show1()

{

System.out.println("I am in show 1");

}

public void show2()

{

System.out.println("I am in show 2");

}

Page 230: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:- Interface Example

public void show3()

{

System.out.println("I am in show 3");

}

}

class myinterface5

{

public static void main(String args[])

{

DTEL DTEL

230

230

{

C c1=new C();

c1.show1();

c1.show2();

c1.show3();

}

}

Page 231: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Interface

Connectivity of class/interface with class/interface

Description

class A interface A

DTEL DTEL

231

231

class B

1. class B extends A

interface B

2. . interface B extends A

Page 232: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Interface

Connectivity of class/interface with class/interface

Description

interface A

interface A interface B

DTEL DTEL

232

232

class B

3. class B implements A

class C

4. class C implements A,B

Page 233: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Interface

Connectivity of class/interface with class/interface

Description

class A interface B

DTEL DTEL

233

233

class C

5. class C extends A implements B

Page 234: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Interface

Connectivity of class/interface with class/interface

Description

class A interface B interface C

DTEL DTEL

234

234

class D

6. class D extends A implements B,C

Page 235: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Interface

Difference between Class & Interface

Description

S.N. Class Interface

1 Class is declared with the keyword

class.

Interface is declared with the keyword

interface.

2 Class is a collection of data

members & member functions.

Interface is a collection of constant data,

also it is collection of function

declaration(prototype of function).

DTEL DTEL

235

235

declaration(prototype of function).

3 Class variables should not be

compulsorily static or final.

Data members present in interface block

are called static or final.

4 Class contains declaration and

definition of function.

Interface contains declaration of function.

5 Class can be extended Interface can be implemented

Page 236: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Interface

Difference between Class & Interface

Description

S.N. Class Interface

6 There is no such restriction to

explicitly declare the body of the

function as public.

Body of function present in implemented

class must have explicit public access

specifier.

7 Object of a class can be created. Object of an interface cannot created.

8 Syntax:-

class <class_name>

{

Syntax:-

interface <interface_name>

{

DTEL DTEL

236

236

{

type variable1;

|

type variablen;

type function1()

{

}

|

type functionn()

{

}

}

{

final variables & abstract method(method

declaration);

}

Page 237: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Interface Description

Difference between Class & Interface

S.N. Class Interface

9 Classes are not used to implement

multiple inheritance.

The interfaces are used in java to

implement the concept of multiple

inheritances.

10 Class contains executable code. Interface contains no executable code.

11 Memory is allocated for the We are not allocating the memory for the

DTEL DTEL

237

237

11 Memory is allocated for the

classes.

We are not allocating the memory for the

interfaces.

12 Class contains constructors. An interface does not contain any

constructor.

13 A class can extend only one

class(no multiple inheritance),but

it can implement many interfaces.

Interfaces can extend one or more other

interfaces. Interfaces cannot extend a

class, or implement a class or interface.

Page 238: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Package Description

�Package is a folder/directory/disk block containing all the files required for the project.

�Package is consisting of two different concepts i.e. same package and different package.

DTEL DTEL

238

238

Page 239: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Java API packages Description

�The classes that are included in these

packages are:

�java.lang – Language support classes such

as System, Thread, Exception etc.

�java.util – Utility classes such as Vector,

Arrays, LinkedList, Stack etc.

�java.io – Input output support classes such

java

DTEL DTEL

239

239

�java.io – Input output support classes such

as BufferedReader, InputStream

�java.awt – Classes using GUI such as

Window, Frame, Panel etc.

�java.applet – Classes for creating and

implementing applets.

lang io util awt applet

Figure: Frequently used java packages

Page 240: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Package Hierarchy Description

java

awt

color

The top package

The sub package

Classes of

package ‘awt’

DTEL DTEL

240

240

ColorSpace

package ‘awt’

Classes of

package ‘color’

Java Class Hierarchy Representation

Page 241: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Same Package Description

�If all the required files and file containing main program are present in

same directory or same folder then such concept is known as concept of

same package.

�If all the files are present in same package then java compiler will

automatically link all the files.

DTEL DTEL

241

241

Page 242: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Same Package Example

DTEL DTEL

242

242

Page 243: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Same Package Description

Saving the file

DTEL DTEL

243

243

Page 244: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Same Package Example

DTEL DTEL

244

244

Page 245: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Same Package Description

Saving the file

DTEL DTEL

245

245

Page 246: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Same Package Output

DTEL DTEL

246

246

Page 247: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Creating the package Description

�This is the general form of the package statement:

�package pkg;

�Here, ‘pkg’ is the name of the package.

�package packagename;

public class classname

{

//body of class

}

�Example

DTEL DTEL

247

247

�Example

package p1 ;

public class A

{

//body of the class A

}

Page 248: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Multileveled package Description

�Package is a keyword which is used to define package of any particular class.

�package pkg1.pkg2.pkg3._ _ _ _ .pkgn;

�Where package is a keyword & pkg1,pkg2,pkg3_ _ _ _ pkgn are the names of

packages(directories)

�pkg1 represent main directory

�pkg2 represent sub-directory of pkg1,

�Pkg3 represent sub directory of pkg2 & so on.

DTEL DTEL

248

248

Page 249: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Import Keyword Description

�Import is a keyword which is used to import any class file in main program file

where the class file should be present in the package.

�Syntax of import:-

� import packagename.classname;

� import package1[.package2][.package3].classname;

� OR

� import packagename.*;

�In first syntax of import statement only the given class will link with the main

program file.

DTEL DTEL

249

249

program file.

�In second syntax of import statement all the classes present in package will link

with the main program file.

Page 250: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- Example of import statement

� import java.lang.*;

import is a keyword which is used to import all the class file present in

java.lang package i.e. all the class files present in java.lang package will

link with the program file and program can access all the classes and

functions present in corresponding classes.

� import java.lang.String;

import statement will import single class file i.e. String class present in

java.lang package. import keyword will link String class file with

Example

DTEL DTEL

250

250

java.lang package. import keyword will link String class file with

program file.Therefore program can access only a single class(String)

and its function.

Page 251: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Description

If all the required files are present in a particular directory or folder & file

containing main program is present in different directory then such concept is

known as concept of different package.

DTEL DTEL

251

251

Page 252: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Example

DTEL DTEL

252

252

Page 253: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Example

Saving the file

DTEL DTEL

253

253

Page 254: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Example

DTEL DTEL

254

254

Page 255: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Example

Saving the file

DTEL DTEL

255

255

Page 256: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Example

How to save program of different package

1. Create a test folder.

2. Save person1.java in test folder.

3. import test.person1; in myperson1.java file

4. Save myperson1.java in your working drive.

5. Compile & Interpret myperson1 file

DTEL DTEL

256

256

Page 257: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Example

Output

DTEL DTEL

257

257

Page 258: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package

Declare Package named Rectangle (i.e create a folder named

Rectangle ) save class rectangle in that folder.

Example

DTEL DTEL

258

258

Page 259: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Example

Import package Rectangle in class AOR and save class AOR in current working

folder

DTEL DTEL

259

259

Page 260: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Different Package Example

OUTPUT

DTEL DTEL

260

260

Page 261: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Access Specifier Description

There are three types of access specifier available in java

1.private 2. public 3.protected.

� Private:-Whenever any data member or member function is declared as

private than that data member or member function is accessible within the

class block and is not accessible by using object i.e. object of that class

cannot access private members.

� Public:-Whenever any data member or member function is declared as

public then we can access public data members or member functions

within the class block as well as we can access all the public member using

DTEL DTEL

261

261

within the class block as well as we can access all the public member using

object of that class.

� Protected:- Whenever any data member or member function is declared as

protected than that data member or member function is accessible within

the class but object of super class or sub class cannot access protected

members provided object should present in different package. Members

can only be accessed by derived class.

Page 262: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Protected Access Specifier Example

DTEL DTEL

262

262

Page 263: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Protected Access Specifier Example

DTEL DTEL

263

263

Page 264: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Protected Access Specifier Example

Error

DTEL DTEL

264

264

Page 265: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Protected Access Specifier Example

Corrected Program

DTEL DTEL

265

265

Page 266: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Protected Access Specifier Example

Output

DTEL DTEL

266

266

Page 267: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Access protection Description

private default protected public

Same class Yes Yes Yes Yes

Same package subclass No Yes Yes Yes

Same package no

subclass

No Yes Yes Yes

Different package

subclass

No No Yes Yes

DTEL DTEL

267

267

subclass

Different package no

subclass

No No No No

Table: Class member access

Page 268: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-STATIC IMPORT Description

� It is used to import static member of a class.� It is used to refer to the static member directly without its classname.� There are two general forms of static import statement.

1. Import only a single static member of a class.

Syntax: import static package.classname.static_member_rname;

Example : import static java.lang.Math.sqrt;

DTEL DTEL

268

268

2. Imports all the static member of a class.

Syntax : import static package.classname.*;

Example : import static java.lang.Math.*;

Page 269: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-STATIC IMPORT Description

public class Test1

{

public static void main(String args[])

{

System.out.println(Math.sqrt(144));

}

}

import static java.lang.Math.*;

public class Test1

{

public static void main(String args[])

{

System.out.println(sqrt(144));

}}

DTEL DTEL

269

269

Page 270: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-4 Multithreaded Programming And Exception Handling

Topic 1: 1

Topic 2: 2

Multi Threading

Managing Errors and Exceptions

DTEL DTEL 270

Page 271: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-4 SPECIFIC OBJECTIVE / COURSE OUTCOME

1

The student will be able to:

To handle the exceptions in programs effectively.

They will also learn ‘how to make their programs

DTEL DTEL 271

2

They will also learn ‘how to make their programs

multithreaded’, set thread priorities, and the concept of

Deadlock.

Page 272: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- Error & Exception

�Fault occurs during the compile time of program is known as error.

�If the fault occurs during the runtime of the program then such fault is known

as exception.

�If any exception occurs during the runtime then java interpreter will catch such

exception and display the message depend on the type of exception and at last

the java interpreter will terminate the execution process.

�To solve the above problem, program must have to catch the exception during

runtime this is known as exception is catch by the program.

�If program is able to catch any exception than execution process will not

Description

DTEL DTEL

272

272

�If program is able to catch any exception than execution process will not

terminate.

Page 273: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Managing Errors & Exceptions Description

Errors classified into 2 types:

�Compile Time Errors :

� All syntax errors that will be given by java compliers. Until & unless these

errors are removed .class file is not created by java compiler.

�Run Time Errors :

�All errors which are generated while program is running.

�.class file is created by java compiler.

�resulting in termination of program abnormally.

DTEL DTEL

273

273

�resulting in termination of program abnormally.

Page 274: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Managing Errors & Exceptions Description

Exception Handling:

�Error which is generated at run time by some part of code , results in

abnormal termination of program.

�When program terminates abnormally all the input and calculation done is

lost.

�The process of solving the Exception at run time is known as Exception

Handling i.e. by creating object of exception type.

�All Exceptions are in java.lang package.

�Exception is a subclass of Throwable class.

DTEL DTEL

274

274

�Exception is a subclass of Throwable class.

�Exception are of 2 types:

�Checked Exception: checked at compile time.

�Unchecked Exception : not checked at compile time.

Page 275: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Managing Errors & Exceptions

Predefined Exceptions & their class hierarchies

Description

Object

Throwable

Exception

Class Not Found Exception

DTEL DTEL

275

275

Class Not Supported Exception

Illegal Access Exception

Installation Exception

Interrupted Exception

No Such Method Exception

Runtime Exception

Page 276: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Managing Errors & Exceptions

Predefined Exceptions & their class hierarchies

Description

Runtime Exception

Arithmetic Exception

Array Store Exception

Class Cast Exception

Illegal Monitor State Exception

DTEL DTEL

276

276

Illegal Monitor State Exception

Negative Array Size Exception

Null Pointer Exception

Security Exception

Index Out of Bounds Exception

Page 277: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Managing Errors & Exceptions Description

No Such Method Exception

class Ex5

{

public static void mian(String args[])

{

Employee e[]=new Employee[5];

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

e[i]=new Employee();

DTEL DTEL

277

277

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

e[i].getdata();

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

e[i].display();

}

}

Page 278: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Managing Errors & Exceptions Description

Exception Handling Mechanism includes a separate error handling code that

performs:

i. Find the problem.(Hit exception)

ii. Inform that an error has occurred.(Throw exception)

iii. Receive the error exception.(Catch exception)

iv. Take corrective actions.(Handle exception)

Exception Handling

DTEL DTEL

278

278

Exception Handling

Hit Exception Throw Exception Catch Exception Handle Exception

Page 279: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-ArrayIndexOutOfBoundsException occurred Example

class MyException1

{

public static void main(String args[])

{

int a[]={10,5,20,15,25};

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

{

System.out.println(a[i]);

}

DTEL DTEL

279

279

}

System.out.println("I am out of loop");

}

}

Page 280: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Example on ArithmeticException occurred Example

class MyException2

{

public static void main(String args[])

{

int a=10,b=0,c;

c=a/b;

System.out.println(c);

System.out.println("number divided by zero");

}

DTEL DTEL

280

280

}

}

Page 281: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Exception handling using try and catch Description

try

{

// block of code to monitor for errors

}

catch(ExceptionType1 exOb)

{

// exception handler for ExceptionType1

}

DTEL DTEL

281

281

}

catch(ExceptionType2 exOb)

{

//exception handler for ExceptionType2

}

//………

Page 282: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Exception handling using try and catch Description

try block

Statements that may

cause an exception

catch block

Statements that handle

the exception if it

Throws

exception

object

Exception

object

creator

Exception

handler

DTEL DTEL

282

282

the exception if it

occurred in try block

Exception handling mechanism

It provides two benefits.

� First, it allows us to fix the errors.

� Second, it prevents the program from automatically terminating.

Page 283: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-ArithmeticException caught Example

class MyException4

{

public static void main(String args[])

{

try

{

int a=10,b=0,c;

c=a/b;

System.out.println(c);

}

DTEL DTEL

283

283

}

catch(ArithmeticException e)

{

System.out.println("Exception Caught");

}

System.out.println("Satement out of try-catch block");

}

}

Page 284: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-ArrayIndexOutOfBoundsException caught Example

class MyException5

{

public static void main(String args[])

{

try

{

int a[]={10,5,20,15,25};

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

System.out.println(a[i]);

}

DTEL DTEL

284

284

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Exception Caught");

}

System.out.println("Statement out of try-catch block");

}

}

Page 285: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Exception Mismatch Example

class MyException6

{

public static void main(String args[])

{

try

{

int a[]={10,5,20,15,25};

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

System.out.println(a[i]);

}

DTEL DTEL

285

285

}

catch(ArithmeticException e)

{

System.out.println("Exception Caught");

}

System.out.println("Statement out of try-catch block");

}

}

Page 286: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Try with multiple catch Example

class MyException7 {

public static void main(String args[])

{

try {

int a[]={10,5,20,15,25};

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

System.out.println(a[i]);

}

System.out.println("Exception Caught

ArrayIndexOutOfBounds");

}

System.out.println("Statement out of try-

catch block");

} }

DTEL DTEL

286

286

}

catch(ArithmeticException e)

{

System.out.println("Exception Caught

Arithmetic");

}

catch(ArrayIndexOutOfBoundsExcepti

on e) {

Page 287: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Printing type of Exception Example

class MyException8

{

public static void main(String args[])

{

try

{

int a[]={10,5,20,15,25};

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

System.out.println(a[i]);

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println(" My Exception: "+e);

}

System.out.println("Statement out of try-

catch block");

}

DTEL DTEL

287

287

System.out.println(a[i]);

}

catch(ArithmeticException e)

{

}

System.out.println(" My Exception: "+e);

}

Page 288: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Nested Try Statements Example

class MyException9

{

public static void main(String args[])

{

try

{

int x[]={10,5,20,15,25};

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

System.out.println(x[i]);

try

{

catch(ArithmeticException e)

{

System.out.println(" Second try-catch: "+e);

}

System.out.println("Statement out of second

try-catch block");

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println(" First try-catch: "+e);

}

DTEL DTEL

288

288

{

int a=10,b=0,c;

c=a/b;

System.out.println(c);

}

}

System.out.println("Statement out of first try-

catch block");

}

}

Page 289: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Nested Try Statements Example

class MyException10

{

public static void main(String args[])

{

try

{

int x[]={10,5,20,15,25};

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

System.out.println(x[i]);

try

{

catch(ArithmeticException e)

{

System.out.println("Second try-catch: "+e);

}

System.out.println("Statement out of second

try-catch block");

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println(" First try-catch: "+e);

}

DTEL DTEL

289

289

{

int a=10,b=0,c;

c=a/b;

System.out.println(c);

}

}

System.out.println("Statement out of first try-

catch block");

}

}

Page 290: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Nested Try Statements Example

class MyException11

{

public static void main(String args[])

{

try

{

int x[]={10,5,20,15,25};

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

System.out.println(x[i]);

try

{

catch(ArithmeticException e)

{

System.out.println("Second try-catch: "+e);

}

System.out.println("Statement out of second

try-catch block");

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println(" First try-catch: "+e);

}

DTEL DTEL

290

290

{

int a=10,b=5,c;

c=a/b;

System.out.println(c);

}

}

System.out.println("Statement out of first try-

catch block");

}

}

Page 291: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Finally block Description

General form of finally block

try

{

______ ;

______ ;

}

finally

{

______;

try

{

_____________;

_____________;

}

catch(….)

{_____________; }

catch(….)

DTEL DTEL

291

291

______;

______;

}

catch(….)

{_____________; )

finally

{

_______________;

_______________;

}

Page 292: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Finally block Description

try

catch

Exception

DTEL DTEL

292

292

finally

No Exception

Page 293: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Finally block Example

class MyException12

{

public static void main(String args[])

{

try

{

int a=10,b=0,c;

c=a/b;

System.out.println(c);

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Exception Caught :

"+e);

}

System.out.println("Statement out of try-

catch block");

}

}

DTEL DTEL

293

293

System.out.println(c);

}

}

Page 294: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Finally block Example

class MyException13

{

public static void main(String args[])

{

try

{

int a=10,b=0,c;

c=a/b;

catch(ArrayIndexOutOfBoundsException

e)

{

System.out.println("Exception Caught :

"+e);

}

finally

{

DTEL DTEL

294

294

c=a/b;

System.out.println(c);

}

{

System.out.println("Statement out of try-

catch block");

} } }

Page 295: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Finally block Example

class MyException14

{

public static void main(String args[])

{

try

{

int a=10,b=0,c;

c=a/b;

catch(ArithmeticException e)

{

System.out.println("Exception Caught :

"+e);

}

finally

{

System.out.println("Statement out of try-

catch block");

DTEL DTEL

295

295

c=a/b;

System.out.println(c);

}

catch block");

} } }

Page 296: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Finally block Example

class MyException15

{

public static void main(String args[])

{

try

{

int a=10,b=0,c;

c=a/b;

catch(ArithmeticException e)

{

System.out.println("Exception Caught : "+e);

}

finally

{

System.out.println("Statement out of try-

catch block");

DTEL DTEL

296

296

c=a/b;

System.out.println(c);

}

catch block");

}

System.out.println("outer statements");

} }

Page 297: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Finally block Example

class MyException16

{

public static void main(String args[])

{

try

{

int a=10,b=0,c;

c=a/b;

{

System.out.println("Exception Caught :

"+e);

}

finally

{

System.out.println("Statement out of try-

catch block");

}

DTEL DTEL

297

297

c=a/b;

System.out.println(c);

}

catch(ArrayIndexOutOfBoundsExcept

ion e)

}

System.out.println("outer statements");

}

}

Page 298: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Generalize Exception Example

class MyException17

{

public static void main(String args[])

{

try

{

int a=10,b=0,c;

c=a/b;

System.out.println("Exception Caught :

"+e);

}

finally

{

System.out.println("Statement out of try-

catch block");

}

DTEL DTEL

298

298

c=a/b;

System.out.println(c);

}

catch(Exception e)

{

System.out.println("outer statements");

}

}

Page 299: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-The throws clause Description

� If a method is capable of causing an exception that it does not handle, it must

specify this behavior so that callers of the method can protect themselves

against that exception. We do this by including a throws clause in front of the

method’s declaration.

� A throws clause lists the types of exceptions that a method might throw. This

is necessary for all exceptions, except those of type Error or

RuntimeException, or any of their subclasses.

� All other exceptions that a method can throw must be declared in the throws

clause. If they are not, a compile-time error will occur.

DTEL DTEL

299

299

clause. If they are not, a compile-time error will occur.

� The general form of writing a throws clause is,

data-type method-name(parameter-list) throws exception-list

{

// body of method

}

Here the exception-list is the list of exceptions that the method might throw

separated by comma.

Page 300: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-The throws clause Example

class TestThrows{static void throwone()throws IllegalAccessException{System.out.println("Inside throwone");throw new IllegalAccessException("demo");}public static void main(String args[]){try{

DTEL DTEL

300

300

{throwone();}catch(IllegalAccessException e){System.out.println("Caught"+e);}}}

Page 301: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Multitasking Process Description

If two or more than two applications (programs) runs concurrently then such

process is known as multitasking process.

DTEL DTEL

301

301

Page 302: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Multi threading Description

class math

{

void add()// thread 1

{

}

void sub() //thread 2

{

}

}

program

DTEL DTEL

302

302

}

� If two or more than two parts of program runs concurrently than such

process is known as multithreading process.

� Each part of program is known thread.

� Java interpreter stores three different information about any thread i.e.

thread name, priority number and parent thread name(group name).

Page 303: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Multi threading Process Description

� Main is a thread which stores following three information

� main:5:main

� Thread name Priority number Parent thread name(Group name)

� Since there is no parent thread of main therefore its group name is main.

� Default priority number of main thread is always 5 which is assigned by

java interpreter.

� Minimum priority number is 1 and maximum priority number is 10.

DTEL DTEL

303

303

� Minimum priority number is 1 and maximum priority number is 10.

� Thread having maximum priority number will be executed first as

compared to thread having minimum priority number.

Page 304: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Diff between multithreading & multitasking Difference

S.N. Multithreading Multitasking

1 Multithreading is a programming

concept in which a program or a

process is divided into two or

more subprograms or threads that

are executed at the same time in

parallel.

Multitasking is an operating

system concept in which multiple

tasks are performed

simultaneously.

2 A thread is the smallest unit in A program or process is the

DTEL DTEL

304

304

2 A thread is the smallest unit in

multithreading.

A program or process is the

smallest unit in a multitasking.

Page 305: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Main Thread Description

� All threads are generated from main thread only.

� main thread is first thread created automatically when program starts.

� main thread can be controlled by Thread object.

DTEL DTEL

305

305

Page 306: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Thread Class Description

� Thread is a class present in java.lang package containing all the methods

required for creating child threads.

� A thread is a thread of execution in a program.

� The Java Virtual Machine allows an application to have multiple threads of

execution running concurrently.

DTEL DTEL

306

306

Page 307: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Method of Thread class Description

� static void sleep(long millis)

� Causes the currently executing thread to sleep for the specified number of

milliseconds.

� sleep() function is present in Thread class declared as static therefore we can

access sleep() function without using object of Thread class i.e. we can access

sleep() function by using classname.

Whenever sleep function is executed the execution control comes out of the

DTEL DTEL

307

307

� Whenever sleep function is executed the execution control comes out of the

current thread and executes the instructions of other threads upto given

number of milliseconds and after completion of time the execution control

returns back to the next step of current thread.

Page 308: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Sleep function using try catch Example

class Myprog1

{

public static void main(String args[])

{

try

{

for(int i=1;i<=10;i++)

{

Thread.sleep(1000);

}

}

catch(InterruptedException e)

{

System.out.println("Exception Caught");

}

}

}

DTEL DTEL

308

308

{

System.out.println(i);

}

Page 309: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-sleep function using throws Example

class Myprog1

{

public static void main(String args[])throws InterruptedException

{

for(int i=1;i<=10;i++)

{

System.out.println(i);

Thread.sleep(1000);

}

DTEL DTEL

309

309

}

}

}

Page 310: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Method of Thread class Description & Example

�static Thread currentThread()

Returns a reference to the currently executing thread object.

� void setName(String name)

Changes the name of this thread to be equal to the argument name.

�WAP to show thread name, priority no. & group name of current thread

class Myprog2

{

public static void main(String args[])

{

Thread t=Thread.currentThread();

System.out.println("Current thread:"+t);

DTEL DTEL

310

310

System.out.println("Current thread:"+t);

t.setName("Mythread");

System.out.println("Current thread:"+t);

}

}

Page 311: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Thread Priority Description

�In order to set a thread’s priority, use the setPriority( ) method of thread class.

�It is having the following general form:

�final void setPriority(int level)

�Thread class has defined another method to obtain the priority given to the

Thread named getPriority( ).

�It has following general form:

�final int getPriority()

DTEL DTEL

311

311

Page 312: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-getPriority() & setPriority() Example

class Priority

{

public static void main(String args[])

{

Thread t= Thread.currentThread();

System.out.println("Current

Thread:"+t);

t.setName("First thread");

System.out.println("The priority

is"+priority);

t.setPriority(10);

priority=t.getPriority();

System.out.println("New priority

is"+priority);

}

}

DTEL DTEL

312

312

t.setName("First thread");

System.out.println("New Name:"+t);

int priority=t.getPriority();

}

Page 313: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Life Cycle of Thread Description

Newborn

Runnable RunningDead

start()

stop()

stop()

New thread

Active thread

DTEL DTEL

313

313

Dead

Blocked

stop()

yield()

suspend()

sleep()

wait()

resume()

notify()

Idle thread

Killed

thread

Page 314: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Life Cycle of Thread Description

� Newborn State : When a thread object is created.

Ex : Thread t = new Thread();

� Runnable State : When thread is ready for execution.

Ex : t.start();

� Running State : When processor has taken thread for execution.

Ex : t.start();

� Blocked State : When a thread is prevented from entering the Runnable

State.

Ex : t.suspend();

t.sleep();

DTEL DTEL

314

314

t.sleep();

t.wait();

� Dead State : When a running thread ends it’s life ; when it has completed

execution or by calling stop() method.

Ex : t.stop();

Page 315: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Methods of Thread class Description

�void suspend():-suspend() function of Thread class pause the currently running

thread.

�void resume():-resume() function of Thread class is used to restart the

execution process of suspended thread.

�static void yield():- Causes the currently executing thread object to temporarily

pause and allow other threads to execute.

�Waiting and notifying provide means of communication between threads that

synchronize on the same object.

�wait( ):- It is used to tell the calling thread to give up the lock and go to sleep

DTEL DTEL

315

315

�wait( ):- It is used to tell the calling thread to give up the lock and go to sleep

until some other thread enters the same lock and calls notify( ).

�notify( ):- It wakes up the first thread that called wait( ) on the same object.

�notifyAll( ):- It wakes up all the threads that called wait( ) on the same object.

Here, the highest priority thread will run first.

Page 316: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Creating Threads

Threads can be created by two methods.

Description

Thread

Thread (Class) Runnable (Interface)

extends Implements(for multiple interfaces)

DTEL DTEL

316

316

Thread (Class)

run() method

overrides

Page 317: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Creating a thread by implementing the Runnable interface Description

�The easiest way to create a thread is to create a class that implements Runnable

interface.

�To implement Runnable, a class need only implement a single method called run( ),

which is declared in Runnable as:

public void run( )

run( ) establishes the entry point for another, concurrent thread of execution within the

program. This thread will end when run( ) returns.

�We have to instantiate an object of type Thread from within that class.

Thread(Runnable threadOb, String threadName)

DTEL DTEL

317

317

Thread(Runnable threadOb, String threadName)

�After the new thread is created, it will not start running until we call its start( ) method,

which is declared within Thread.

In essence, start( ) executes a call to run() method. General form of start( ) method is:

void start()

Page 318: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Program for creating thread using Runnable interface Example

class MyThread1 implements Runnable

{

Thread t;

String s=null;

MyThread1(String s1)

{

s=s1;

t=new Thread(this);

public void run()

{

System.out.println(s);

}

}

public class RunnableThread

{

public static void main(String args[])

DTEL DTEL

318

318

t=new Thread(this);

t.start();

}

public static void main(String args[])

{

MyThread1 m1=new

MyThread1("Thread started");

} }

Page 319: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Program for creating thread using Runnable interface Example

WAP to create a child thread using runnable interface & synchronies the process of child

thread with main thread

class Newthread implements Runnable

{

Thread t;

Newthread()

{

t=new Thread(this,"My child");

try

{

for(int i=1;i<=10;i++)

{

System.out.println("Child

thread="+i);

DTEL DTEL

319

319

t=new Thread(this,"My child");

t.start();

}

public void run()

{

thread="+i);

Thread.sleep(500);

}

}

catch(InterruptedException e)

{

}}}

Page 320: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Program for creating thread using Runnable interface Example

WAP to create a child thread using runnable interface & synchronies the process of child

thread with main thread

class Mythread1

{

public static void main(String args[])

{

Newthread n1=new Newthread();

try

}

}

catch(InterruptedException e)

{

}

}

DTEL DTEL

320

320

try

{

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

{

System.out.println("Main thread="+i);

Thread.sleep(1000);

}

}

Page 321: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Program for creating thread using Runnable interface Example

WAP to create a child thread using runnable interface & synchronies the process of

child thread with main thread

class Newthread implements Runnable

{

Thread t;

Newthread()

{

t=new Thread(this,"My child");

for(int i=1;i<=10;i++)

{

System.out.println("Child thread="+i);

Thread.sleep(1000);

}

}

DTEL DTEL

321

321

t=new Thread(this,"My child");

t.start();

}

public void run()

{

try

{

}

catch(InterruptedException e)

{

}

}

}

Page 322: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:- Program for creating thread using Runnable interface Example

WAP to create a child thread using runnable interface & synchronies the process of

child thread with main thread

class Mythread1

{

public static void main(String args[])

{

Newthread n1=new Newthread();

try

}

}

catch(InterruptedException e)

{

}

}

DTEL DTEL

322

322

try

{

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

{

System.out.println("Main thread="+i);

Thread.sleep(500);

}

}

Page 323: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-join( ) methods Description

�The join( ) method is used to wait for the thread to finish. Its general form is:

�final void join() throws InterruptedException

�This method waits until the thread on which it is called terminates.

�Its name comes from the concept of the calling thread waiting until the specified

thread joins it.

DTEL DTEL

323

323

Page 324: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-join( ) methods Example

WAP to create multiple thread & synchronise the process of all the child thread with each

other

class Newthread implements Runnable

{

String s;

Thread t;

Newthread()

{

s="child";

t=new Thread(this,s);

t.start();

public void run()

{

try

{

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

{

System.out.println(s+"="+i);

Thread.sleep(500);

}

DTEL DTEL

324

324

t.start();

}

Newthread(String s1)

{

s=s1;

t=new Thread(this,s);

t.start();

}

}

}

catch(InterruptedException e)

{

}

}

}

Page 325: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-join( ) methods Example

WAP to create multiple thread & synchronise the process of all the child thread with each

other

class Mythread4

{

public static void main(String args[])

{

Newthread n1=new Newthread("First");

n1.t.join();

n2.t.join();

n3.t.join();

}

catch(InterruptedException e)

{

DTEL DTEL

325

325

Newthread("First");

Newthread n2=new Newthread("Second");

Newthread n3=new Newthread("Third");

try

{

{

}

}

}

Page 326: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Creating a thread by inheriting from Thread class Description

1. The second way to create a thread is to create a new class that is derived

from Thread class, and then to create an instance of that class.

2. The inheriting class must override the run( ) method, which is the entry

point for the new thread.

3. It must also call start( ) to begin execution of the new thread.

DTEL DTEL

326

326

Page 327: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Program to demonstrate thread creation extending the “Thread” class Example

class MyThread extends Thread

{

String s=null;

MyThread(String s1)

{

s=s1;

start();

}

public void run()

System.out.println(s);

}

}

public class RunThread

{

public static void main(String args[])

{

MyThread m1=new MyThread("Thread started");

}

DTEL DTEL

327

327

public void run()

{

}

}

Page 328: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Program to demonstrate thread creation extending the “Thread” class Example

WAP to create a child thread using super class thread & synchronies the process of child

thread with main thread

class Newthread extends Thread

{

String name;

Newthread(String s)

{

name=s;

for(int i=1;i<=10;i++)

{

System.out.println(name+"="+i);

Thread.sleep(500);

}

}

DTEL DTEL

328

328

name=s;

start();

}

public void run()

{

try

{

}

catch(InterruptedException e)

{

}

}

}

Page 329: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Program to demonstrate thread creation extending the “Thread” class Example

WAP to create a child thread using super class thread & synchronies the process of child

thread with main thread

class Mythread5

{

public static void main(String args[])

{

Newthread n1=new Newthread("Child");

try

catch(InterruptedException e)

{

}

}

}

DTEL DTEL

329

329

try

{

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

{

System.out.println("main="+i);

Thread.sleep(1000);

}

}

Page 330: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Program to demonstrate thread creation extending the “Thread” class Example

Write a program to create two threads one to print odd numbers from 1 to 10 and other to

print even numbers from 11 to 20.

class odd extends Thread

{

public void run()

{

try

{

} } }

catch(InterruptedException e)

{}

} }

class even extends Thread

{

DTEL DTEL

330

330

{

for(int i=1;i<=10;i++)

{

if(i%2!=0)

{

System.out.println("Odd number="+i);

Thread.sleep(500);

{

public void run()

{

try

{

for(int i=11;i<=20;i++)

{

Page 331: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Program to demonstrate thread creation extending the “Thread” class Example

Write a program to create two threads one to print odd numbers from 1 to 10 and other to

print even numbers from 11 to 20.

if(i%2==0)

{

System.out.println("Even

number="+i);

Thread.sleep(500);

} } }

{

new odd().start();

new even().start();

} }

DTEL DTEL

331

331

} } }

catch(InterruptedException e)

{ }

} }

class evenodd

{

public static void main(String args[])

Page 332: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Program to demonstrate thread creation extending the “Thread” class Example

Write a program to create two threads so one thread will print 1 to 10 number where as

second thread will print 11 to 20 numbers.

class one2ten extends Thread

{

public void run()

{

try

catch(InterruptedException e)

{}

} }

class eleven2twenty extends Thread

{

DTEL DTEL

332

332

{

for(int i=1;i<=10;i++)

{

System.out.println("First

Thread="+i);

Thread.sleep(500);

} }

public void run()

{

try

{

for(int i=11;i<=20;i++)

{

Page 333: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Program to demonstrate thread creation extending the “Thread” class Example

Write a program to create two threads so one thread will print 1 to 10 number where as

second thread will print 11 to 20 numbers.

System.out.println("Second

Thread="+i);

Thread.sleep(500);

}

}

catch(InterruptedException e)

new one2ten().start();

new eleven2twenty().start();

} }

DTEL DTEL

333

333

catch(InterruptedException e)

{}

} }

class one2twenty

{

public static void main(String args[])

{

Page 334: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-isAlive( ) Description

�The isAlive( ) method of Thread class is used to determine whether the thread has

finished its execution or not?

�The general form of this method is:

�final boolean isAlive()

�This method returns true if the thread upon which it is called is still running else returns

false.

DTEL DTEL

334

334

Page 335: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-isAlive( ) Example

class Newthread extends Thread

{

String name;

Newthread(String s)

{

start();

name=s;

}

} }

catch(InterruptedException e)

{ }

} }

class Mythread7

{

public static void main(String args[])

{

DTEL DTEL

335

335

public void run()

{

try

{

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

{

System.out.println(name+"="+i);

Thread.sleep(500);

Newthread n1=new

Newthread("Child1");

Newthread n2=new

Newthread("Child2");

Newthread n3=new

Newthread("Child3");

System.out.println(n1.isAlive());

System.out.println(n2.isAlive());

Page 336: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-isAlive( ) Example

System.out.println(n3.isAlive());

try

{

n1.join();

n2.join();

n3.join();

}

catch(InterruptedException e)

{

}

System.out.println(n1.isAlive());

System.out.println(n2.isAlive());

System.out.println(n3.isAlive());

}

}

DTEL DTEL

336

336

Page 337: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-WAP to show the use of suspend(); & resume(); function Example

class Newthread extends Thread

{

String name;

Newthread(String s)

{

super(s);

start();

name=s;

}

System.out.println(name+"="+i);

Thread.sleep(500);

}

}

catch(InterruptedException e)

{

}

}

DTEL DTEL

337

337

}

public void run()

{

try

{

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

{

}

}

class Mythread8

{

public static void main(String args[])

{

Newthread n1=new Newthread("Child1");

Newthread n2=new Newthread("Child2");

Newthread n3=new Newthread("Child3");

Page 338: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-WAP to show the use of suspend(); & resume(); function Example

try

{

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

{

System.out.println("Main="+i);

if(i==2)

n1.suspend();

Thread.sleep(1500);

DTEL DTEL

338

338

Thread.sleep(1500);

}

}

catch(InterruptedException e)

{

}

n1.resume();

}

}

Page 339: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-WAP to show the use of suspend(); & resume(); function Example

Main=1

Child1=1

Child2=1

Child3=1

Main=2

Child2=2

Child3=2

Child2=3

Main=3

Child1=4

Child1=5

DTEL DTEL

339

339

Main=3

Child2=4

Child3=3

Child2=5

Main=4

Child3=4

Child3=5

Child1=2

Child1=3

Page 340: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Sychronized keyword Description

� When any method is declared as synchronized then that method is known as

synchronized method.

� Synchronized method will not terminate during its own execution & executes

all the instructions present in a method & after complete execution, the

execution control enters into the process of next child thread.

DTEL DTEL

340

340

Page 341: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Sychronized keyword Example

class Message

{

void show(String s)

{

System.out.println("start="+s);

try

{

Thread.sleep(1000);

}

catch(InterruptedException e)

class Newthread extends Thread

{

Message m;

String s;

Newthread(String name,Message m1)

{

super(name);

start();

s=name;

m=m1;

DTEL DTEL

341

341

catch(InterruptedException e)

{

}

System.out.println("stop");

}

}

m=m1;

}

public void run()

{

m.show(s);

}

}

Page 342: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Sychronized keyword Example

class Mythread9

{

public static void main(String args[])

{

Message m=new Message();

Newthread n1=new Newthread("child1",m);

Newthread n2=new Newthread("child2",m);

Newthread n3=new Newthread("child3",m);

try

catch(InterruptedException e)

{

}

}

}

DTEL DTEL

342

342

try

{

n1.join();

n2.join();

n3.join();

}

Page 343: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Sychronized keyword Example

class Message

{

synchronized void show(String s)

{

System.out.println("start="+s);

try

{

Thread.sleep(1000);

}

catch(InterruptedException e)

class Newthread extends Thread

{

Message m;

String s;

Newthread(String name,Message m1)

{

super(name);

start();

s=name;

m=m1;

DTEL DTEL

343

343

catch(InterruptedException e)

{

}

System.out.println("stop");

}

}

m=m1;

}

public void run()

{

m.show(s);

}

}

Page 344: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Sychronized keyword Example

class Mythread9

{

public static void main(String args[])

{

Message m=new Message();

Newthread n1=new

Newthread("child1",m);

Newthread n2=new

Newthread("child2",m);

catch(InterruptedException e)

{

}

}

}

DTEL DTEL

344

344

Newthread("child2",m);

Newthread n3=new

Newthread("child3",m);

try

{

n1.join();

n2.join();

n3.join();

}

Page 345: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-The throw statement

� If we want to throw the exceptions by our own, the throw statement

can be used. That is, it will force the Java run-time system to throw an

exception.

� The general form of throw statement is:

� throw Throwable-Instance;

� Here, the Throwable-Instance must be an object of type Throwable or a

Description

DTEL DTEL

345

345

� Here, the Throwable-Instance must be an object of type Throwable or a

subclass of Throwable.

Page 346: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-The throw statement Example

import java.lang.*;

public class Test

{

public static void main(String args[])throws Exception

{

int num1=20,num2=10;

if(num1>num2)

throw new Exception("number1 is greater");

else

DTEL DTEL

346

346

else

System.out.println("number2 is greater");

}

}

Page 347: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-The throw statement Example

import java.lang.*;

import java.io.*;

class MyException extends Exception

{

MyException(String msg)

{

super(msg);

}

}

class Exp12_2

{

public static void main(String args[])

{

BufferedReader br=new

BufferedReader(new

InputStreamReader(System.in));

try

{

DTEL DTEL

347

347

}{

System.out.println("Enter a number=");

int number=Integer.parseInt(br.readLine());

Page 348: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-The throw statement Example

if((number%2)==0)

{

throw new MyException("Even

number");

}

else

{

throw new MyException("Odd number");

catch(IOException e)

{

System.out.println(e);

}

}

}

DTEL DTEL

348

348

}

}

catch(MyException e)

{

System.out.println(e);

}

Page 349: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-The throw statement Example

import java.lang.*;

import java.io.*;

class MyException extends Exception

{

MyException(String msg)

{

super(msg);

}

}

class Example1

{

public static void main(String args[])

{

BufferedReader br=new

BufferedReader(new

InputStreamReader(System.in));

try

{

DTEL DTEL

349

349

}{

String s1="sdmp";

System.out.println("Enter the

password:");

String s2=br.readLine();

Page 350: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-The throw statement Example

if(s1.equals(s2))

{

throw new MyException("Authentication

Successful");

}

else

{

throw new MyException("Authentication

Failure");

catch(MyException e)

{

System.out.println(e);

}

catch(IOException e)

{

System.out.println(e);

}

DTEL DTEL

350

350

Failure");

}

}

}

}

}

Page 351: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-5 Java Applets and Graphics Programming

Topic 1: 1

Topic 2: 2

Applet Programming

Graphics Programming

DTEL DTEL 35

1

Page 352: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-5 SPECIFIC OBJECTIVE / COURSE OUTCOME

1

The student will be able to:

The students will be able to write interactive applets and

make use of graphics in programming.

DTEL DTEL 35

2

2They will also learn to change the background and the

foreground color and to use the different fonts.

Page 353: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- A Simple Applet Example

DTEL DTEL

353

353

Page 354: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-APPLET Description

Applet program is a window base program which is used to create active

program in website i.e. whenever programmer require to run any program in

website then we must have to use the concept of applet programming

DTEL DTEL

354

354

Page 355: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-The Applet class Description

� To create an applet, you must import the Applet class

� This class is in the java.applet package

� The Applet class contains code that works with a browser to create a display

window

� Capitalization matters!

� applet and Applet are different names

DTEL DTEL

355

355

Page 356: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Applets and applications Description

� An applet is a Java program that runs on a web page

� Applets can be run within any modern browser

� To run modern Java applets, old browsers need an up-to-date Java

plugin

� appletviewer is a program that can run

� An application is a Java program that runs all by itself

DTEL DTEL

356

356

Page 357: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Application vs. Applet Description

� Application� Run on stand alone systems.� Invoked by Java Virtual Machine

(JVM, java), e.g.,java HelloWorld

� Should contain a main method, i.e.,

public static void main(String[])

� Applet� Run in web pages.� Invoked automatically by

the web browser.� Should be a subclass of

class java.applet.Applet

DTEL DTEL

357

357

Page 358: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Applets and applications Difference

How Applet Differ From Application

•Applets and standalone applications are Java Programs, with difference

between them listed below:

1. Applets are not fully-featured application programs. They are written to

accomplish a small task.

DTEL DTEL

358

358

2. Applets are designed for use on internet, they have certain limitations and

restrictions in their design.

3. Applets do not use main() method for initiating the execution of code.

Applets,when loaded, automatically calls certain methods of Applet class to

start and execute the applet code.

Page 359: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Applets and applications Difference

How Applet Differ From Application

4. Stand alone application can run independently, whereas applets cannot

be run independently. They are run inside the webpage using HTML tag.

5. Applets cannot read from or write to the files in the local computer.

6. Applets cannot communicate with other server over

network.

DTEL DTEL

359

359

7. Applet cannot run any program from the local computer.

8. Applets are restricted from using libraries from other languages such as

C,C++.

9. All above restrictions ensures that an applet cannot make any damage to

the local system.

Page 360: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Importing the Applet class Description

� Here is the directive that you need:

� import java.applet.Applet;

� import is a keyword.

� java.applet is the name of the package.

� A dot ( . ) separates the package from the class.

DTEL DTEL

360

360

� Applet is the name of the class.

� There is a semicolon ( ; ) at the end.

Page 361: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-The java.awt package

� “awt” stands for “Abstract Window Toolkit”

� The java.awt package includes classes for:

� Drawing lines and shapes

� Drawing letters

� Setting colors

� Choosing fonts

� If it’s drawn on the screen, then java.awt is probably involved!

� Since you may want to use many classes from the java.awt package, simply

import them all:

Description

DTEL DTEL

361

361

import them all:

� import java.awt.*;

� The asterisk, or star (*), means “all classes”

� The import directives can go in any order, but must be the first lines in your

program

Page 362: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-The applet so far Description

import java.applet.Applet;

import java.awt.*;

DTEL DTEL

362

362

Page 363: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Your applet class Description

� public class Program1 extends Applet

� {

… }

� Program1 is the name of your class

� Class names should always be capitalized

� extends Applet says that our Program1 is a kind of Applet, but with added

capabilities

� Java’s Applet just makes an empty window

� We are going to draw in that window

DTEL DTEL

363

363

� We are going to draw in that window

� The only way to make an applet is to extend Applet

Page 364: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-The applet so far Description

import java.applet.Applet;

import java.awt.*;

public class Program1 extends Applet

{

…we still need to put some code in here...

}

DTEL DTEL

364

364

Page 365: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Pixels Description

� A pixel is a picture (pix) element

� one pixel is one dot on your screen

� java.awt measures everything in pixels

DTEL DTEL

365

365

Page 366: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-APPLET TAG Description

� HTML is a hypertext markup language which is used to create webpage for any

website.

� To create any webpage we have to use html tags. Similarly to create applet

window we have to use applet tag.

� The syntax of applet tag is given below

<applet code=<classname> width=<value in pixels> height=<value in pixels>>

</applet>

� Applet tag contains three elements i.e.code,width and height

� Code specify the class name in which applet program is present

DTEL DTEL

366

366

� Code specify the class name in which applet program is present

� Width specify the width of applet window in pixels

� Height specify the height of applet window in pixels

Page 367: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Sample Applet Program Example

/*

<applet code=“Program1” width=300 height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class Program1 extends Applet

{

}

DTEL DTEL

367

367

STEPS TO RUN APPLET PROGRAM

C:\>javac Program1.java

C:\>AppletViewer Program1.java

Page 368: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Output Example

DTEL DTEL

368

368

Page 369: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Sample Program Description

DTEL DTEL

369

369

Page 370: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Elements of Applets Description

�Superclass: java.applet.Applet

�No main method

�paint method to paint the picture

�Applet tag: <applet> </applet>

� Code

� Width and Height

DTEL DTEL

370

370

Page 371: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-AppletViewer

� AppletViewer is a interpreter developed by SunMicroSystem.

� It is used to interpret HTML file and generate output according to the tag.

� When execution control enters into a class file then it will interpret statements

present in multiline comments then AppletViewer will create applet window

according to the given width and height.

� When applet window is created then it will link class file with applet window

and class file will generate its output in applet window.

Description

DTEL DTEL

371

371

and class file will generate its output in applet window.

� Therefore, only applet tag and class files are necessary requirement for

AppletViewer interpreter.

Page 372: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Skeleton of Applet Class Description

Applet is a class present in java.applet package containing five methods known

as applet events as given below:

1) public void init();

2) public void start();

3) public void stop();

4) public void destroy();

DTEL DTEL

372

372

4) public void destroy();

5) public void paint(Graphics g);

Page 373: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Skeleton of Applet Class Description

1) public void init();� init() function is executed by the applet viewer during the initialization of applet

program.� init() function is used to initialize object or variables of class.� During runtime init() function will execute only single time.

2) public void start();

� start() function of applet class is executed by the AppletViewer after the

initialization of applet program .

� Also it is execute by the AppletViewer/internet explorer whenever the applet

webpage is refreshed

DTEL DTEL

373

373

webpage is refreshed

3) public void stop();

� stop() function of applet class is execute by the AppletViewer/internet explorer

whenever the applet window is closed or process of downloading is stop.

4) public void destroy();

� destroy() function of applet class is execute by the AppletViewer/ internet explorer

when the website or applet window is completely closed

Page 374: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Skeleton of Applet Class

5) public void paint(Graphics g);

� paint() function is executed by the AppletViewer/internet explorer whenever

the applet window is create or maximized/restore/refresh.

� paint() function contain a single argument of type Graphics which is used to

perform graphical operations in applet window.

� Our applet is going to have a method to paint some colored rectangles on the

screen

� This method must be named paint

� paint needs to be told where on the screen it can draw

� This will be the only parameter it needs

Description

DTEL DTEL

374

374

� paint doesn’t return any result

� public void paint(Graphics g) { … }

� public says that anyone can use this method

� void says that it does not return a result

� A Graphics (short for “Graphics context”) is an object that holds information

about a painting

� It remembers what color you are using

� It remembers what font you are using

� You can “paint” on it (but it doesn’t remember what you have painted)

Page 375: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Applet Life Cycle Diagram

BORN

RUNNING IDLE

INTIALIZATION init();

STOPPED

start()

Begin

(LOAD

APPLET)

stop();

DTEL DTEL

375

375

DEAD END

start();

paint();

destroy();

Destroyed

Exit of Browser

Page 376: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Methods of applet life cycle Description

Method When the method is called and its purpose

public

void init()

This method is called once by the applet container when an applet is

loaded for execution. It performs initialization of an applet. Typical

actions performed here are initializing fields, creating GUI

components, loading sounds to play, loading images to display

public

void

start()

This method is called after the init method completes execution. In

addition, if the browser user visits another Web site and later returns

to the HTML page on which the applet resides, method start is called

again. The method performs any tasks that must be completed when

DTEL DTEL

376

376

again. The method performs any tasks that must be completed when

the applet is loaded for the first time and that must be performed

every time the HTML page on which the applet resides is revisited.

Typical actions performed here include starting an animation (see

Chapter 19) and starting other threads of execution

Page 377: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Methods of applet life cycle Description

public void paint(

Graphics g )

This drawing method is called after the init method completes

execution and the start method has started. It is also called every

time the applet needs to be repainted. For example, if the user

covers the applet with another open window on the screen and

later uncovers the applet, the paint method is called. Typical actions

performed here involve drawing with the Graphics object g that is

passed to the paint method by the applet container.

public void stop() This method is called when the applet should stop executing—

normally, when the user of the browser leaves the HTML page on

DTEL DTEL

377

377

normally, when the user of the browser leaves the HTML page on

which the applet resides. The method performs any tasks that are

required to suspend the applet’s execution. Typical actions

performed here are to stop execution of animations and threads.

public void

destroy()

This method is called when the applet is being removed from

memory—normally, when the user of the browser exits the

browsing session (i.e., closes all browser windows). The method

performs any tasks that are required to destroy resources allocated

to the applet.

Page 378: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-The applet so far

import java.applet.Applet;

import java.awt.*;

public class Program1 extends Applet {

public void paint(Graphics g) {

…we still need to put some code in here…

}

}

Description

DTEL DTEL

378

378

Page 379: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Java’s coordinate system Description

� Java uses an (x, y) coordinate system

DTEL DTEL

379

379

� Java uses an (x, y) coordinate system

� (0, 0) is the top left corner

� (50, 0) is 50 pixels to the right of (0, 0)

� (0, 20) is 20 pixels down from (0, 0)

� (w - 1, h - 1) is just inside the bottom right corner, where w is the

width of the window and h is its height

Page 380: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-drawString() Method Description

� It is the member of the Graphics class.

� It is used to output a string to an applet.

� Syntax-: void drawString( String message, int x ,int y );

� Here, message is the string to be output beginning at x,y.

� In a java window, the upper-left corner is location 0,0.

� The drawString() method will not recognize newline characters.

� If you want to start a line of text on another line,you must do so manually

,specifying the precise X,Y location where you want the line to begin.

� This method is used to draw the message specified in ‘message’ on the

DTEL DTEL

380

380

� This method is used to draw the message specified in ‘message’ on the

applet window at the position specified by ‘x’ and ‘y’ position(i.e x and y co-

ordinates)

Page 381: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-drawString() Method

WAP to create applet window and show “Hello” message in

applet window

Example

/*<applet code="p1" width=300 height=300></applet>*/import java.applet.*;import java.awt.*;public class p1 extends Applet{

DTEL DTEL

381

381

{public void paint(Graphics g){g.drawString("hello",100,20);}}

Page 382: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-drawString() Method Output

DTEL DTEL

382

382

Page 383: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Events of Applet Window

/*<applet code="p10" width=300

height=300>

</applet>*/

import java.applet.*;

import java.awt.*;

public class p10 extends Applet

{

String msg;

public void init()

{

Example

public void paint(Graphics g)

{

msg=msg+"Paint";

g.drawString(msg,20,100);

}

public void stop()

{

msg=msg+"stop";

}

public void destroy()

DTEL DTEL

383

383

{

msg="Init";

}

public void start()

{

msg=msg+"Start";

}

public void destroy()

{

msg=msg+"Destroy";

}

}

Page 384: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Events of Applet Window Output

DTEL DTEL

384

384

Page 385: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Color Class Description

� The java.awt package defines a class named Color� There are 13 predefined colors—here are their fully-qualified names:

Color.BLACK Color.PINK Color.GREENColor.DARK_GRAY Color.RED Color.CYANColor.GRAY Color.ORANGE Color.BLUEColor.LIGHT_GRAY Color.YELLOWColor.WHITE Color.MAGENTA

DTEL DTEL

385

385

� For compatibility with older programs (before the naming conventions were established), Java also allows color names in lowercase: Color.black, Color.darkGray, etc.

Page 386: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Color Class Description

Color code values1)Color.red2)Color.green3)Color.blue4)Color.black

6)Color.yellow7)Color.cyan

DTEL DTEL

386

386

7)Color.cyan8)Color.magenta9)Color.pink10)Color.orange

All the above variables are present in Color class declared as static and final therefore we can access all the variables by using classname but we can’t change the value of above variables.

Page 387: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Color Class Description

Constructor of Color class-:

� Color(int red,int green,int blue);

� Where

� red value varies from 0 to 255

� green value varies from 0 to 255

� blue value varies from 0 to 255

� Every color is a mix of red, green, and blue

� You can make your own colors:

new Color( red , green , blue )

DTEL DTEL

387

387

new Color( red , green , blue )

� Amounts range from 0 to 255

� Black is (0, 0, 0), white is (255, 255, 255)

� We are mixing lights, not pigments

� Yellow is red + green, or (255, 255, 0)

Page 388: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Color Class

1)Color c=new Color(255,0,0);

Red

2)Color c=new Color(0,255,0);

Green

3)Color c=new Color(0,0,255);

Blue

4)Color c=new Color(127,0,0);

Dark red

5)Color c=new Color(0,127,0);

Dark green

Example

DTEL DTEL

388

388

Dark green

6)Color c=new Color(0,0,127);

Dark blue

7)Color c=new Color(192,192,192);

Light gray

8)Color c=new Color(127,127,127);

Dark gray

Page 389: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Setting And Getting Background Color

� It is used to set the background color of an applet’s window

� Syntax:- void setBackground(Color newColor);

� Here, newColor specifies the new color

� For example:- setBackground(Color.red);

� This will set the background color to red.

� A good place to set the background colors is in the init() method.

� You can obtain the current settings for background colors by calling

getBackground();

� Syntax:- Color getBackground();

Description

DTEL DTEL

389

389

� Syntax:- Color getBackground();

Page 390: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Setting And Getting Background Color Example

WAP to change background color of applet window

/*<applet code="p2" width=300 height=300></applet>*/import java.applet.*;import java.awt.*;public class p2 extends Applet{public void init(){

DTEL DTEL

390

390

{setBackground(Color.red);}}

Page 391: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Setting And Getting Background Color Output

DTEL DTEL

391

391

Page 392: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Setting And Getting Foreground Color Description

� It is used to set the foreground color (the color in which text is shown).

� Syntax:- void setForeground(Color newColor);

� Here, newColor specifies the new color

� For example:- setForeground(Color.red);

� This will set the text color to red.

� A good place to set the background colors is in the init() method.

� The default foreground color is black.

� You can obtain the current settings for foreground colors by calling

getForeground();

Syntax:- Color getForeground();

DTEL DTEL

392

392

� Syntax:- Color getForeground();

Page 393: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Setting And Getting Foreground Color

WAP to change background and foreground color of applet

window

Example

/*<applet code="p4" width=300 height=300></applet>*/import java.applet.*;import java.awt.*;public class p4 extends Applet{public void init()

DTEL DTEL

393

393

public void init(){setBackground(Color.yellow);setForeground(Color.red);}public void paint(Graphics g){g.drawString("SDMP",50,50);}}

Page 394: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Setting And Getting Foreground Color Output

DTEL DTEL

394

394

Page 395: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Setting a color Description

� To use a color, we tell our Graphics g what color we want:

� g.setColor(Color.RED);

� g will remember this color and use it for everything until we tell it some

different color

DTEL DTEL

395

395

Page 396: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Passing Parameters to Applets Description

� The Applet tag in an HTML document allows to pass the

� arguments to the applet using param tag

� SYNTAX:-

<applet code=“Program1” height=300 width=300>

<param name=var value=“val”>

</applet>

� To retrieve these arguments we use getParameter() method of Applet

DTEL DTEL

396

396

� To retrieve these arguments we use getParameter() method of Applet

class

� SYNTAX:- String getParameter(“var”);

Page 397: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Passing Parameters to Applets

WAP to accept a string using param tag and display it an

applet

Example

/*<applet code="p9" width=300

height=300>

<param name="str" value=“Welcome to

applet programming">

</applet>*/

import java.applet.*;

import java.awt.*;

public void init()

{

msg=getParameter("str");

if(msg==null)

msg=“Java”;

}

DTEL DTEL

397

397

import java.awt.*;

public class p9 extends Applet

{

String msg;

public void paint(Graphics g)

{

g.drawString(msg,10,100);

}

}

Page 398: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Passing Parameters to Applets Output

DTEL DTEL

398

398

Page 399: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Using the Status Window Description

� An Applet can also output a message to the status window of the browser or

applet viewer on which it is running.

� To do so we call showStatus() with the string that you want to display

� SYNTAX:- showStatus(String msg);

DTEL DTEL

399

399

Page 400: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Using the Status Window Example

WAP to show any message in status bar of applet window

DTEL DTEL

400

400

This is the status bar

Page 401: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Using the Status Window

/*<applet code="p8" width=300 height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class p8 extends Applet

{

public void paint(Graphics g)

{

Example

DTEL DTEL

401

401

{

showStatus("This is my status bar");

}

}

Page 402: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Using the Status Window Output

DTEL DTEL

402

402

Page 403: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Using the Status Window Example

Write an applet program that accepts two input string using <param> tag and

concatenate the strings and display it in status window.

/*<applet code="append" width=300

height=300>

<param name="string1" value="Wel">

<param name="string2" value="come">

</applet>*/

import java.applet.*;

import java.awt.*;

public class append extends Applet

public void init()

{

msg1=getParameter("string1");

msg2=getParameter("string2");

}

public void paint(Graphics g)

{

showStatus(msg1+msg2);

DTEL DTEL

403

403

public class append extends Applet

{

String msg1,msg2;

showStatus(msg1+msg2);

}

}

Page 404: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Using the Status Window Output

DTEL DTEL

404

404

Page 405: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Font Class Description

� Fonts are encapsulated by the Font class.

� Creating a Font

� To select a new font, you must first construct a Font object that describes that

font.� Font CONSTRUCTOR has this general form:� Font(String fontName, int fontStyle, int pointSize);� Here, fontName specifies the name of the desired font� fontStyle specifies style of the font� fontStyle can consist of one of these three constants:� 1)Font.PLAIN

DTEL DTEL

405

405

� 1)Font.PLAIN� 2)Font.BOLD� 3)Font.ITALIC� pointSize specifies size of the font in points.� Selecting a Font

� To use a font that you have created you must set it using setFont(), method

which is defined by Component

� SYNTAX: void setFont(Font fontObj);

� Here fontObj is the object that contains the desired font.

Page 406: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Font Class

WAP to display text in font arial, style italic, size as 50

Example

/*<applet code="p1" width=300 height=300></applet>*/import java.applet.*;import java.awt.*;public class p1 extends Applet{Font f;public void init(){

DTEL DTEL

406

406

{f=new Font("Arial",Font.ITALIC,50);setFont(f);}public void paint(Graphics g){g.drawString("hello",100,200);}}

Page 407: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Font Class Example

DTEL DTEL

407

407

Page 408: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 5:-Font Class

WAP to display text in font century ,style bold ,size as 50

Example

DTEL DTEL

408

408

Page 409: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Graphics Function Description

1) Line

• Syntax for function-:g.drawLine(int x1,int y1,int x2,int y2);

• The drawLine() method is used to draw line which takes two pair of

coordinates (x1,y1) and (x2,y2) as arguments and draw a line between them.

y1

Applet

(0,0)

DTEL DTEL

409

409

x2

y2x1

y1(0,0)

Page 410: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Graphics Function Description

2) Rectangle

• Syntax for function-:g.drawRect(int x1,int y1,int width,int height);

• The drawRect() method draws the rectangle. It takes four arguments first two

x and y coordinates represents top left corner of rectangle and remaining two

represents the width and height of rectangle in pixels.

Applet

DTEL DTEL

410

410

width

heightx1

y1Applet

(0,0)

Page 411: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Graphics Function Description

3) Rounded Rectangle

• Syntax for function-:g.drawRoundRect(int x1,int y1,int width,int height,int

xdiameter,int ydiameter);

• The drawRoundRect() method draws the rounded rectangle. Its takes six

parameters, the first four arguments are same as drawRect() and next

parameters are xdiameter and ydiameter.

Applet

DTEL DTEL

411

411

width

heightx1

y1

Applet(0,0)

Page 412: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Graphics Function Description

• Example

ydiameter

Case 1) xdiameter=ydiameter

Rounded Rectangle

DTEL DTEL

412

412

xdiameter

Page 413: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 6:-Graphics Function Description

• Case 2) xdiameter>ydiameter Case 3) xdiameter<ydiameter

Rounded Rectangle

DTEL DTEL

413

413

Page 414: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Description

4) Oval

• Syntax for function-:g.drawOval(int x1,int y1,int width,int height);

• ThedrawOval() method can be used to draw a circle or an

ellipse.ThedrawOval() method takes four arguments; the first two represents

the top left corner of the imaginary rectangle and the others two represent

the width and height of the oval itself.

Applet

DTEL DTEL

414

414

width

heightx1

y1

Applet(0,0)

Page 415: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Description

• Case 1) width=height

• Case 2) width>heightheight

Oval

DTEL DTEL

415

415

• Case 2) width>height

• Case 3) width<height height

width

width

Page 416: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Example

Write the applets to draw square inside a circle.

/*<applet code="RectOval" width=300

height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class RectOval extends Applet

DTEL DTEL

416

416

public class RectOval extends Applet

{

public void paint(Graphics g)

{

g.drawOval(100,100,100,100);

g.drawRect(120,120,60,60);

}

}

Page 417: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Description

5) Arc

• Syntax for function-:g.drawArc(int x1,int y1,int width,int height,int starting

angle,int sweep angle);

• The drawArc() method is used to draw arcs which takes six arguments, the

first two represents the top left corner of the imaginary rectangle and the

others two represent the width and height of the oval itself and the last two

represent the starting angle and the number of degrees(sweep angle) around

the arc.Applet

DTEL DTEL

417

417

width

heightx1

y1

Applet(0,0)

Page 418: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Description

• Anticlockwise

90

Arc

DTEL DTEL

418

418

0

180

270

Page 419: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Description

• Case 1)

90 Starting angle=90

Sweep angle=90

Arc

DTEL DTEL

419

419

Page 420: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Description

• Case 2)

90 Starting angle=90

Sweep angle=180

Arc

DTEL DTEL

420

420

Page 421: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Description

• Case 3)

90 Starting angle=180

Sweep angle=90

Arc

DTEL DTEL

421

421

Page 422: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Description

6) Fill Rectanlge

• To draw a filled rectangle use the following method

• Syntax for function-:g.fillRect(int x1,int y1,int width,int height);

Applet

DTEL DTEL

422

422

width

heightx1

y1

Applet(0,0)

Default filling

color is black

Page 423: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 7:-Graphics Function Example

Write simple applet draw a rectangle which is filled with Red color.

/*<applet code="FillRect" width=300

height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class FillRect extends Applet

DTEL DTEL

423

423

public class FillRect extends Applet

{

public void paint(Graphics g)

{

g.setColor(Color.red);

g.fillRect(100,100,100,50);

}

}

Page 424: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Graphics Function Description

7) Fill Oval

• To draw a filled a circle or an ellipse use the following method

• Syntax for function-:g.fillOval(int x1,int y1,int width,int height);

Applet

DTEL DTEL

424

424

width

heightx1

y1

Applet(0,0)

Page 425: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Graphics Function Example

Write an applet which shows two concentric circles filled with red and yellow color

respectively.

/*<applet code="ConCir" width=300 height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class ConCir extends Applet

{

public void paint(Graphics g)

DTEL DTEL

425

425

public void paint(Graphics g)

{

g.setColor(Color.red);

g.fillOval(100,100,100,100);

g.setColor(Color.yellow);

g.fillOval(120,120,60,60);

}

}

Page 426: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Graphics Function Example

Design an applet which displays three circles one below the other and fill them

with red, green and yellow color respectively.

/*<applet code="threecircle"

width=300 height=300>

</applet>*/

import java.applet.*;

import java.awt.*;

public class threecircle extends Applet

{

public void paint(Graphics g)

DTEL DTEL

426

426

public void paint(Graphics g)

{

g.setColor(Color.red);

g.fillOval(100,50,50,50);

g.setColor(Color.green);

g.fillOval(100,120,50,50);

g.setColor(Color.yellow);

g.fillOval(100,190,50,50);

}}

Page 427: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Graphics Function Description

8) Fill Rounded Rectangle

• To draw a filled rounded rectangle use the following method

• Syntax for function-:g.fillRoundRect(int x1,int y1,int width,int height,int

xdiameter,int ydiameter);

y1Applet

(0,0)

DTEL DTEL

427

427

width

heightx1

y1(0,0)

Page 428: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Graphics Function Example

Write a program to create an applet for displaying different shapes.

(0,0) 50

50

50 300

(150,0)Applet

DTEL DTEL

428

428

50

50

50

50

100

300

300

(0,150)(300,150)

(150,300)

Page 429: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Graphics Function Example

/*<applet code="p4" width=300 height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class p4 extends Applet

{

public void paint(Graphics g)

{

//VERTICAL LINE

g.drawLine(150,0,150,300);

//CIRCLE

g.drawOval(50,50,50,50);

//Line

g.drawLine(200,50,250,100);

//Rectangle

g.drawRect(175,200,100,50);

//ARC

DTEL DTEL

429

429

{

//HORIZONTAL LINE

g.drawLine(0,150,300,150);

//ARC

g.drawArc(50,200,50,50,0,90);

}

}

Page 430: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 8:-Graphics Function Example

DTEL DTEL

430

430

Page 431: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

WAP to draw following graphical shape on the output screen of the applet window

Applet

300

DTEL DTEL

431

431

300

150

50R20R

Page 432: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

/*<applet code="p7" width=300 height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class p7 extends Applet

{

public void paint(Graphics g)

{

DTEL DTEL

432

432

{

g.drawOval(40,100,100,100);

g.drawOval(220,130,40,40);

g.drawLine(90,100,240,130);

g.drawLine(90,150,240,150);

g.drawLine(90,200,240,170);

}

}

Page 433: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

DTEL DTEL

433

433

Page 434: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

WAP to draw following graphical shape on the output screen of the applet window

Applet

300

DTEL DTEL

434

434

300

150

50R20R

Page 435: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

*<applet code="p6" width=300 height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class p6 extends Applet

{

public void paint(Graphics g)

{

g.setColor(Color.blue);

g.fillOval(40,100,100,100);

DTEL DTEL

435

435

g.fillOval(40,100,100,100);

g.setColor(Color.red);

g.fillOval(220,130,40,40);

g.setColor(Color.black);

g.drawLine(90,100,240,130);

g.drawLine(90,150,240,150);

g.drawLine(90,200,240,170);

}

}

Page 436: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

DTEL DTEL

436

436

Page 437: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

WAP to show shading effect on the output screen in the applet window

20

20256 shades of blue color

DARK BLUE

APPLET

300

DTEL DTEL

437

437

100

LIGHT BLUE

300

Page 438: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

/*<applet code="p5" width=300 height=300>

</applet>

*/

import java.applet.*;

import java.awt.*;

public class p5 extends Applet

{

public void paint(Graphics g)

{

int i,y;

y=20;

DTEL DTEL

438

438

y=20;

for(i=0;i<=255;i++)

{

Color c=new Color(0,0,i);

g.setColor(c);

g.drawLine(20,y,120,y);

y++;

}

}

}

Page 439: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 9:-Graphics Function Example

DTEL DTEL

439

439

Page 440: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

�Graphics function to draw polygon

�drawPolygon function draws polygon by joining x and y co-ordinate of the

‘n’ number of points stored in the xp and yp array.

�Syntax:- drawPolygon(xp,yp,n);

�fillPolygon function draws a filled polygon by joining x and y co-ordinate

of ‘n’ points stored in xp,yp array.

�Syntax:- fillPolygon(xp,yp,n);

DTEL DTEL

440

440

Page 441: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

import java.awt.*;

import java.applet.*;

public class Poly extends Applet

{

int x1[]={20,120,220,20};

int y1[]={20,120,20,20};

int n1=4;

public void paint(Graphics g)

{

g.drawPolygon(x1,y1,n1);

DTEL DTEL

441

441

g.drawPolygon(x1,y1,n1);

}

}

/*<applet code="Poly" width=300 height=300>

</applet>*/

Page 442: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

DTEL DTEL

442

442

Page 443: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

• int x1[]={20,120,220,20};

• int y1[]={20,120,20,20};

• int n1=4;

(220,20)

(20,20)

DTEL DTEL

443

443

(120,120)

Page 444: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

import java.awt.*;

import java.applet.*;

public class Poly extends Applet

{

int x1[]={20,120,220,20};

int y1[]={20,120,20,20};

int n1=4;

int x2[]={120,220,220,120};

int y2[]={120,20,220,120};

int n2=4;

DTEL DTEL

444

444

int n2=4;

public void paint(Graphics g)

{

g.drawPolygon(x1,y1,n1);

g.drawPolygon(x2,y2,n2);

}

}

/*<applet code="Poly" width=300 height=300>

</applet>*/

Page 445: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

DTEL DTEL

445

445

Page 446: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

• int x1[]={20,120,220,20};

• int y1[]={20,120,20,20};

• int n1=4;

• int x2[]={120,220,220,120};

• int y2[]={120,20,220,120};

• int n2=4;

(20,20) (220,20)

DTEL DTEL

446

446

• int n2=4;(120,120)

(220,220)

Page 447: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

Example to draw filled Polygon

import java.awt.*;

import java.applet.*;

public class Poly extends Applet

{

int x1[]={20,120,220,20};

int y1[]={20,120,20,20};

int n1=4;

int x2[]={120,220,220,120};

int y2[]={120,20,220,120};

int n2=4;

DTEL DTEL

447

447

int n2=4;

public void paint(Graphics g)

{

g.drawPolygon(x1,y1,n1);

g.fillPolygon(x2,y2,n2);

}

}

/*<applet code="Poly" width=300 height=300>

</applet>*/

Page 448: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

DTEL DTEL

448

448

Page 449: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

• int x1[]={20,120,220,20};

• int y1[]={20,120,20,20};

• int n1=4;

• int x2[]={120,220,220,120};

• int y2[]={120,20,220,120};

• int n2=4;

(220,20)(20,20)

(120,120)

DTEL DTEL

449

449

• int n2=4;

• pixel

(120,120)

(220,220)

Page 450: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Graphics Function Example

Design an applet which displays a triangle filled with red color and a message as ’The

triangle’ in blue below it.

import java.awt.*;

import java.applet.*;

public class triangle extends Applet

{

int x1[]={120,20,220,120};

int y1[]={20,120,120,20};

int n1=4;

public void paint(Graphics g)

DTEL DTEL

450

450

public void paint(Graphics g)

{

g.setColor(Color.red);

g.fillPolygon(x1,y1,n1);

g.setColor(Color.blue);

g.drawString("The Triangle",80,145);

}

}

/*<applet code="triangle" width=300 height=300>

</applet>*/

Page 451: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 10:-Applet Programming Description

Standard Classes required for Applet Programming

�Applet is a standard inbuilt class present in java.applet package containing all

the applet events and functions.

�Graphics is a class present in java.awt package which is used to perform all the

graphical operation in applet window.

�Color is a class present in java.awt package containing constructors and

methods which are used to generate color code numbers

DTEL DTEL

451

451

methods which are used to generate color code numbers

�Color class can generate 256*256*256 color.

Page 452: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-6 File I/O & Collection Framework

Topic 1: 1

Topic 2: 2

File Classes

Introduction to collections framework

DTEL DTEL 45

2

Page 453: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

CHAPTER-6 SPECIFIC OBJECTIVE / COURSE OUTCOME

1

The student will be able to:

The students will be able to work with File IO

DTEL DTEL 45

3

2They will also learn the concept of serialization.

Page 454: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-What is Java I/O? Description

� I/O = Input/Output

� In this context it is input to and output from programs

� Input can be from keyboard or a file

� Output can be to display (screen) or a file

� Advantages of file I/O

� permanent copy

� output from one program can be input to another

� input can be automated (rather than entered manually)

� The Java Input/Output (I/O) is a part of java.io package.

DTEL DTEL

454

454

� The Java Input/Output (I/O) is a part of java.io package.

� The java.io package contains a relatively large number of classes that

support input and output operations.

� The classes in the package are primarily abstract classes and stream-

oriented that define methods and subclasses which allow bytes to be read

from and written to files or other input and output sources.

� The InputStream and OutputStream are central classes in the package

which are used for reading from and writing to byte streams, respectively.

Page 455: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:- java.io Package Description

The java.io package can be categories along with its stream classes in a hierarchy

structure shown below:

Inputstream

ByteArrayInputStream

FileInputStream

ObjectInputStream

FilterInputStream

PipedInputStream

SequenceInputStream

DTEL DTEL

455

455

java.io

SequenceInputStream

StringBufferInputStream

OutputStream

ByteArrayOutputStream

FileOutputStream

FilterOutputStream

ObjectOutputStream

PipedOutputStream

Page 456: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Streams Description

� Stream: an object that either delivers data to its destination (screen, file,

etc.) or that takes data from a source (keyboard, file, etc.)

� it acts as a buffer between the data source and destination

� Input stream: a stream that provides input to a program

� System.in is an input stream

� Output stream: a stream that accepts output from a program

� System.out is an output stream

DTEL DTEL

456

456

� System.out is an output stream

� A stream connects a program to an I/O object

� System.out connects a program to the screen

� System.in connects a program to the keyboard

Page 457: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Classification of java stream classes Description

Java stream classes

Byte Character

DTEL DTEL

457

457

Input Output Reader Writer

Page 458: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Byte Stream Class & Character Stream Class Description

S.N. Byte Stream Class Character Stream Class

1 Byte stream access the file byte

by byte (8 bits)

A character stream will read a file

character by character (16 bit)

2 Byte stream classes are

classified into:

i. Input Stream Classes

ii. Output stream Classes

2. Character stream classes are

classified into:

i. Reader class

ii. Writer class

DTEL DTEL

458

458

Page 459: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Input Stream Class & Reader Class Description

S.N. Input Stream Class Reader Class

1 Input Stream are used to

read bytes from a stream.

Reader Classes are used to read

characters from a stream.

2 Input Stream are used to

read 8 bits.

Reader Classes are used to read 16 bit

unicode character stream.

3 Input Stream class is

useful for binary data

Reader classes are best used to read

character data.

DTEL DTEL

459

459

useful for binary data

such as images, video and

serialized objects

character data.

Page 460: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 1:-Output Stream Class &Writer Class Description

S.N. Output Stream Class Writer Class

1 Output streams are used to write

bytes to stream

Writer classes are used to write

character streams

2 Output streams are used to write

8 bit

Writer classes are used to write 16

bit unicode character streams

DTEL DTEL

460

460

Page 461: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-System Class Description

Variable Type Purpose

err PrintStream The “standard error” output

stream. This stream is already

open and ready to accept

output data.

in InputStream The “standard input” stream.

This stream is already open and

Data Fields in the System Class

DTEL DTEL

461

461

This stream is already open and

ready to supply input data.

out Printstream The “standard output” stream.

This stream is already open and

ready to accept output data.

Page 462: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-File Class

� It is present in java.io package

� A file can be created using File class

� It is used find properties of given file

Constructor

� File(File parent, String child)

Creates a new File instance from a parent(directory name) abstract

pathname and a child pathname string.

� File(String pathname)

Description

DTEL DTEL

462

462

� File(String pathname)

Creates a new File instance by converting the given pathname string

into an abstract pathname.

� File(String parent, String child)

Creates a new File instance from a parent pathname string and a child

pathname string.

Page 463: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-File Class

WAP to find the properties of a given file,where filename is input through

the command line argument

Example

import java.io.*;

class Myfile1

{

public static void main(String args[])

{

if(args.length==1)

{

System.out.println("Can Read="+f.canRead());

System.out.println("Can Write="+f.canWrite());

System.out.println("Is File="+f.isFile());

System.out.println("Is

Directory="+f.isDirectory());

System.out.println("File

size="+f.length()+"Bytes");

DTEL DTEL

463

463

{

File f=new File(args[0]);

System.out.println("File

Name="+f.getName());

System.out.println("Parent

Directory="+f.getParent());

System.out.println("File Path="+f.getPath());

System.out.println("File Exist="+f.exists());

size="+f.length()+"Bytes");

}

else

System.out.println("Wrong Argument");

}

}

Page 464: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-File Class OUTPUT

C:\ javac Myfile1.java

C:\ java Myfile1 C:\Windows\setup.bmp

File Name=setup.bmp

Parent directory=C:\Windows

File Path=C:\Windows\setup.bmp

File Exist=true

Can Read=true

Can Write=true

Is File=true

DTEL DTEL

464

464

Is File=true

Is Directory=false

File size=308280 Bytes

Page 465: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-File Class

� Acts like a wrapper class for file names� A file name like "numbers.txt" has only String properties� File has some very useful methods

� exists: tests if a file already exists� canRead: tests if the OS will let you read a file� canWrite: tests if the OS will let you write to a file� delete: deletes the file, returns true if successful� length: returns the number of bytes in the file� getName: returns file name, excluding the preceding path� getPath: returns the path name—the full name

Description

DTEL DTEL

465

465

� getPath: returns the path name—the full nameFile numFile = new File(“numbers.txt”);if (numFile.exists())System.out.println(numfile.length());

Page 466: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 2:-Serialization Description

� Storing state of object into file is serialization

� Object state are converted into byte stream

� Reading the object state from stored file is de-serialization

DTEL DTEL

466

466

Page 467: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Collections Description

�A collection is a structured group of objects

�A Collection is a container that groups similar elements into an entity.

�Examples would include a list of bank accounts, set of students, group of telephone numbers.

�The Collections framework in Java offers a unified approach to store, retrieve and manipulate a group of data

DTEL DTEL

467

467

�Unified architecture for representing and manipulating collections.

�A collections framework contains three things�Interfaces�Implementations�Algorithms

Page 468: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Collections Framework Diagram Description

DTEL DTEL

468

468

•Interfaces, Implementations, and Algorithms

Page 469: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Collections Description

Collection

Set List Queue

SortedSet

Map

SortedMap

DTEL DTEL

469

469

The Collection framework forms a suitable hierarchy

Page 470: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Collection Interface Description

The Collection interface is used to represent any group of objects, or elements.

Methods:

1. public boolean add(object element)2. public boolean remove(object element)3. public int size()4. public void clear()5. public boolean contains(object element)6. boolean equals(object o)

DTEL DTEL

470

470

6. boolean equals(object o)

Page 471: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- List Interface Description

�This is an ordered collection(also known as a sequence) much like an array

�The List Interface extends the Collection Interface.

�Duplicate elements are allowed within the collection and position-oriented

operations are permitted.

�Lists grow automatically when needed

�The list interface provides accessor methods based on index

DTEL DTEL

471

471

�The list interface provides accessor methods based on index

�Types of Lists�ArrayList�LinkedList�Vector�Stack

Page 472: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-ArrayList Class Description

�ArrayList is roughly equivalent to Vector except that its methods are not synchronized

�Extends AbstractList

� Auto-resizeable.

� Based on a simple array.

DTEL DTEL

472

472

� Permits the null element.

�Methods

�void add(int index,E element)�E remove(int index)�void clear()�boolean contains(Object o)�int size()

Page 473: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- LinkedList Class Description

� LinkedList implements a doubly linked list of elements

�Similar to ArrayList

� Different implementation based on nodes that contain data and links to other nodes

� Stores each element in a node

� Each node stores a link to the next and previous nodes

DTEL DTEL

473

473

� Insertion and removal are inexpensive

�just update the links in the surrounding nodes

�Linear traversal is inexpensive

�Random access is expensive

�Start from beginning or end and traverse each node while counting

�Methods are not synchronized

Page 474: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- LinkedList Class Description

�Methods are as follows:

�void add(int index,E element)

�void clear()

�boolean contains(Object o)

�E remove()

DTEL DTEL

474

474

�int size()

Page 475: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Vector Description

�The package java.util contains a library of Java’s utility classes.

� One of them is Vector class.

� It implements a dynamic array which can hold the array of any type and any number.

�Capacity of the Vector can be increased automatically.

�It is used to add dissimilar type of element/object.

�Creation of Vector

Vector class defines three different constructors:

�Vector()

The first form creates a default vector, which has an initial size of 10.

DTEL DTEL

475

475

�Vector(int size)

The second form creates a vector whose initial capacity is specified by ‘size’

�Vector(int size, int incr)

The third form creates a vector whose initial capacity is specified by ‘size’ and whose

increment is specified by ‘incr’. The increment specifies the number of elements to

allocate each time when new elements are added in the vector.

Page 476: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Vector Description

S.N. Method Task Performed

1 void addElement(Object obj) Adds the specified component to the

end of this vector, increasing its size

by one

2 int capacity() Returns the current capacity of this

vector.

DTEL DTEL

476

476

3 int size() Returns the number of components

in this vector.

4 boolean contains(Object elem) Tests if the specified object is a

component in this vector.

5 Object elementAt(int index) Returns the component at the

specified index.

Page 477: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Vector Description

S.N. Method Task Performed

6 Enumeration elements() Returns an enumeration of the

components of this vector.

7 Object firstElement() Returns the first component

(the item at index 0) of this

vector.

8 Object lastElement() Returns the last component of

the vector.

DTEL DTEL

477

477

9 int indexOf(Object elem) Searches for the first

occurrence of the given

argument, testing for equality

using the equals method.

10 void insertElementAt(Object obj,

int index)

Inserts the specified object as a

component in this vector at the

specified index.

Page 478: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Vector Description

S.N. Method Task Performed

11 Object remove(int index) Removes the element at the specified

position in this Vector.

12 void

removeElementAt(int index)

Deletes the component at the specified

index.

13 Object set(int index,

Object element)

Replaces the element at the specified

position in this Vector with the specified

DTEL DTEL

478

478

Object element) position in this Vector with the specified

element.

14 void clear() Removes all of the elements from this

Vector.

Page 479: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-Stack Class Description

�Extends Vector

� “Last in, First Out” behavior

� Contains methods to allow typical Stack behaviors. (ie: push(), pop(), etc. )

�Methods are follows:

�boolean empty()

DTEL DTEL

479

479

�Object pop()

�Object push(Object element)

�int search(Object element)

Page 480: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- Set Interface Description

�A set is a collection in which:�There are no duplicate elements (according to equals), and�Order is not important

�The Set Interface extends the Collection Interface.�Types of Sets

�HashSet

�LinkedHashSet

�TreeSet

DTEL DTEL

480

480

�TreeSet

Page 481: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:- SortedSet Interface Description

�SortedSet provides the same mechanisms as the Set interface, except that SortedSets maintain the elements in ascending order.

�SortedSet stores elements in ascending order as per the natural ordering or as defined by a comparator provided at instantiation time.

�Ordering is based on natural ordering (Comparable) or by using a Comparator.

DTEL DTEL

481

481

Page 482: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-HashSet Class Description

�A hash table stores information by using a mechanism called hashing

�It does not guarantee that the order will remain constant over time.

�Find and add elements very quickly

�uses hashing implementation in HashMap

�Hashing uses an array of linked lists

�Methods are as follows:

�boolean add(Object o)

DTEL DTEL

482

482

�void clear()

�boolean contains(Object o)

�boolean remove(Object o)

�int size()

Page 483: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 3:-TreeSet Class Description

�Elements can be inserted in any order

�The TreeSet stores them in order

�An iterator always presents them in order

�Default order is defined by natural order

�Methods are as follows:

DTEL DTEL

483

483

�boolean add(Object o)

�void clear()

�boolean contains(Object o)

�boolean remove(Object o)

�int size()

Page 484: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-The Map interface Description

�A map is a data structure for associating keys and values.

The collection is kept in key/value pairs. Any object can be a key or value. No duplicate keys allowed.�The Map interface provides the basis for dictionary or key-based collections in Java.

�Stores key/value pairs

�Maps from the key to the value

�Keys are unique

�a single key only appears once in the Map

�a key can map to only one value

�Values do not have to be unique

DTEL DTEL

484

484

�Values do not have to be unique

� Java provides 3 concrete classes which implement the list interface

� HashMap

� LinkedHashMap

� TreeMap

Page 485: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-The Map interface Description

Methods

� void clear()

�boolean containsKey(Object key)

�boolean containsValue(Objectvalue)

�Object get(Object key)

DTEL DTEL

485

485

�Object put(Object key,Obejct value)

�int size()

Page 486: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-The SortedMap interface Description

�A sorted map is a map that keeps the keys in sorted order.�Organizes data in ascending order based on natural ordering of the keys or a comparator supplied at instantiation time.

�Methods

� Object firstKey()

� Object lastKey()

DTEL DTEL

486

486

Page 487: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Map Implementations Description

Map

DTEL DTEL

487

487

HashMap TreeMap Linkedlist HashTable

Performance Increases

Page 488: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:- HashMap Class Description

� HashMap is the most commonly used Map.Provides access to elements through a key.The keys can be iterated if they are not known

� The keys are a set - unique, unordered� Fast� Permits the null element.� Makes no guarantees as to the iteration order of the set.

Methods

DTEL DTEL

488

488

Methods� void clear()

�boolean containsKey(Object key)

�boolean containsValue(Objectvalue)

�Object get(Object key)

�int size()

Page 489: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-TreeMap Class Description

�The keys are a set - unique, ordered�Same options for ordering as a TreeSet�Keys can be kept in acscending order

Methods

� void clear()

�boolean containsKey(Object key)

DTEL DTEL

489

489

�boolean containsValue(Objectvalue)

�Object get(Object key)

�Object put(Object key,Obejct value)

�int size()

Page 490: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-java.util package Description

Classes�Dictionary�HashTable�Properties�Stack�Vector

Interface

DTEL DTEL

490

490

Interface�Enumeration

Page 491: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Enumeration Interface Description

�The Enumeration interface is used to obtain a series of elements, one at a time

in a collection of objects.

�Successive calls to the nextElement method return successive elements of the

series.

Method

�boolean hasMoreElements()

Tests if this enumeration contains more elements.

�Object nextElement()

Returns the next element of this enumeration if this enumeration object

DTEL DTEL

491

491

Returns the next element of this enumeration if this enumeration object

has at least one more element to provide.

Page 492: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Hashtable Description

� A hashtable is a data structure that organizes data based on a user defined key structure.

� Hash tables typically make use of hash codes, which are computed, keys that uniquely identify each element in the hash table.

�A Hash table will expand in size as elements are added to it.

DTEL DTEL

492

492

Page 493: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Date Class Description

�The java.util.Date class represents a specific instant in time, with millisecond precision.

�Constructor

�1Date()This constructor allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

DTEL DTEL

493

493

�2Date(long date)This constructor allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Page 494: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Date Class Description

S.N. Method & Description

1 boolean after(Date when)

This method tests if this date is after the specified date.

2 boolean before(Date when)

This method tests if this date is before the specified date.

3 long getTime( )

Returns the number of milliseconds that have elapsed since January 1, 1970.

4 void setTime(long time)

DTEL DTEL

494

494

4 void setTime(long time)

Sets the time and date as specified by time, which represents an elapsed time

in milliseconds from midnight, January 1, 1970

Page 495: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-Date Class Example

import java.util.*;public class DateExample{public static void main(String args[]){Date d=new Date();System.out.println(d);}}

DTEL DTEL

495

495

Page 496: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

LECTURE 4:-The Iterator Interface Description

�An iterator is an object that will return the elements of a collection, one at a

time.

�Defines three fundamental methods

�Object next()

�boolean hasNext()

�void remove()

�These three methods provide access to the contents of the collection

DTEL DTEL

496

496

�These three methods provide access to the contents of the collection

�An Iterator knows position within collection

�Each call to next() “reads” an element from the collection

�Then you can use it or remove it

Page 497: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

RECOMMENDED BOOKS

1. The Complete Reference Java Seventh Edition By Herbert Schildt

2. Computer Programming in JAVA By Junaid Khateel & Dr. G. T. Thampi

3. Core JAVA for Beginners By Sharnam Shah & Vaishali Shah

DTEL DTEL

497

497

3. Core JAVA for Beginners By Sharnam Shah & Vaishali Shah

4. Programming in JAVA a primer By E Balagurusamy

5. Core Java for beginners By Rashmi Kanta Das

Page 498: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

REFERENCE BOOKS

1. Programming in JAVA By Sachin Malhotra & Saurabh Chaudhary

2. Java 7 Programming - Black Book By Kogent Learning Solutions Inc.

3. Core Java: An Integrated Approach By R. Nageswara Rao

DTEL DTEL

498

498

3. Core Java: An Integrated Approach By R. Nageswara Rao

4. Java Fundamentals By Gary Marrer

5. Java: Classes in Java Applications By David Etheridge

Page 499: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

REFERENCE WEB

1. http://www.tutorialspoint.com/java/

2. http://www.slideshare.net/kakkarlokesh/core-java-complete-notes

3. http://www.learnjavaonline.org/

DTEL DTEL

499

499

4. https://www.udemy.com/java-tutorial/

5. http://www.java2s.com/Tutorial/Java/CatalogJava.htm

6. http://www.learn-java-tutorial.com/

Page 500: sdmp.ac.insdmp.ac.in/DTLE/JAVA PROGRAMMING 6TH SEM CM-IF [Compatibili… · LECTURE 1:-Compilation Process Description Java compiler (javac) is used to compile any java file. Java

THANK YOUTHANK YOU

JAVA PROGRAMMING

DTEL DTEL 500