JavaClassPresentation

72
Welcome To Programming in JAVA By Mr. A. Julias Ceasor Bosco Institute of Information Technology James Gosling

description

 

Transcript of JavaClassPresentation

Page 1: JavaClassPresentation

WelcomeTo

Programming in JAVA

By

Mr. A. Julias CeasorBosco Institute of Information

Technology

James Gosling

Page 2: JavaClassPresentation

Java Basics:OOP and Java - Objects and Classes – Encapsulation - Inheritance - Polymorphism - Java Language - The Primaries - Character Set - Tokens - Constants - Variables - Operators and Expressions - Library Methods - Strings - I/O Streams - Formatting the Output values - Control Statements – If - Switch - While - Do-While-for.

After this unit will be over, you will be the Know-how of the followings:

Page 3: JavaClassPresentation

Java Fundamentals & Basics for Programming

What is Java?Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look and feel" of the C++ language, but it is simpler to use than C++ and enforces an object-oriented programming model.

Key Concept of Java:• Java Technology is:- Simple, Secure, Robust, Complete Object Oriented and Platform Independent High level Language.- It is portable and Multi-thread technology gives High performance.• It is based on concept called JVM.- Act as a translator between the language and the underlying Software and Hardware.

Page 4: JavaClassPresentation

Objects

What is Object Oriented Programming?• This is a technique used to develop programs revolving around the real world entities. • In OOPs programming model, programs are developed around data rather than actions and logics.• In OOPs, every real life object has properties and behavior. • It contains properties (variables of some type) and behavior (methods). • OOPs provides a better flexibility and compatibility for developing large applications.

What is object?• Object is a real world entity.• the Real world Objects are: Building,Car, Fruit,… and etc.

Page 5: JavaClassPresentation

An Object

Attributes:• Four Wheels• Engine• Seats• Steering• Speed• Disk Break• Etc.

Car

Functionalities (Methods):+Wheels for Rolling+ Engine for Moving+Seats for Sitting+Break for Control+Etc.

Page 6: JavaClassPresentation

Programming Object:- It is combination of Data and Methods.

Data

Method

Method

Method

Method

Attributes of an object

(-) Functionalities of an Object

(+)

Object = Data + Methods

An Object

Page 7: JavaClassPresentation

Pillars of OOPL:

O O P L

Inheritance Encapsulation PolymorphismDynamic Binding

Page 8: JavaClassPresentation

Why the Java?• C, C++ and other programming languages are not flexible for complex problems.• Other languages are Structured and Object Oriented Programming language. Not Fully OOPL.• Others are not Platform Independent.

Evolution of Java• In 1990, the group of engineers developed a software for consumer electronics at Sun micro System of USA.• This group is headed by James Gosling.• In 1991, it is proved that it satisfy the concepts of OOPL like C++ and called as 'Oak' by James Gosling.• In 1992, the Green Project is started.• In 1993, the team developed small applet program for World Wide Web.• In 1994, the team came up with browser called HotJava.• In 1995, the 'Oak' renamed as 'Java'

Page 9: JavaClassPresentation

Why is it named 'Oak'?When the 'Ever green' team was Developed Software for consumer Electronics, such as Set-Top-Boxes, and Other hand held devices, the Head of the team James Gosling saw a Oak tree in front of his office.The Oak tree is a ever green tree and never its leaves get dry. Due to this reason, the software named as 'Oak'.

Page 10: JavaClassPresentation

Features of Java:• Java is:

simple easy to design easy to write and therefore easy to compile debug and learn than any other programming languages.

• Java is object-oriented, that is used to build modular programs and reusable code in other application.

• Java is platform-independent and flexible in nature.

• The most significant feature of Java is to run a program easily from one computer system to another. 

Page 11: JavaClassPresentation

Continued…..

• Java works on distributed environment.

• Java is secure. The Java language, compiler, interpreter and runtime environment are  securable .

• Java is robust. Robust means reliability.

• Java  emphasis on  checking for possible errors.

• Java supports multithreaded. Multithreaded is the path of execution for a program to perform several tasks simultaneously within a program.

Page 12: JavaClassPresentation

Java Platform:• Platform  is cross-combination of  hardware or software environment in which a program runs.

Hardware Platform

Java Platform

Software (OS) Platform

Operates and

Controls H/W

Environment for Java

Development

Page 13: JavaClassPresentation

Java Platform:• Java Platform has Two Components.1. Java Virtual Machine (JVM)2. Java Application Programming Interface (API)

JVM API

Page 14: JavaClassPresentation

JVM: The Java Virtual Machine is the root for the Java platform and is integrated into various hardware-based platforms.

API: The API is a vast collection of various software components that provide you many useful functionality to the application.It is grouped into logical collection  of related classes and interfaces; these logical collection  are known as packages.

Page 15: JavaClassPresentation

How it Works:

•All source code is  written in  text files (Notepad Editor) save with the .java extension • The source files are compiled into .class files by the java

compiler. A .class file  contains byte codes • The java launcher tool  runs your application with an instance of

the Java Virtual Machine.

Page 16: JavaClassPresentation

Execution of Program as Platform Independent

Page 17: JavaClassPresentation

A simple Java Program:HelloWorld.java

import java.io.*;

class HelloWorld{public static void main(String args[]){System.out.println("HelloWorld");}}

Output:HelloWorld

Page 18: JavaClassPresentation

Procedure for developing java application1. Write a java source code as a text file (can create in notepad) using

any of the text editor.• Save the file with .java extension in your directory.• The filename should be the class name of the program.• Open the command prompt to run the application• Compile the code with command javac filename.java• Run the class file with the command java filename• The output will be displayed on your console.

Page 19: JavaClassPresentation

Two ways of using Java

Java Source Code

Java Compiler

Java Enabled

Web Browser

Java Interpreter

Output Output

Applet Type Application Type

Page 20: JavaClassPresentation

Java Technology:On full implementation of the Java platform gives you the following features:

JDK Tools: The JDK tools provide  compiling, Interpreter, running, monitoring, debugging, and documenting your applications.  The main tools used are the Javac compiler, the java launcher, and the javadoc documentation tool. Application Programming Interface (API): The API provides the core functionality of the Java programming language.

Deployment Technologies: The JDK software provides two type of deployment technology such as the Java Web Start software and Java Plug-In software for deploying your applications to end users. 

Graphical User Interface Toolkits: The Swing and Java 2D toolkits provide us the feature of  Graphical User Interfaces (GUIs).

Integrated Libraries: Integrated with various libraries such as the Java IDL API, JDBC API, Java Naming and Directory Interface TM ("J.N.D.I.") API, Java RMI, and Java Remote Method Invocation over Internet.

Page 21: JavaClassPresentation

Structure of Java Program

Documentation Section

Package Statements

Import Statements

Interface Statements

Class Definitions

Main Method Class{Main method Definition}

A set of comment lines giving the name of the program, author and other details./**…….*/ or // or /*…..*/

Declare the package names and inform the compiler the class defined below belongs to this packages. e.g.: package student;

Instruct the interpreter to load the test class contained in Student package. E.g. import student.test;Includes a group of methods declarations.

Can have multiple class declarations.

Creates objects of various classes and establishes communication between them.

Page 22: JavaClassPresentation

Java Virtual Machine:• All language compiler translate source code into machine code for specific computer.• Java compiler produces an intermediate code known as bytecode for a machine that does not exist.• This machine is called Java Virtual Machine (JVM)• It is simulated computer with in a computer does all major functions.• the bytecode is called as virtual machine code.• this is not machine specific.• Machine specific code is generated by Java Interpreter by acting as intermediary between the virtual machine and real machine.• Illustrated below.

Java Progra

m

Virtual Machin

eSource code

Bytecode

Java Compiler

Process of Compilation:

Page 23: JavaClassPresentation

Java Interpreter

Virtual Machine

Real Machine

Bytecode

Process of Converting bytecode into machine code

Machine Code

Page 24: JavaClassPresentation

Classes and Objects:Class:A class is a programming language construct that is used as a blueprint to create objects. This blueprint describes the state and behavior that the created objects all share.

E.g.: Bicycles

• There may be thousands of other bicycles in existence, all of the same make and model.

• Each bicycle was built from the same set of blueprints and therefore contains the same components.

• In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.

• A class is the blueprint from which individual objects are created.

Page 25: JavaClassPresentation

The following Bicycle class is one possible implementation of a bicycle:

class Bicycle {

int cadence = 0; int speed = 0; int gear = 1;

void changeCadence(int newValue) { cadence = newValue; }

void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); }

}

Page 26: JavaClassPresentation

• The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.

• It is just the blueprint for bicycles that might be used in an application

Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:

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

// Create two different Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle();

// Invoke methods on those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates();

bike2.changeCadence(40); bike2.speedUp(10);bike2.changeGear(3);bike2.printStates(); } }

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:cadence:50 speed:10 gear:2 cadence:40 speed:20 gear:3

Page 27: JavaClassPresentation

Object:Object is the basic entity of object oriented programming language. Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (variables) and uses the behavior (methods) defined in the class. 

E.g.: Bicycle

• Real-world objects share two characteristics: They all have state and behavior.

• Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).

• Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes).

• Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

• Ask yourself: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations.

Page 28: JavaClassPresentation

• An object stores its state in fields (variables in some programming languages)

• And exposes its behavior through methods (functions in some programming languages).

Data Encapsulation: Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

A Software Object

Page 29: JavaClassPresentation

Bundling code into individual software objects provides a number of benefits, including:

Modularity:The source code for an object can be written and maintained independently of the source code for other objects. Information-hiding:By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. Code re-use:If an object already exists (perhaps written by another software developer), you can use that object in your program.Pluggability and debugging ease:If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement.

Page 30: JavaClassPresentation

Main Pillars of OOP:Encapsulation:• Abstraction: Hiding the information (Complexities) to the end users. E.g.: User Driving a Car.• Encapsulation is the process of binding together the methods and

data variables as a  single entity. • It keeps both the  data and functionality code safe  from the

outside world. • It hides the data within the class and makes it available only

through  the methods. • Java provides different accessibility scopes (public, protected,

private ,default) to hide the data from outside.

Example:Here we create a class "Check" which has a variable "amount" to store the current amount. To manipulate  this variable we create a methods and to set the value of amount we create setAmount() method and to get the value of amount we create getAmount() method .

Page 31: JavaClassPresentation

class Check{  private int amount=0;  public int getAmount(){     return amount;  }  public void setAmount(int amt){     amount=amt;  } } public class Mainclass{  public static void main(String[] args){     int amt=0;     Check obj= new Check();     obj.setAmount(200);     amt=obj.getAmount();      System.out.println("Your current amount is :"+amt);     }}

Here the data variable "amount" and methods setAmount() and  getAmount() are enclosed together with in a single entity called the "Check" class.

Page 32: JavaClassPresentation

Inheritance: • Inheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass). • In java, a class can inherit only one class (superclass) at a time

but a class can have any number of subclasses. • It helps to reuse, customize and enhance the existing code. • So it helps to write a code accurately and reduce the

development time. Java uses extends keyword to extend a class.

Class A

Class B

Fun 1

Fun 2

Extends

Class B inherits the property of

class A

Page 33: JavaClassPresentation

class A{  public void fun1(int x){     System.out.println("Int in A is :" + x);  }} class B extends A{  public void fun2(int x,int y){     fun1(6);  // prints "int in A"      System.out.println("Int in B is :" + x+" and "+y);    }}public class inherit{  public static void main(String[] args){     B obj= new B();     obj.fun2(2,6);      }}

In the above example,  class B extends class A and so acquires properties and behavior of class A. So we can call method of A in class B.

Page 34: JavaClassPresentation

Polymorphism :• Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to different functionality. • Polymorphism allows a object to accept different requests of a

client (it then properly interprets the request like choosing appropriate method) and responds  according to the current state of the runtime system, all without bothering the user. 

There are two types of polymorphism :1.Compile-time polymorphism (Method Overloading)2.Runtime Polymorphism (Method Overriding)

Method Overloading:• In compiletime Polymorphism, method to be invoked is determined at the compile time. • Compile time polymorphism is supported through the method overloading concept in java.• Method overloading means having multiple methods with same name but with different signature (number, type and order of parameters).

Page 35: JavaClassPresentation

class A{  public void fun1(int x){    System.out.println("The value of class A is : " + x);  }  public void fun1(int x,int y){    System.out.println("The value of class B is : " + x + " and " + y);  }}public class polyone{  public static void main(String[] args){    A obj=new A();// Here compiler decides that fun1(int) is to be called and "int" will be printed.    obj.fun1(2);   // Here compiler decides that fun1(int,int)is to be called and "int and int" will be printed.       obj.fun1(2,3);         }}

Method Overloading (Compile-time polymorphism)

Page 36: JavaClassPresentation

Method Overriding:• In Run-time polymorphism, the method to be invoked is

determined at the run time. • The example of run time polymorphism is method overriding.

When a subclass contains a method with the same name and signature as in the super class then it is called as method overriding.

Page 37: JavaClassPresentation

class A{  public void fun1(int x){     System.out.println("int in Class A is : "+ x);  }}

class B extends A{  public void fun1(int x){     System.out.println("int in Class B is : "+ x);  }}

public class polytwo{  public static void main(String[] args){     A obj;          obj= new A(); // line 1     obj.fun1(2);  // line 2 (prints "int in Class A is : 2")          obj=new B();  // line 3     obj.fun1(5);  // line 4 (prints ""int in Class B is : 5")  }}

Method Overriding (Run-time Polymorphism)

Page 38: JavaClassPresentation

Character Set in Java:• The smallest units of java languages are Characters used to

write Java Tokens.• These characters are defined by Unicode Character set.• The Unicode is a 16-bit character coding system.• It supports more than 34,000 characters in worldwide.• ASCII characters are subset of UNICODE Character set.

lower-case <= a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|zupper-case <= A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Zalphabetic <= lower-case | upper-casenumeric     <= 0|1|2|3|4|5|6|7|8|9alphanumeric <= alphabetic | numericspecial       <= !|%|^|&|*|(|)|-|+|=|{|}|||~|[|]|\|;|'|:|"|<|>|?|,|.|/|#|@|`|_graphic     <= alphanumeric | special

Page 39: JavaClassPresentation

Java Tokens:•Smallest individual units in a program are known as tokens.•The compiler recognizes them for building up expressions and statements.•Java language includes Five types of tokens. They are:•Reserved Keywords•Identifiers•Literals•Operators•Separators

Page 40: JavaClassPresentation

Keywords:•Keyword are an essential part of a language definition.•Java has 50 keywords listed below.•Keywords have specific meaning in Java.•We cannot use them as names for variables, classes, methods and so on.• All keywords are to be written in lower-case letters.•It is good practice avoiding usage of key words as identifiers.•keywords are case-sensitive.

Page 41: JavaClassPresentation

abstract continue goto package switch

assert default if private this

boolean do implements protected throw

break double import public throws

byte Else Instanceof Return Transient

Case Extends Int Short Try

Catch Final Interface Static Void

Char Finally Long Strictfp Volatile

Class Float Native Super While

Const For New Synchronized enum

List of Keywords in Java

Page 42: JavaClassPresentation

Identifiers:•Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, objects, labels, packages and interfaces in a program.•Rules for Identifiers:

1. They can have alphabets, digits, underscore and dollar sign characters.

• They must not begin with digit.• Uppercase and lowercase letters are distinct.• They can be of any length.

Literals:Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables.

Page 43: JavaClassPresentation

Java specifies Five major types of literals. They are:

1.Integer Literals E.g.: 123• Floating-point Literals E.g.: 123.45• Character Literals E.g.: 'X' or 'x'• String Literals E.g.: "Hello"• Boolean Literals E.g.: true or false

Operators:An operator is a symbol that takes one or more arguments and operates on them to produce a result.

Separators:Separators are symbols used to indicate where groups of code are divided and arranged.

Page 44: JavaClassPresentation

separators

Note that the first three separators are tokens that separate/punctuate other tokens. The last six separators (3-pairs of 2 each) are also known as delimiters.For example the Java code Math.max(count,limit); contains nine tokens. 1. An identifier (math), followed by • A separator (a period), followed by • Another identifier (max), followed by • A separator (the left parenthesis delimiter), followed by • An identfier (count), followed by • A separator (a comma), followed by • Another identifier(limit), followed by • A separator (the right parenthesis delimiter), followed by • A separator (a semicolon)

; , . ( ) { } [ ]

Page 45: JavaClassPresentation

Java Statements

Selection Statements

Iteration Statements

Jump Statements

Expression Statements

Labeled Statements

Synchronize Statements

Guarding Statements

return

break

continueIf-

else

switch

if

while do for

Control St.

Page 46: JavaClassPresentation

Constants:Definition:Constants in Java refer to fixed values that do not change during the execution of a program.

Java Constants

Java Constants Java Constants

Integer Constants

Real Constants

String Constants

Character Constants

Decimal : 123Octal : 037Hexadecimal: 0X9F

Fractional : 0.0065,-0.75Exponential : 1.5e+5

E.g.: '5' 'X' ';'

E.g.:"Hello" "1223"

Page 47: JavaClassPresentation

Integer Constants:An integer constant refers to a sequence of digits.Real Constant:A constant which has fractional part is called Real constant.Character Constant:A single character constant (or simply character constant) contains a single character enclosed within a pair of single quote marks. String Constant:A string constant is a sequence of characters enclosed between double quotes.Backslash Character Constants:'\b', '\f', '\n', '\r', '\t', '\"', '\"', '\\'

Page 48: JavaClassPresentation

Variables:A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program.Rules for variable names:1. They must not begin with a digit.• Uppercase and lowercase are distinct.• It shou8ld not be a keyword.• White space is not allowed.• Variable names can be of any length.

Declaration of variables:Variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler.

type variable1, variable2, …………, variableN;Declaration does :1. Tell the compiler what the variable name is.• Specify what type of data the variable will hold.• Decides the scope of variable (depends on the place it is declared).

Page 49: JavaClassPresentation

Scope of Variables:The area of the program where the variable is accessible is called its scope.It is classified into three kinds:• Instance variable• Class variable• Local variable

Instance:Instance variable is declared inside the class. It is created when the objects are instantiated and therefore they are associated with the objects. They take different values for different object.Class:It is also declared inside the class and it is global variable to a class and belong to the entire set of objects that creates. Only one memory location is created for each class.Local:Variables declared and used inside methods are called local variables. And it also can be declared inside the block of codes that defined between { and }.

Page 50: JavaClassPresentation

Data Types in Java:• Data types specify the size and type of values that can be stored.• Variety of data types available allow the programmer to select the

type appropriate to the needs of the application.

Primitive (Intrinsic

)

Non-Primitive (Derived)

Numeric Non-Numeric

IntegerFloating-Point

CharacterBoolean

Classes Arrays

Interface

DATA TYPES IN JAVA

Page 51: JavaClassPresentation

Integer Type:• Can hold whole numbers such as 123, -234.• It has Four types of Integer Types:

o Byteo Shorto Into Long

Floating Point Types:• Can hold numbers containing fractional parts such as 57.78 and -

45.78.• It has two types of values:

o Single Precisiono Double precision

Page 52: JavaClassPresentation

Character Type:• To store character constant in memory the data type Char is

used.• It assumes a size of 2 bytes and holds a single character.

Boolean type:this type of data type is used to hold the values of Boolean such as ‘true’ or ‘false’.Symbolic Constants:Storing of some Constant value (which is needed frequently in the program) to a symbol is called Symbolic Constant.final type symbolic-name = value;E.g.: final int STRENGTH = 100;Type Casting:The process of Converting one data type to another is called casting.type variable1 = (type) variable2;

Page 53: JavaClassPresentation

Operators:Operators are used in programs to manipulate data and variables.The list of Operators:1. Arithmetic operators• Relational operators• Logical operators• Assignment operators• Increment and decrement operators• Conditional operators• Bitwise operators• Special operators

Page 54: JavaClassPresentation

Operator Meaning

+ Addition or unary plus

- Subtraction or unary minus

* Multiplication

/ Division

% Modulo division

Arithmetic Operators

Operator Meaning

< Is less than

<= Is less than or equal to

> Is greater than

>= Is greater than or equal to

== Is equal to

!= Is not equal toRelational Operators

Page 55: JavaClassPresentation

Logical Operators

Assignment Operator

Increment and decrement Operators

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Operator Meaning

= Store value

Operator Meaning

++ Incrementing value

-- Decrementing value

Conditional Operator

Exp1 ? Exp2 : exp3

Page 56: JavaClassPresentation

Bitwise Operators

Special Operators

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ One's complement

<< Shift left

>> Shift right

>>> Shift right with zero fill

Instanceof Operator:E.g.: person instanceof student

Dot Operator:E.g.: person.age

Page 57: JavaClassPresentation

postfix [] . () expr++ expr–

unary ++expr –expr +expr -expr ! ~

creation/caste new (type)expr

multiplicative * / %

additive + -

shift >> >>>

relational < <= > >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ?:

assignment = “op=”

Operator Precedence

Page 58: JavaClassPresentation

Control Statements:There are two types of control statements. They are:1. Decision making and Branching Statements• Decision making and Looping statements

Decision making and Branching:•when a program breaks the sequential flow and jumps to another part of the code, it is called branching. •When the branching is based on a particular condition, it is known as conditional branching. •If branching takes place without any decision, it is known as unconditional branching.They are:1. If statement• Switch statement• Conditional operator statement

Page 59: JavaClassPresentation

If Statement:The four forms of If statement:1. Simple if• If….else• Nested if…else• Else if ladder

Simple if:General form:if (test expression){statement-block;}statement-X;

Next statements

Statements X

Statements block

Test?

Entry

true

False

Page 60: JavaClassPresentation

If…Else statement:General form:if (test expression){True-block statement;}else{False-block statement;}statement-X;

Conditional Operator:

General form:

Conditional expression ? Expression-1 : Expression-2

Next statements

Statements X

Statements block

Test?

Entry

true

FalseStatements block

False

Page 61: JavaClassPresentation

Nested If…Else statement:General form:if (test expression){if (test expression){True-block statement;}else{False-block statement;}}else{False-block statement;}statement-X;

Test?

Entry

true

FalseStatements block

False

Statements

Test?

trueFalse

Statements

Statements X

Page 62: JavaClassPresentation

Else…If Ladder:General form:if (test expression)else if (test expression)Statement-1;else if (test expression)Statement-2;elseDefault St;Statement-X;

Test?

Entry

true

FalseStatements block

False

Test?

trueFalse

Statements

Default

Test?

true

False

Statements

Statements X

Page 63: JavaClassPresentation

Switch Statement:General form:Switch (expression){case value-1:blockt-1;break;case value-1:blockt-1;break;default:default-block;break;} Statement-X;

Page 64: JavaClassPresentation

Loop Controls:There are three types of looping statements:1. While construct2. Do construct3. For construct

A looping process, in general, would include the following four steps:1. Setting and initialization of a counter• Execution of the statements in the loop• Test for a specified condition for execution of the loop• Incrementing the counter

Page 65: JavaClassPresentation

Loop control structures:

Entry

true

FalseTest

?

Body of the loop

Entry

true

False

Test?

Body of the loop

Exit controlEntry control

Page 66: JavaClassPresentation

The While Statement:Entry Controlled Loop.General Form:Initialization;While (test-condition){Body of the loop;}

The do Statement:

Exit Controlled Loop.General Form:Initialization;do{Body of the loop;}While (test-condition);

The for Statement:Another entry Controlled Loop.General Form:for (initialization; test-condition; increment){Body of the loop;}

Nesting of for Loops:

General Form:for (initialization; test-condition; increment){for (initialization; test-condition; increment){Body of the loop;}}

Page 67: JavaClassPresentation

Jump in Loops:Java permits a jump from one statement to the end or beginning of a loop as well as out of loop.Jumping Out of Loop:General Form:Initialization;While (test-condition){ ………….………….if (condition)break;Body of the loop;}……………..……………..

Exit from loop

Skipping a Part of a Loop:During the loop operations, it may be necessary to skip a part of the body of the loop under certain conditions.the continue statement causes the loop to be continued with the next iteration after skipping.General Form:Initialization;While (test-condition){ ………….………….if (condition)continue;Body of the loop;}……………..……………..

Skip the iteration

Page 68: JavaClassPresentation

Labeled Loops:General Form:Outer: While (test-condition){ ………….………….if (condition)Body of the loop;continue Outer;}……………..……………..

Transferring Control

Page 69: JavaClassPresentation

Java Library Methods:Strings:In Java string is a sequence of characters. Java implements strings as objects of type String.String Constructors:

String(char chars[])String(char chars[], int startindex, int numChars)String(String strObj)Strin(byte asciiChars[])String(byte asciiChars[], int startIndex, int numChars)Where: startIndex • specify the subrange begins and numChars • specify the number of characters to use.Declaration: E.g.: String S = new String();

Page 70: JavaClassPresentation

Methods in String Description

int length() Return the length of the string

String toString() Converts data into string representation

Char charAt(int where) Returns a character at index specified

Void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)

Extract the specified characters from one string to another

char[] toCharArray() Returns an array of characters

boolean equals(Object str) Returns boolean value

Boolean startsWith(String str) Returns boolean value

Boolean endsWith(String str) Returns boolean value

int compareTo(String str) If value is: < 0 • Invoking String is less than str> 0 • Invoking String is greater than str== 0 • Invoking String equal to str

String substring(int startIndex,int endIndex)

Separate the substring from main string

String concat(String str) Concatenation of two strings

String replace(char original, char replace)

Replace the string

String trim() Remove the white space in a string.

Page 71: JavaClassPresentation

Methods in String Description

Static String value(double num)

Converts data into human readable format

String toLowerCase() Converts letters to lower case

String to UpperCase() Converts letters to Uppercase

Char charAt(int where) Return a character

Void setCharAt(int where, char ch)

Set the character at its position

StringBuffer delete(int start, int end) and StringBuffer deleteCharAt(int where)

Delete the content at specified position.

StringBuffer replace(int start, int end, String str)

Replace the string at specified positions

'+' is a Concatenation operator of Strings or any Data types.

It just join the strings or data

Page 72: JavaClassPresentation