Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

Unit-1: Introduction to Java, Data Types, Operators, Statements

Paradigms of Programming Languages


 Since the invention of computers, many programming
approach (styles) have been tried. Such as modular programming, top-
down programming, bottom-up programming and structured
programming.

 When computers were first invented, programming was done by manually


toggling in the binary machine instructions by use of the front panel. As
long as programs were just a few hundred instructions long, this approach
worked.

 As programs grew, assembly language was invented so that a programmer


could deal with larger, increasingly complex programs by using symbolic
representations of the machine instructions.

 As programs continued to grow, high-level languages were introduced that


gave the programmer more tools with which to handle complexity

 Java is a high-level, third generation programming language like C,


FORTRAN, Smalltalk, Perl, and many others.

 Computer language innovation and development occurs for two


fundamental reasons:
■ To adapt to changing environments and uses
■ To implement refinements and improvements in the art of
programming
 Major Programming Paradigms

 There are several kinds of major programming paradigms:


1. Imperative
2. Logical
3. Functional
4. Object-Oriented

 It can be shown that anything solvable using one of these paradigms can
be solved using the others; however, certain types of problems lend
themselves more naturally to specific paradigms.
1. Imperative Paradigm
“First do this and next do that”
 This statement describes the spirit of the imperative paradigm.

 The imperative programming paradigm assumes that computations are


performed through a guided sequence of steps.

 The order of the steps is crucial, because a given step will have different
consequences depending on the current values of variables when the step is
executed.

 Popular programming languages are imperative. There are two reasons for
such popularity:

1. the imperative paradigm most closely resembles the actual


machine itself, so the programmer is much closer to the
machine;
2. because of such closeness, the imperative paradigm was the
only one efficient enough for widespread use until recently.

 Disadvantages

 The semantics of a program can be complex to understand or prove


 Side effects also make debugging harder;
 Abstraction is more limited than with some paradigms;
 Order is crucial, which doesn't always suit itself to problems.

 For example: Fortran, Algol, Pascal, Basic, C

2. Logical [ “Answer a Question via search for a solution” ]

 The Logical Paradigm takes a declarative approach to problem-solving.


Various logical assertions about a situation are made, establishing all known
facts. Then queries are made. The role of the computer becomes maintaining
data and logical deduction.

 A logical program is divided into three sections:


1. a series of definitions/declarations that define the problem domain
2. statements of relevant facts
3. statement of goals in the form of a query
 The advantages of logic oriented programming are bi-fold:
1. The system solves the problem, so the programming steps
themselves are kept to a minimum;
2. Proving the validity of a given program is simple.

3. Functional
 The Functional Programming paradigm views all subprograms as
functions in the mathematical sense-informally, they take in arguments and
return a single solution.

 The solution returned is based entirely on the input, and the time at which
a function is called has no relevance.

 The advantages of functional language:


 The high level of abstraction, especially when functions are
used, suppresses many of the details of programming and
thus removes the possibility of committing many classes of
errors;
 The lack of dependence on assignment operations, allowing
programs to be evaluated in many different orders. This
evaluation order independence makes function-oriented
languages good candidates for programming massively
parallel computers;
 The absence of assignment operations makes the function-
oriented programs much more amenable to mathematical
proof and analysis than are imperative programs, because
functional programs possess referential transparency.
 Disadvantages
 Perhaps less efficiency
 Problems involving many variables or a lot of sequential
activity are sometimes easier to handle imperatively or with
object-oriented programming.

4. Object-Oriented
 Object Oriented Programming (OOP) is a paradigm in which real-world
objects are each viewed as seperate entities having their own state which is
modified only by built in procedures, called methods.

 Objects are organized into classes, from which they inherit methods and
equivalent variables. The object-oriented paradigm provides key benefits
of reusable code and code extensibility.
Modern Programming Era begins with: C

 The C language shook the computer world. The creation of C was a direct
result of the need for a structured, efficient, high-level language that could
replace assembly code when creating systems programs.

 Prior to C, programmers usually had to choose between languages that are


less powerful and focuses on single purpose only. For example:
 Although FORTRAN could be used to write fairly efficient programs
for scientific applications, it was not very good for systems code.
 And while BASIC was easy to learn, it wasn’t very powerful, and its
lack of structure so not very useful for large programs.
 Assembly language can be used to produce highly efficient
programs, but it is not easy to learn or use effectively. Further,
debugging assembly code can be quite difficult.

 Earlier Languages were not well-structured and lack of proper jumping


and branching so programs written using these languages tended to
produce “spaghetti code”.

 The creation of C is considered as a beginning of the modern age of


computer languages. It solved the troubles from earlier languages. C is a
powerful, efficient, structured language that is relatively easy to learn.

 Prior to the invention of C, computer languages were generally designed


either as academic exercises or by bureaucratic committees. C is different.
It was designed, implemented, and developed by real working
programmers.

Evolution of OO Methodology

 During the late 1970s and early 1980s, C became the dominant computer
programming language, and it is still widely used today. Since C is a
successful and useful language, you might ask why a need for something
else existed. The answer is complexity.

 Even with structured programming methods, once a project reaches a


certain size, its complexity exceeds what a programmer can manage. To
solve this problem, a new way to program was invented, called object-
oriented programming (OOP).
 OOP is a programming methodology that helps organize complex programs
through the use of inheritance, encapsulation, and polymorphism.

 Although C is one of the world’s great programming languages, there is a


limit to its ability to handle complexity. Once a program exceeds
somewhere between 25,000 and 100,000 lines of code, it becomes so
complex that it is difficult to grasp as a totality. C++ allows this barrier to
be broken, and helps the programmer comprehend and manage larger
programs.

Simula
 The introduction of Simula-67 brought with it the first true programming
object, classes, and a form of inheritance; therefore, Simula is an
important milestone in any discussion on O-O programming languages.

 The language was designed by Dahl, Myhrhaug, and Nygaard at the


Norwegian Computing Center at Oslo, Norway. The initial version of the
language, Simula-1, was introduced in 1966.

Smalltalk
 Many consider that the first truly O-O language was Smalltalk, developed
at the Learning Research Group at Xerox's Palo Alto Research Center in
the early 1970s.

 In Smalltalk, everything is really an object that enforces the O-O paradigm.


It is virtually impossible to write a program in Smalltalk that is not O-O.
This is not the case for other languages that support objects, such as C++
and Visual Basic (and Java, for that matter).

C++:
 C++ was invented by Bjarne Stroustrup in 1979, while he was working at
Bell Laboratories in Murray Hill, New Jersey. Stroustrup initially called
the new language “C with Classes.” However, in 1983, the name was
changed to C++.

 C++ extends C by adding object-oriented features. Because C++ is built


upon the foundation of C, it includes all of C’s features, attributes, and
benefits.
Java
 Java's origins are in consumer electronics. In 1991, Sun Microsystems
began to investigate how it might exploit this growing market.

 Sometime later, James Gosling was investigating the possibility of creating


a hardware-independent software platform for just this purpose. Initially,
he attempted to use C++, but soon abandoned C++ and began the creation
of a new language he dubbed Oak.

C# .NET
 Microsoft responded to the popularity of Java by producing a version of
Java called Visual J++.

 C#, like Java, uses C/C++ syntax. C# incorporates many of concepts


introduced by the initial Java released.

Basic Concept of OO Approach:

Comparison of Object-oriented and procedure oriented approaches:

 As you know, all computer programs consist of two elements: code and
data. Furthermore, a program can be conceptually organized around its
code or around its data.

 That is, some programs are written around “what is happening” and others
are written around “who is being affected.”
 These are the two paradigms that govern how a program is constructed.
The first way is called the process-oriented model.

 This approach characterizes a program as a series of linear steps (that is,


code). The process-oriented model can be thought of as code acting on
data.

 Procedural languages such as C employ this model to considerable


success. However, problems with this approach appear as programs grow
larger and more complex.

 To manage increasing complexity, the second approach, called object-


oriented programming, was conceived. Object-oriented programming
organizes a program around its data (that is, objects) and a set of well-
defined interfaces to that data.

 An object-oriented program can be characterized as data controlling access


to code. As you will see, by switching the controlling entity to data, you can
achieve several organizational benefits.

Difference Between Procedure Oriented Programming (POP) & Object


Oriented Programming (OOP)
Procedure Oriented Object Oriented Programming
Programming
Divided Into In POP, program is divided into In OOP, program is divided
small parts called functions. into parts called objects.
Importance In POP, Importance is not given In OOP, Importance is given to
to data but to functions as well the data rather than
as sequence of actions to be procedures or functions
done. because it works as a real
world.
Approach POP follows Top Down OOP follows Bottom Up
approach. approach.
Access POP does not have any access OOP has access specifiers
Specifiers specifier. named Public, Private,
Protected, etc.
Data Moving In POP, Data can move freely In OOP, objects can move and
from function to function in the communicate with each other
system. through member functions.
Expansion To add new data and function OOP provides an easy way to
in POP is not so easy. add new data and function.
Data Access In POP, Most function uses In OOP, data can not move
Global data for sharing that easily from function to
can be accessed freely from function, it can be kept public
function to function in the or private so we can control the
system. access of data.
Data Hiding POP does not have any proper OOP provides Data Hiding so
way for hiding data so it is less provides more security.
secure.
Overloading In POP, Overloading is not In OOP, overloading is possible
possible. in the form of Function
Overloading and Operator
Overloading.
Examples Example of POP are : C, VB, Example of OOP are : C++,
FORTRAN, Pascal. JAVA, VB.NET, C#.NET.

Concepts of OOP [ Object-Oriented Programming ]


 There are some basic concepts of object oriented programming as follows:
1. Object
2. Class
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
1. Object
 Objects are important runtime entities in object oriented method. They
may characterize a location, a bank account, and a table of data or any
entry that the program must handle. For example:
[ Representation of an object: Student ]

 Each object holds data and code to operate the data. Object can interact
without having to identify the details of each other’s data or code. It is
sufficient to identify the type of message received and the type of reply
returned by the objects. Another example of object is CAR.

[ Representation of an object: Car ]


2. Classes
 A class is a set of objects with similar properties (attributes), common
behaviour (operations), and common link to other objects.

 The complete set of data and code of an object can be made a user defined
data type with the help of class. The objects are variable of type class.

 A class is a collection of objects of similar type. Classes are user defined


data types and work like the build in type of the programming language.
Once the class has been defined, we can make any number of objects
belonging to that class. Each object is related with the data of type class
with which they are formed.
 As we learned that, the classification of objects into various classes is
based on its properties (States) and behavior (methods). Classes are used
to distinguish are type of object from another. The important thing about
the class is to identify the properties and procedures and applicability to
its instances.

[Representation of class]

 In above example, we will create an objects MH-01 1234 belonging to the


class car. The objects develop their distinctiveness from the difference in
their attribute value and relationships to other objects.

3. Data Abstraction
 Data abstraction refers to the act of representing important description
without including the background details or explanations.

 Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, cost and functions operate on these attributes.
They summarize all the important properties of the objects that are to be
created.

 Classes use the concepts of data abstraction and it is called as Abstract


Data Type (ADT).

4. Data Encapsulation
 Data Encapsulation means wrapping of data and functions into a single
unit (i.e. class). It is most useful feature of class. The data is not easy to
get to the outside world and only those functions which are enclosed in
the class can access it.

 These functions provide the boundary between Object’s data and program.
This insulation of data from direct access by the program is called as Data
hiding.

[Encapsulation]
5. Inheritance

 Inheritance is the process by which objects of one class can get the
properties of objects of another class. Inheritance means one class of
objects inherits the data and behaviors from another class.

 Inheritance maintains the hierarchical classification in which a class


inherits from its parents.

 Inheritance provides the important feature of OOP that is reusability. That


means we can include additional characteristics to an existing class
without modification. This is possible deriving a new class from existing
one.

 In other words, it is property of object-oriented systems that allow objects


to be built from other objects. Inheritance allows openly taking help of the
commonality of objects when constructing new classes.

 Inheritance is a relationship between classes where one class is the parent


class of another (derived) class. The derived class holds the properties and
behaviour of base class in addition to the properties and behaviour of
derived class.
 In above Figure, the Santro is a part of the class Hyundai which is again
part of the class car and car is the part of the class vehicle. That means
vehicle class is the parent class.

6. Polymorphism (Poly means “many” and morph means “form”).

 Polymorphism means the ability to take more than one form.

 Polymorphism plays a main role in allocate objects having different


internal structures to share the same external interface. This means that
a general class of operations may be accessed in the same manner even
though specific activities associated with each operation may differ.

 Polymorphism is broadly used in implementing inheritance. It means


objects that can take on or assume many different forms. Polymorphism
means that the same operations may behave differently on different
classes.

 Booch defines polymorphism as “the relationship of objects many different


classes by some common super class. Polymorphism allows us to write
generic, reusable code more easily, because we can specify general
instructions and delegate the implementation detail to the objects
involved.
For Example:
In a pay roll system, manager, office staff and production worker objects all will
respond to the “compute payroll” message, but the real operations performed are
object particular.
[Polymorphism]

7. Dynamic Binding
 Binding refers to the linking of a procedure call to the code to be executed
in response to the call. Dynamic binding means that the code related with
a given procedure call is not known until the time of the call at run time.
 Dynamic binding is associated with polymorphism and inheritance.

Introduction to Java

 Compared to other programming languages, Java is most similar to C.


However although Java shares much of C's syntax, it is not C. Knowing
how to program in C or, better yet, C++, will certainly help you to learn
Java more quickly, but you don't need to know C to learn Java.

 From C, Java derives its syntax. Many of Java’s object-oriented features


were influenced by C++.

 You can use Java to write computer applications that play games, store
data or do any of the thousands of other things computer software can do.

 What's most special about Java in relation to other programming


languages is that it lets you write special programs called applets that can
be downloaded from the Internet and played safely within a web browser.

 Java language is called as an Object-Oriented Programming language and


before beginning for Java, we have to learn the concept of OOPs(Object-
Oriented Programming).
JAVA HISTORY :
 Java is a general-purpose, object-oriented programming language
developed by Sun Microsystems of USA in 1991.Originally called Oak by
James Gosling (one of the inventor of the language).
 Java was invented for the development of software for consumer electronic
devices like TVs, tosters, etc. The main aim had to make java simple,
portable and reliable.
 Java Authors: James , Arthur Van , and others

*Following table shows the year and beginning of Java.


Features of Java Language:
 Java is first programming language which is not attached with any
particular hardware or operating system. Program developed in Java can
be executed anywhere and on any system.
 Features of Java are as follows:
1. Compiled and Interpreted
2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible

1. Compiled and Interpreted


 Basically a computer language is either compiled or interpreted. Java
comes together both these approach thus making Java a two-stage system.
 Java compiler translates Java code to Bytecode instructions and Java
Interpreter generate machine code that can be directly executed by
machine that is running the Java program.

2. Platform Independent and portable


 Java supports the feature portability. Java programs can be easily moved
from one computer system to another and anywhere. Changes and
upgrades in operating systems, processors and system resources will not
force any alteration in Java programs.

 This is reason why Java has become a trendy language for programming
on Internet which interconnects different kind of systems worldwide.

 Java certifies portability in two ways. First way is, Java compiler generates
the bytecode and that can be executed on any machine. Second way is,
size of primitive data types are machine independent.

3. Object- oriented
 Java is truly complete object-oriented language. In Java, almost everything
is an Object. All program code and data exist in objects and classes. Java
comes with an extensive set of classes; organize in packages that can be
used in program by Inheritance. The object model in Java is trouble-free
and easy to enlarge.

4. Robust and secure


 Java is a most strong language which provides many securities to make
certain reliable code. It is design as garbage–collected language, which
helps the programmers virtually from all memory management problems.

 Java also includes the concept of exception handling, which detain serious
errors and reduces all kind of threat of crashing the system.

 Security is an important feature of Java and this is the strong reason that
programmer use this language for programming on Internet.

 The absence of pointers in Java ensures that programs cannot get right of
entry to memory location without proper approval.
5. Distributed
 Java is called as Distributed language for construct applications on
networks which can contribute both data and programs.

 Java applications can open and access remote objects on Internet easily.
That means multiple programmers at multiple remote locations to work
together on single task.

6. Simple and small


 Java is very small and simple language. Java does not use pointer and
header files, goto statements, etc. It eliminates operator overloading and
multiple inheritance.

7. Multithreaded and Interactive


 Multithreaded means managing multiple tasks simultaneously. Java
maintains multithreaded programs. That means we need not wait for the
application to complete one task before starting next task. This feature is
helpful for graphic applications.

8. High performance
 Java performance is very extraordinary for an interpreted language,
majorly due to the use of intermediate bytecode.

 Java architecture is also designed to reduce overheads during runtime.


The incorporation of multithreading improves the execution speed of
program.

9. Dynamic and Extensible


 Java is also dynamic language. Java is capable of dynamically linking in
new class, libraries, methods and objects.

 Java can also establish the type of class through the query building it
possible to either dynamically link or abort the program, depending on the
reply.

 Java program is support functions written in other language such as C


and C++, known as native methods.
JAVA VIRTUAL MACHINE
 As we know that all programming language compilers convert the source
code to machine code. Same job done by Java Compiler to run a Java
program, but the difference is that Java compiler convert the source code
into Intermediate code is called as bytecode.

 This machine is called the Java Virtual machine and it exits only inside the
computer memory.
 *Following figure shows the process of compilation.

 Java Object Framework act as the intermediary between the user


programs and the virtual machine which in turn act as the intermediary
between the operating system and the Java Object Framework.

Java Environment (JDK/JRE)


 Java environment includes a number of development tools, classes and
methods. The development tools are part of the system known as Java
Development Kit (JDK) and the classes and methods are part of the Java
Standard Library (JSL), also known as the Application Programming
Interface (API).
 Java Development kit (JDK) – The JDK comes with a set of tools that are
used for developing and running Java program. It includes:
1. Appletviewer ( It is used for viewing the applet )
2. javac ( It is a Java Compiler )
3. java ( It is a java interpreter )
4. javap (Java disassembler, which convert byte code into
program description)
5. javah (It is for java C header files)
6. javadoc (It is for creating HTML document)
7. jdb (It is Java debugger)
8. JAR (Java Archives)
appletviewer
 AppletViewer is a standalone, command line program from Sun to run
Java applets. Appletviewer is generally used by developers for testing their
applets before being deployed to a website. The appletviewer command
allows you to run applets outside of the context of a World-Wide Web
browser.

 The appletviewer command connects to the document(s) or resource(s)


designated by urls and displays each applet referenced by that document
in its own window.

javac (Java compiler)


 In java, we can use any text editor for writing program and then save that
program with “.java” extension. Java compiler convert the source code or
program in bytecode and interpreter convert “.java” file in “.class” file.
Syntax:
C:\javac filename.java

java(Java Interpreter)
 As we learn that, we can use any text editor for writing program and
then save that program with “.java” extension. Java compiler convert
the source code or program in bytecode and interpreter convert
“.java” file in “.class” file.
Syntax:
C:\java filename

JAR (Java Archive) :

 JARis an archive file format typically used to aggregate many Java


class files and associated metadata and resources (text, images and
so on) into one file to distribute application software or libraries on
the Java platform.

 JAR files are built on the ZIP file format and have the .jar file
extension. Computer users can create or extract JAR files using the
jar command that comes with a JDK
Java Program Structure

Documentation Section

Package Section

Import Section

Interface Section

Class Definitions

Main Method Class

main() method Definition

 DOCUMENTATION SECTION:
 It is a set of comment lines giving the name of the program,the
author and the other details,which the programmer would like
to refer.

 PACKAGE STATEMENT:
 The first statement allowed in Java files is a
package statement.Thisstatement declares a package name and
informs the compiler that the classes defined here belong to this
package.
Exa: package student;

 It is optional because no need & our class to be part of packages.

 IMPORT STATEMENT:
 Similar to #include statement in C.
Ex:import student.test;
 This statement instructs the interpreter to load the test class
contained in package student. Using import statement ,we can
access to classes that part of other named packages.
 INTERFACE STATEMENT:
 Interface like class but includes group of methods declaration.
Used when we want to implement multiple inheritance
feature.

 CLASS DEFINITION:
 Java program may contain multiple class definition.
 Classes are primary feature of Java program.
 The classes are used to map real world problems.

 MAIN METHOD CLASS:


 Java stand alone program requires main method as starting point.
 This is essential part of program. Main method creates object of
various classes.
 On reaching end of the main the program terminate and the control
passes back to then operating system.

##Let us take a sample program to understand the structure of basic java


program.
/* This is a simple Java program.
Call this file "Example.java". */
class Example
{
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}

 Saving the Program


 The first thing that you must learn about Java is that the name you give
to a source file is very important. For this example, the name of the source
file should be Example.java.

 In Java, a source file is officially called a compilation unit. It is a text file


that contains one or more class definitions. The Java compiler requires
that a source file use the .java filename extension. Notice that the file
extension is four characters long.
 As you might guess, your operating system must be capable of supporting
long filenames. This means that DOS and Windows 3.1 are not capable of
supporting Java. However, Windows 95/98 and Windows NT/2000/XP
work just fine.

 As you can see by looking at the program, the name of the class defined
by the program is also Example. Because in Java, all code must reside
inside a class. By convention, the name of that class should match the
name of the file that holds the program(main function).

 You should also make sure that the capitalization of the filename matches
the class name. The reason for this is that Java is case-sensitive. This
convention makes it easier to maintain and organize your programs.

 Compiling the Program


 To compile the program,
C:\>javac Example.java
 The javac compiler creates a file called Example.class that contains
the bytecode version of the program. The Java bytecode is the
intermediate representation of your program that contains
instructions the Java interpreter will execute.

 Thus, the output of javac is not code that can be directly executed.

 To actually run the program, you must use the Java interpreter,
called java.
C:\>java Example
 When Java source code is compiled, each individual class is put into
its own output file named after the class and using the .class
extension.

 Java uses same symbols as C for single and multiline comments.


For example:
/*
This is a simple Java program.
Call this file "Example.java".
*/

// Your program begins with a call to main().


main() statement in java:
class Example
{
// Your program begins with a call to main().
public static void main(String args[])
{

 All Java applications begin execution by calling main( ).

 The public keyword is an access specifier, which allows the


programmer to control the visibility of class members. When a class
member is preceded by public, then that member may be accessed
by code outside the class in which it is declared.

 In this case, main( ) must be declared as public, since it must be


called by code outside of its class when the program is started.

 The keyword static allows main( ) to be called without having to


instantiate a particular instance of the class. This is necessary since
main( ) is called by the Java interpreter before any objects are made.

 The keyword void simply tells the compiler that main( ) does not
return a value.

 Keep in mind that Java is case-sensitive. Thus, Main is different


from main. It is important to understand that the Java compiler will
compile classes that do not contain a main( ) method. But the Java
interpreter has no way to run these classes. So, if you had typed
Main instead of main, the compiler would still compile your
program. However, the Java interpreter would report an error
because it would be unable to find the main( ) method.

 In main( ), there is only one parameter, String args[ ] declares a


parameter named args, which is an array of instances of the class
String. Here, args receives any command-line arguments when the
program is executed.

 The next line of code is shown here. Notice that it occurs inside
main( ).
System.out.println("This is a simple Java program.");
 This line outputs the string “This is a simple Java program.” followed
by a new line on the screen. Output is actually accomplished by the
built-in println( ) method. println( ) can be used to display other
types of information, too.

 System is a predefined class that provides access to the system, and


out is the output stream that is connected to the console.

 Unicode System in Java:


Unicode is a universal international standard character encoding
that is capable of representing most of the world's written
languages.

Why java uses Unicode System?


Before Unicode, there were many language standards:
 ASCII (American Standard Code for Information Interchange) for the
United States.
 ISO 8859-1 for Western European Language.
 KOI-8 for Russian.
 GB18030 and BIG-5 for chinese, and so on.

This caused two problems:


1. A particular code value corresponds to different letters in the various
language standards.
2. The encodings for languages with large character sets have variable
length.Some common characters are encoded as single bytes, other
require two or more byte.

To solve these problems, a new language standard was developed i.e. Unicode
System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF

To enable a computer system for storing text and numbers which is
understandable by humans, there should be a code that transforms characters
into numbers.
Unicode is a standard of defining the relevant code by using character
encoding. Character encoding is the process for assigning a number for every
character. The central objective of Unicode is to unify different language encoding
schemes in order to avoid confusion among computer systems that uses limited
encoding standards such as ASCII, EBCDIC etc.

Java Unicode:
The evolution of Java was the time when the Unicode standards had been defined
for very smaller character set. Java was designed for using Unicode Transformed
Format (UTF)-16, when the UTF-16 was designed. The ‘char’ data type in Java
originally used for representing 16-bit Unicode. Hence Java uses Unicode
standard

//Unicode representation of a character indicated by the leading \u sequence.


//The numeric value is always a four-digit hexadecimal number in this format.
public class MainClass
{
public static void main(String[] argv)
{
char c1 = '\u0057'; // the letter W
char c2 = 'W';
char c3 = (char) 87; // the letter W
char cr = '\r'; // carriage return
}
}
Escape Sequence Character Represented
\b Backspace.
\t Horizontal tab
\n New line (line feed).
\f Form feed.
\r Carriage return.
\" Double quotation mark.
\' Single quotation mark.
\\ Backslash.
\xxx A character in octal representation; xxx must range from 000
through 377.
\uxxxx A Unicode character, where xxxx is a hexadecimal-format
num ber.
 These days the Unicode standard defines values for over 100,000
characters and can be seen at the Unicode Consortium. It has several
character encoding forms, UTF standing for Unicode Transformation Unit:
 UTF-8: only uses one byte (8 bits) to encode English
characters. It can use a sequence of bytes to encode the
other characters. UTF-8 is widely used in email systems
and on the Internet.
 UTF-16: uses two bytes (16 bits) to encode the most
commonly used characters. If needed, the additional
characters can be represented by a pair of 16-bit numbers.
 UTF-32: uses four bytes (32 bits) to encode the characters.
It became apparent that as the Unicode standard grew a
16-bit number is too small to represent all the characters.
UTF-32 is capable of representing every Unicode character
as one number.

JAVA BASICS

Variables and Data Types


 Variables are locations in memory in which values can be stored. They
have a name, a type, and a value. Before you can use a variable, you have
to declare it. After it is declared, you can then assign values to it.

 Java actually has three kinds of variables: instance variables, class


variables, and local variables.

 Instance variables are used to define attributes or the state for a


particular object. For example: color, size, height of ITEM object.

 Class variables are similar to instance variables, except their values apply
to all that class’s instances (and to the class itself) rather than having
different values for each object.

 Local variables are declared and used inside method definitions. For
example, index counters in loops, as temporary variables, They can also
be used inside blocks ({}).

 For Example:
class FamilyMember {
static String surname = “Johnson”;
String name;
int age;
...
}
 Instances of the class FamilyMember each have their own values for name
and age. But the class variable surname has only one value for all family
members. Change surname, and all the instances of FamilyMember are
affected.

 To access class variables, you use the same dot notation as you do with
instance variables. To get or change the value of the class variable, you can use
either the instance or the name of the class on the left side of the dot. Both the
lines of output in this example print the same value):
FamilyMember dad = new FamilyMember()
System.out.println(“Family’s surname is: “ +
dad.surname);
System.out.println(“Family’s surname is: “ +
FamilyMember.surname);

 Declaring Variables
 To use any variable in a Java program, you must first declare it. Variable
declarations consist of a type and a variable name:
int myAge;
String myName;
boolean isTired;
 You can string together variable names with the same type:
int x, y, z;
String firstName, LastName;
 You can also give each variable an initial value when you declare it:
int myAge, mySize, numShoes = 28;
String myName = “Laura”;
boolean isTired = true;
int a = 4, b = 5, c = 6;

 Rules on Variable Names


 Variable names in Java can start with a letter, an underscore (_), or
a dollar sign ($). They cannot start with a number.
 After the first character, your variable names can include any letter
or number. Symbols, such as %, *, @, and so on, are often reserved
for operators in Java, so be careful when using symbols in variable
names.
 In addition, the Java language uses the Unicode character set.
 Java language is case-sensitive, which means that uppercase letters
are different from lowercase letters.
 By convention, Java variables have meaningful names, often made
up of several words combined. The first word is lowercase, but all
following words have an initial uppercase letter:
Button theButton;
long reallyBigNumber;
boolean currentWeatherState;
 Variable Types
 In addition to the variable name, each variable declaration must
have a type, which defines what values that variable can hold. The variable
type can be one of three things:
 One of the eight basic primitive data types
 The name of a class
 An array

 Primitive Data Types


 Java is a strongly typed language. This means that every variable
must have a declared type.

 Every variable has a type, every expression has a type, and every
type is strictly defined. Second, all assignments, whether explicit or via
parameter passing in method calls, are checked for type compatibility.

 There are no automatic coercions or conversions of conflicting types


as in some languages. The Java compiler checks all expressions and
parameters to ensure that the types are compatible.

Any type mismatches are errors that must be corrected before the
compiler will finish compiling the class.

 Java defines eight primary (or elemental) data types: byte, short, int, long,
char, float, double, and boolean. These can be put in four groups:

■ Integers: This group includes byte, short, int, and long, which are
for whole valued signed numbers.
■ Floating-point numbers: This group includes float and double,
which represent numbers with fractional precision.
■ Characters: This group includes char, which represents symbols in
a character set, like letters and numbers.
■ Boolean: This group includes boolean, which is a special type for
representing true/false values.
Integers
 All integer types are signed, positive and negative values. Java does not
support unsigned, positive-only integers.

Name Width Range


long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127

Floating-Point Types
 Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision. For example,
calculations such as square root, or transcendental such as sine and
cosine, result in a value whose precision requires a floating-point type.
Name Width in Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038

Characters
 In Java, the data type used to store characters is char. In C/C++, char is
an integer type that is 8 bits wide. This is not the case in Java. Instead,
Java uses Unicode to represent characters. Unicode defines a fully
international character set that can represent all of the characters found
in all human languages.

Booleans
 Java has a simple type, called boolean, for logical values. It can have only
one of two possible values, true or false. This is the type returned by all
relational operators, such as a < b. boolean is also the type required by the
conditional expressions that govern the control statements such as if and
for.
 Symbolic Constants
 In Java, you use the keyword final to create a constant.
Syntax:
final type Symbolic_name=value;
For example,
final double CM_PER_INCH = 2.54;

 The keyword final indicates that you can assign to the variable once, then
its value is set once and for all. It is customary to name constants in all
upper case. And Do not declare in method.
 It is probably more common in Java to want a constant that is available to
multiple methods inside a single class. These are usually called class
constants. You set up a class constant with the keywords static final. Here
is an example of using a class constant:
public class Constants2
{
public static final double CM_PER_INCH = 2.54;;
public static void main(String[] args)
{
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeter: "
+ paperWidth * CM_PER_INCH + " by "
+ paperHeight * CM_PER_INCH);
}
}
 In Java, there are two types of constant as follows:
o Numeric Constants:
 Integer constant
 Real constant
o Character Constants:
 Character constant
 String constant
 Arrays
 An array is a group of like-typed variables that are referred to by a common
name. Arrays of any type can be created and may have one or more
dimensions. A specific element in an array is accessed by its index.
One-Dimensional Arrays
 A one-dimensional array is, essentially, a list of like-typed variables. To
create an array, you first must create an array variable of the desired type.
The general form of a one dimensional array declaration is:
type var-name[ ];
 Here, type declares the base type of the array. The base type determines
the data type of each element that comprises the array.

 The base type for the array determines what type of data the array will
hold.

 you must allocate using new and assign it to array. new is a special
operator that allocates memory.

 The general form of new as it applies to one-dimensional


arrays appears as follows:
array-var = new type[size];

 To use new to allocate an array, you must specify the type and number of
elements to allocate.

 The elements in the array allocated by new will automatically be initialized


to zero.
For Exa: month_days = new int[12];

 In Java, all arrays are dynamically allocated. Once you have allocated an
array, you can access a specific element in the array by specifying its index
within square brackets. All array indexes start at zero. For example,
month_days[1] = 28;

 It is possible to combine the declaration of the array variable with the


allocation of the array itself, as shown here:
int month_days[] = new int[12];

 Arrays can be initialized when they are declared. The array will
automatically be created large enough to hold the number of elements you
specify in the array initializer. There is no need to use new. For example,
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31};
 The Java run-time system will check to be sure that all array indexes are
in the correct range. (In this regard, Java is fundamentally different from C/C++,
which provide no run-time boundary checks.)

Multidimensional Arrays
 In Java, multidimensional arrays are actually arrays of arrays. To declare
a multidimensional array variable, specify each additional index using another
set of square brackets.

 For example, the following declares a two-dimensional array variable called


twoD.
int twoD[][] = new int[4][5];

 The following program numbers each element in the array from left to
right, top to bottom, and then displays these values:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19
 When you allocate memory for a multidimensional array, you need only
specify the memory for the first (leftmost) dimension. You can allocate the
remaining dimensions separately.
 For example, this following code allocates memory for the first dimension
of twoD when it is declared. It allocates the second dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];

 since multidimensional arrays are actually arrays of arrays, the length of


each array is under your control. For example, the following program
creates a two dimensional array in which the sizes of the second dimension
are unequal.
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0
12
345
6789
 Initialization of a two-dimensional array.
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};

Alternative Array Declaration Syntax


 There is a second form that may be used to declare an array:
type[ ] var-name;
 For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];

 Literals
 Literals are used to indicate simple values in your Java programs.
 Literal is a programming language term, which essentially means that
what you type is what you get.
 For example, if you type 4 in a Java program, you automatically get an
integer with the value 4. If you type ‘a’, you get a character with the value
a.
Number Literals
 There are several integer literals. 4, for example, is a decimal integer
literal of type int.
 A decimal integer literal larger than an int is automatically of type
long. You also can force a smaller number to a long by appending
an L or l to that number (for example, 4L is a long
integer of value 4).
 Negative integers are preceded by a minus sign—for example,
-45.
 Integers can also be expressed as octal or hexadecimal: a
leading 0 indicates that a number is octal—for example, 0777
or 0004. A leading 0x (or 0X) means that it is in hex (0xFF,
0XAF45).
 Hexadecimal numbers can contain regular digits (0–9) or
upper- or lowercase hex digits (a–f or A–F).
 Floating-point literals usually have two parts: the integer part and
the decimal part—for example, 5.677777. Floating-point literals
result in a floating-point number of type double, regardless of the
precision of that number. You can force the number to the type float
by appending the letter f (or F) to that number—for example, 2.56F.
 You can use exponents in floating-point literals using the
letter e or E followed by the exponent: 10e45 or .36E-2.
Boolean Literals
 Boolean literals consist of the keywords true and false. These
keywords can be used anywhere you need a test or as the only
possible values for boolean variables.
Character Literals
 Character literals are expressed by a single character surrounded
by single quotes: ’a’, ’#’, ’3’,and so on.
 Characters are stored as 16-bit Unicode characters. Table 3.2 lists
the special codes that can represent nonprintable characters, as well
as characters from the Unicode character set.
 Table: Character escape codes.
Escape Meaning
\n Newline
\t Tab
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
\’ Single quote
\” Double quote
\ddd Octal
\xdd Hexadecimal
\udddd Unicode character

Note: Java does not include character codes for \a (bell) or \v (vertical tab).

String Literals
 A combination of characters is a string. Strings in Java are instances of
the class String.
 Strings are not simple arrays of characters as they are in C or C++, but
strings are real objects in Java. They have methods that enable you to
combine, test, and modify strings very easily.
 String literals consist of a series of characters inside double quotes:
“Hi, I’m a string literal.”
“” //an empty string
 Strings can contain character constants such as newline, tab, and Unicode
characters:
“A string with a \t tab in it”
“Nested strings are \”strings inside of\” other strings”
“This string brought to you by Java\u2122”
Note:In the last example, the Unicode code sequence for \u2122 produces a
trademark symbol (™).

 When you use a string literal in your Java program, Java automatically
creates an instance of the class String for you with the value you give it.

Type Conversion and Casting


 It is common to assign a value of one type to a variable of another type. If
the two types are compatible, then Java will perform the conversion
automatically. For example, it is always possible to assign an int value to
a long variable.

 However, not all types are compatible, and thus, not all type conversions
are implicitly allowed. For instance, there is no conversion defined from
double to byte. Fortunately, it is still possible to obtain a conversion
between incompatible types.
 To do so, you must use a cast, which performs an explicit conversion
between incompatible types.

Java’s Automatic Conversions


 When one type of data is assigned to another type of variable, an automatic
type conversion will take place if the following two conditions are met:
■ The two types are compatible.
■ The destination type is larger than the source type.
 For example, the int type is always large enough to hold all valid byte
values, so no explicit cast statement is required.
 For widening conversions, the numeric types, including integer and
floating-point types, are compatible with each other.
 However, the numeric types are not compatible with char or boolean. Also,
char and boolean are not compatible with each other.
 As mentioned earlier, Java also performs an automatic type conversion
when storing a literal integer constant into variables of type byte, short,
or long.
Casting Incompatible Types

 Although the automatic type conversions are helpful, they will not fulfill
all needs. For example, what if you want to assign an int value to a byte
variable? This conversion will not be performed automatically, because a
byte is smaller than an int.

 This kind of conversion is sometimes called a narrowing conversion, since


you are explicitly making the value narrower so that it will fit into the target
type.

 To create a conversion between two incompatible types, you must use a


cast. A cast is simply an explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified
value to.
 For example, the following fragment casts an int to a byte. If the integer’s
value is larger than the range of a byte, it will be reduced modulo (the
remainder of an integer division by the) byte’s range.

int a;
byte b;
// ...
b = (byte) a;
 Thus, when a floating-point value is assigned to an integer type, the
fractional component is lost.

Automatic Type Promotion in Expressions


 In addition to assignments, there is another place where certain type
conversions may occur: in expressions.

 To see why, consider the following.


 In an expression, the precision required of an intermediate value will
sometimes exceed the range of either operand. For example,
examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
 The result of the intermediate term a * b easily exceeds the range of either
of its byte operands. To handle this kind of problem, Java automatically
promotes each byte or short operand to int when evaluating an
expression.

 Sometimes automatic promotions can cause confusing compile-time


errors. For example, this seemingly correct code causes a problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!

 So it is better to use explicit type conversion in expressions.

OPERATORS IN JAVA
Arithmetic Operators

 Arithmetic operators are used in mathematical expressions in the same


way that they are used in algebra.
 The following table lists the arithmetic operators:

Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus

2:Assignment Operators

+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

3: Increment and Decrement


The ++ and the – – are Java’s increment and decrement operators.

The increment operator increases its operand by one. The decrement operator
decreases its operand by one.
For example, this statement: x = x + 1; can be rewritten like this by use of the
increment operator: x++;
Similarly, this statement: x = x - 1; is equivalent to x--;

These operators are unique in that they can appear both in postfix form and
prefix form. In postfix form, the previous value is obtained for use in the
expression, and then the operand is modified.
For example:
x = 42;
y = ++x;
In this case, y is set to 43 as you would expect, because the
increment occurs before x is assigned to y.
Thus, the line y = ++x; is the equivalent of these two statements:
x = x + 1;
y = x;
However, when written like this,
x = 42;
y = x++;
 the value of x is obtained before the increment operator is executed,
so the value of y is 42. Of course, in both cases x is set to 43.
 Here, the line y = x++; is the equivalent of these two statements:
y = x;
x = x + 1;

4:The Bitwise Operators


 Java defines several bitwise operators which can be applied to the integer
types, long, int, short, char, and byte. These operators act upon the
individual bits of their operands. They are summarized in the following
table:
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR a ssignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignmen

Relational Operators
 The relational operators determine the relationship that one operand has
to the other. Specifically, they determine equality and ordering. The
relational operators are shown here:
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Boolean Logical Operators
 The Boolean logical operators shown here operate only on boolean
operands. All of the binary logical operators combine two boolean values
to form a resultant boolean value.

Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else

 The logical Boolean operators, &, |, and ^, operate on boolean values in


the same way that they operate on the bits of an integer. The logical !
operator inverts the Boolean state: !true == false and !false == true.

 The following table shows the effect of each logical operation:


A B A|B A&B A^B !A
False False False False False True
True False True False True False
False True True False True True
True True True True False False

The ?: Operator
 Java includes a special ternary (three-way) operator that can replace
certain types of if-then-else statements.
 The ? has this general form:
expression1 ? expression2 : expression3
 Here, expression1 can be any expression that evaluates to a boolean value.
If expression1 is true, then expression2 is evaluated; otherwise,
expression3 is evaluated. The result of the ? operation is that of the
expression evaluated. Both expression2 and expression3 are required to
return the same type, which can’t be void.

Operator Precedence
 Operator precedence determines the order in which expressions are
evaluated.
As following table shows, new operator has a highest precedence.
COMMAND LINE ARGUMENTS:
 Command line arguments are parameters that are supplied to the
application program at the time of invoking its execution.

 They must be supplied at the time of its execution following the file
name.

 In the main () method, the args is confirmed as an array of string known


as string objects. Any argument provided in the command line at the time
of program execution, are accepted to the array args as its elements.

 The number of element in the array args can be getting with the length
parameter.
For example:
class Add
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(“Addition is=”+c);
}
}
output:
c:\javac Add.java
c:\java Add 5 2
7

CONTROL STATEMNTS
 A programming language uses control statements to cause the flow of
execution to advance and branch based on changes to the state of a
program.

 Java’s program control statements can be put into the following categories:
selection, iteration, and jump.
 Selection statements allow your program to choose different paths
of execution based upon the outcome of an expression or the state of a
variable.
 Iteration statements enable program execution to repeat one or
more statements (that is, iteration statements form loops).
 Jump statements allow your program to execute in a nonlinear
fashion

Selection Statement:
 Selection statement is also called as Decision making statements because
it provides the decision making capabilities to the statements.
 In selection statement, there are two types:
 if statement
 switch statement
 These two statements are allows you to control the flow of a program with
their conditions.

if Statement:
 The “if statement” is also called as conditional branch statement. It is used
to program execution through two paths.
 The syntax of “if statement” is as follows:
Syntax:
if (condition)
{
Statement 1;
...
}
else
{
Statement 2;
...
}
 The “if statement” is a commanding decision making statement and is used
to manage the flow of execution of statements. The “if statement” is the
simplest one in decision statements. Above syntax is shows two ways
decision statement and is used in combination with statements.

 Following figure shows the “if statement”


*Simple if statement:
Syntax:
If (condition)
{
Statement block;
}
Statement-a;
In statement block, there may be single statement or multiple statements. If
the condition is true then statement block will be executed. If the condition is
false then statement block will omit and statement-a will be executed.

*The if…else statement:


Syntax:
If (condition)
{
True - Statement block;
}
else
{
False - Statement block;
}
 If the condition is true then True - statement block will be executed.If the
condition is false then False - statement block will be executed. In both
cases the statement-a will always executed.
 Following figure shows the flow of statement.

*Nesting of if-else statement:


Syntax:
if (condition1)
{
If(condition2)
{
Statement block1;
}
else
{
Statement block2;
}
}
else
{
Statement block3;
}
 If the condition1 is true then it will be goes for condition2. If the condition2
is true then statement block1 will be executed otherwise statement2 will
be executed. If the condition1 is false then statement block3 will be
executed. In both cases the statement4 will always executed.

* The if-else-if Ladder


 A common programming construct that is based upon a sequence
of nested ifs is the if-else-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
 The if statements are executed from the top down. As soon as one
of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed. If
none of the conditions is true, then the final else statement will be
executed. The final else acts as a default condition; that is, if all
other conditional tests fail, then the last else statement is
performed. If there is no final else and all other conditions are false,
then no action will take place.

* switch statement:
 In Java, switch statement check the value of given variable or statement
against a list of case values and when the match is found a statement-
block of that case is executed. Switch statement is also called as multiway
decision statement.
Syntax:
switch(condition)// condition means case value
{
case value-1:statement block1;break;
case value-2:statement block2;break;
case value-3:statement block3;break;

default:statement block-default;break;
}
statement a;
 The condition result can be byte, short, character or an integer. value-
1,value-2,value-3,…are constant and is called as labels. Each of these
values be matchless or unique with the statement. Statement block1,
Statement block2, Statement block3,..are list of statements which contain
one statement or more than one statements.

 Case label is always end with “:” (colon).

 Program: write a program for bank account to perform following


operations.
-Check balance
-withdraw amount
-deposit amount
For example:
import java.io.*;
class bankac
{
public static void main(String args[]) throws Exception
{
int bal=20000;
int ch=Integer.parseInt(args[0]);
System.out.println("Menu");
System.out.println("1:check balance");
System.out.println("2:withdraw amount... plz enter
choice and amount");
System.out.println("3:deposit amount... plz enter
Choice and amount");
System.out.println("4:exit");

switch(ch)
{
case 1:System.out.println("Balance is:"+bal);
break;

case 2:int w=Integer.parseInt(args[1]);


if(w>bal)
{
System.out.println("Not sufficient
balance");
}
bal=bal-w;
System.out.println("Balance is"+bal);
break;

case 3:int d=Integer.parseInt(args[1]);


bal=bal+d;
System.out.println("Balance is"+bal);
break;

default:break;
}
}
}
Output:
C:\MCA>javac bankac.java
C:\MCA>java bankac 1
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is:20000
C:\MCA>java bankac 2 2000
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is18000
* Nested switch Statements
 You can use a switch as part of the statement sequence of an outer
switch. This is called a nested switch.

 Since a switch statement defines its own block, no conflicts arise


between the case constants in the inner switch and those in the
outer switch.
 For example, the following fragment is perfectly valid:
switch(count) {
case 1:
switch(target)
{ // nested switch
case 0:
System.out.println("target is zero");
break;
case 1:
// no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...

 Here, the case 1: statement in the inner switch does not conflict
with the case 1: statement in the outer switch. The count variable
is only compared with the list of cases at the outer level. If count is
1, then target is compared with the inner list cases.

 In summary, there are three important features of the switch


statement to note:
■ The switch differs from the if in that switch can only test for
equality, whereas if can evaluate any type of Boolean expression.
That is, the switch looks only for a match between the value of the
expression and one of its case constants.
■ No two case constants in the same switch can have identical
values. Of course, a switch statement enclosed by an outer switch
can have case constants in common.
■ A switch statement is usually more efficient than a set of nested
ifs.

 Iteration Statement:

 The process of repeatedly executing a statements and is called as looping.


The statements may be executed multiple times (from zero to infinite number). If
a loop executing continuous then it is called as Infinite loop. Looping is also
called as iterations.

 In Iteration statement, there are three types of operation:


 for loop
 while loop
 do-while loop
for loop:
 The for loop is entry controlled loop. It means that it provide a more
concious loop control structure.
Syntax:
for(initialization;condition;iteration)
{
Statement block;
}
while loop:
 The while loop is entry controlled loop statement. The condition is
evaluated, if the condition is true then the block of statements or
statement block is executed otherwise the block of statement is not
executed.
Syntax:
While(condition)
{
Statement block;
}
do-while loop:
 In do-while loop, first attempt of loop should be execute then it check the
condition. The benefit of do-while loop/statement is that we get entry in
loop and then condition will check for very first time. In while loop,
condition will check first and if condition will not satisfied then the loop
will not execute.
Syntax:
do
{
Statement block;
}
While(condition);
 In program,when we use the do-while loop, then in very first
attempt, it allows us to get enter in loop and execute that loop and
then check the condition.

Jumps in statement:
 Statements or loops perform a set of operartions continually until the
control variable will not satisfy the condition. but if we want to break the
loop when condition will satisy then Java give a permission to jump from
one statement to end of loop or beginning of loop as well as jump out of a
loop.

 “break” keyword use for exiting from loop and “continue” keyword use for
continuing the loop.
 Following statements shows the exiting from loop by using “break”
statement.

do-while loop:
do
{
if(condition)
{
break;//exit from if loop and do-while loop
}
}
While(condition);

For loop:
for(…………)
{
if(condition)
break; ;//exit from if loop and for loop
}

While loop:
while(…………)
{
If(cond)
break; ;//exit from if loop and while loop
}

Following statements shows the continuing the loop by using “continue”


statement.
do-while loop:
do
{
if(condition)
{
continue;//continue the do-while loop
}
}While(condition);

For loop:
for(…………)
{
if(…………..)
continue ;// continue the for loop
}

While loop:
while(…………)
{
if(…………..)
continue ;// continue the while loop
}

 Labelled block/ Jump to specific location:


We can give label to a block of statements with any valid name.

following example shows the use of label, break and continue.


Import java.io.*;
class Demo
{
public static void main(String args[]) throws Exception
{
int j,i;
LOOP1: for(i=1;i<100;i++)
{
System.out.println(““);
if(i>=10)
{
break;
}
for(j=1;j<100;j++)
{
System.out.println(“$ ”);
if(i==j)
{
continue LOOP1;
}
}
}
System.out.println(“ End of program “);
}
}
Output:
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
$$$$$$$$
$$$$$$$$$
End of program

Return statement:
 The last control statement is return. 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.
 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 which it is
executed.

 The following example illustrates this point. Here, eturn causes


execution to return to the Java run-time system, since it is the run-
time system that calls main( ).
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");

if(t) return; // return to caller

System.out.println("This won't execute.");


}
}
 The output from this program is shown here:
Before the return.

You might also like