Java U1
Java U1
UNIT I
INTRODUCTION TO JAVA:
THE KEY ATTRIBUTES OF OBJECT ORIENTED PROGRAMMING:
Object
Class
Data Abstraction and Encapsulation
Dynamic Binding
Message Passing
Inheritance
Polymorphism
Object:
Object is a collection of number of entities. Object take up space in the memory.
Objects are instances of classes. When a program is executed, the objects interact by
sending messages to one another. Each object contains data and code to manipulate the
data. Objects can interact without having no details of each other’s data or code.
Class:
Class is a collection of objects of similar type. Objects are variables of the type
class. Once a class has been defined, we can create any number of objects belonging to
that class.
Ex: banana, orange are the objects of class Fruit.
Fruit mango;
By above mango object is created for class Fruit.
Data Abstraction and Encapsulation:
Combining data and functions into a single unit called class and the process is
known as Encapsulation. Data encapsulation is important feature of a class. Class contains
both data and functions. Data is not accessible from the outside world and only those
functions which are present in the class can access the data. The insulation of the data
from direct access by the program is called data hiding or data abstraction. Hiding the
complexity of program is called abstraction only essential features are represented. In
short we can say that internal working is hidden.
Dynamic Binding:
Refers to linking of function call with function defination is called binding and when
it is take place at run time called dynamic binding.
1
JAVA PROGRAMMING
Message Passing:
The process by which one object can interact with other object is called message
passing.
Inheritance:
It is the process by which object of one class aquire the properties or features of
objects of another class. The concept of inheritance provide the idea of reusability means
we can add additional features to an existing class without Modifying it. This is possible by
driving a new class from the existing one. The new class will have the combined features
of both the classes.
Example: Parrot is a part of the class flying bird which is again a part of the class bird.
Polymorphism:
A Greek term means ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of data
used in the operation.
Example:
Operator Overloading
You can redefine or overload most of the built in operators.
Function Overloading
You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the type and/or the number of
arguments in the argument list but not only by return type.
2
JAVA PROGRAMMING
3
JAVA PROGRAMMING
Object - Oriented:
•Java follows object oriented model.
•So, it supports all the features of object oriented model like:
Encapsulation
Inheritance
Polymorphism
Abstraction
Robust:
•A program or an application is said to be robust(reliable) when it is able to give some
response in any kind of context.
•Java’s features help to make the programs robust. Some of those features are:
1. Type checking
2. Exception handling
Multithreaded:
•Java supports multithreading which is not supported by C and C++.
•A thread is a light weight process.
•Multithreading increases CPU efficiency.
•A program can be divided into several threads and each thread can be executed
concurrently or in parallel with the other threads.
•Real world example for multithreading is computer. While we are listening to music, at
the same time we can write in a word document or play a game.
Architecture - Neutral:
•Byte code helps Java to achieve portability.
•Byte code can be executed on computers having any kind of operating system or any
kind of CPU.
•Since Java applications can run on any kind of CPU, Java is architecture – neutral.
Interpreted and High Performance:
•In Java 1.0 version there is an interpreter for executing the byte code. As interpreter is
quite slow when compared to a compiler, java programs used to execute slowly.
•After Java 1.0 version the interpreter was replaced with JIT(Just-In-Time) compiler.
•JIT compiler uses Sun Micro system’s Hot Spot technology.
•JIT compiler converts the byte code into machine code piece by piece and caches them
for future use.
•This enhances the program performance means it executes rapidly.
Distributed:
4
JAVA PROGRAMMING
•Java supports distributed computation using Remote Method Invocation (RMI) concept.
•The server and client(s) can communicate with another and the computations can be
divided among several computers which makes the programs to execute rapidly.
•In distributed systems, resources are shared.
Dynamic:
•The Java Virtual Machine(JVM) maintains a lot of runtime information about the program
and the objects in the program.
•Libraries are dynamically linked during runtime.
•So, even if you make dynamic changes to pieces of code, the program is not effected.
THE JAVA KEYWORDS:
Here is a list of keywords in the Java programming language. You cannot use any of
the following as identifiers in your programs. The keywords const and goto are reserved,
even though they are not currently used. true, false, and null might seem like keywords,
but they are actually literals; you cannot use them as identifiers in your programs.
1. abstract 17. extends 34. protected
2. assert (since Java 18. final 35. public
1.4) 19. finally 36. return
3. boolean 20. float 37. short
4. break 21. for 38. static
5. byte 22. goto (not used) 39. strictfp (since Java 1.2)
6. case 23. if 40. super
7. catch 24. implements 41. switch
8. char 25. import 42. synchronized
9. class 26. instanceof 43. this
10. const (not used) 27. int 44. throw
11. continue 28. interface 45. throws
12. default 29. long 46. transient
13. do 30. native 47. try
14. double 31. new 48. void
15. else 32. package 49. volatile
16. enum (since Java 33. private 50. while
5.0)
1.abstract: -
5
JAVA PROGRAMMING
Java provides abstract keyword to signify something empty. By empty we mean that it
has no definition or implementation. Keyword abstract is used before the classes and
methods. At the time of declaring a class we mark it as abstract. An abstract class cannot
be instantiated. It means an abstract class cannot have Objects. By abstract method, we
mean that method doesn't have any body. An abstract method doesn't have any
statements to execute. Classes that contain abstract method must also be assigned as
abstract class and implementation to their abstract method must be provided by
extending those classes. If subclasses fail to provide implementation to super-class
abstract methods, than they are also marked as abstract.
2. assert: -
Java provides us with a debugging keyword called as assert. In Java, assert is a normal
Java statement which a programmer puts in the code, that he/she thinks will always be
true. Generally, assert statements are being used by the programmer for the debugging
purpose. Assertion statements can be turned on or off. While running a program if we
enable assertion then wherever our assert statement gets failed Assertion Error is thrown
by the program and whole program gets terminated. Generally, assertions are placed by
programmer in the code where he believes that statement will be true. After enabling
assertion if there is a failure, programmer gets an idea that in code there is some bug. The
code fails with an Assertion Error.
3. boolean: -
A boolean keyword in Java is a data type for a variable which can store two values, true
or false. Generally, boolean keyword is a data type which has size of 1 bit. In Java I am not
sure about the size that whether it store 1 bit or not.
4. break: -
In Java, 'break' keyword is of quite high importance. As the name suggest, break
statement breaks code from one point and transfer flow to other part of program to
execute. Generally let say in if block you have placed a break statement. If your code
enters if statement an encounters break statement it will stop executing further if block
and come out of if block and continue to execute.
5. byte :-
In Java, byte keyword is used as a data type for storing 8 bits of information for an
integer. If it’s used before a method definition than that method, when called will always
return a byte value.
6. case :-
6
JAVA PROGRAMMING
7
JAVA PROGRAMMING
19. finally :-
In Java, finally keyword is used to define a block of statements after try to catch
blocks. This block executes after try block, or after catch block, or before any return
statement.
20. float :-
In Java, float keyword is used as a data type for storing 32 bits of information for a
float type. If it’s used before a method definition than that method when called will always
return a float value.
21. for :-
In Java, for keyword is used to create looping statement that is for loop. In this for
loop a counter variable is initialized, than a boolean condition is evaluated and compared
with counter variable or any expression which turns out to either true or false. If the
condition comes out to be true a block of statements following for keyword executes, if
8
JAVA PROGRAMMING
28. interface :-
In Java, interface is a special type of structure which contains abstract methods,
constant fields which are generally static or final.
29. long :-
In Java, long keyword is used as a data type for storing 64 bits of information for an
integer type. If it’s used before a method definition than that method when called will
always return a long value.
30. native :-
9
JAVA PROGRAMMING
38. static :-
In Java, static keyword is used when you want to declare method, fields and inner
class as class members rather object members, generally static members belong to a
class rather than instance of that class. Therefore only one copy is made for them and
used by the class as its own implementation.
39. strictfp :-
10
JAVA PROGRAMMING
45. throws :-
In Java, we use throws keyword in the method declarations. If we get an exception
in a method and method has no implementation for that exception, than method throws
11
JAVA PROGRAMMING
an exception. The exception thrown has been handled by the method who has called to
current method in execution.
46. transient :-
Whenever we declare a variable as transient, that variable is not the part of Object
serialization. When an object gets saved through default serialization all the non-transient
variable retain their value after deserialization. If you want the variable should have
default value after deserialization than make it transient.
47. try :-
In Java, whenever we want to do exception handling we use try keyword. Generally
try block is used where we are sure that exception can occur. In try block statements are
executed normally and as soon as exception occur it is handled my catch keyword
following try block. It must have at least one catch or finally block.
48. void :-
In Java, when we use void before any method declaration, we make sure that
method doesn't return any value.
49. volatile :-
In Java, volatile keyword provides a lock free mechanism. If a variable is assigned as
volatile than all the threads accessing it can modify its current value without keeping a
separate copy. A volatile keyword is accessed by all threads simultaneously. They operate
on current value of variable rather than cached value.
50. while :-
In Java, while keyword is used to create looping statement that is while loop. In this
while loop a boolean condition is evaluated and compared with counter variable or any
expression which turns out to either true or false. If the condition comes out to be true a
block of statements following while keyword executes, if condition comes out to be false
the while loop terminates.
51. false :-
In Java, false keyword is the literal for the data type Boolean. Expressions are
compared by this literal value.
52. null :-
12
JAVA PROGRAMMING
In Java, null keyword is the literal for the reference variable. Expressions are
compared by this literal value. It is a reserved keyword.
53. true :-
In Java, true keyword is the literal for the data type Boolean. Expressions are
compared by this literal value. - See more at: http://www.hubberspot.com/2012/03/top-50-
java-keywords-complete-reference.html#sthash.Fwpuhrxd.dpuf
IDENTIFIERS IN JAVA:
Identifiers are the names of variables, methods, classes, packages and interfaces.
Unlike literals they are not the things themselves, just ways of referring to them. In the
HelloWorld program, HelloWorld, String, args, main and println are identifiers.
Identifiers must be composed of letters, numbers, the underscore _ and the dollar
sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.
Each variable has a name by which it is identified in the program. It's a good idea to
give your variables mnemonic names that are closely related to the values they hold.
Variable names can include any alphabetic character or digit and the underscore _. The
main restriction on the names you can give your variables is that they cannot contain any
white space. You cannot begin a variable name with a number. It is important to note that
as in C but not as in Fortran or Basic, all variable names are case-sensitive. MyVariable is
not the same as myVariable. There is no limit to the length of a Java variable name. The
following are legal variable names:
MyVariable
myvariable
MYVARIABLE
x
i
_myvariable
$myvariable
_9pins
andros
DATA TYPES:
As with all modern programming languages, Java supports several types of data.
You may use these types to declare variables and to create arrays. As you will see, Java’s
approach to these items is clean, efficient, and cohesive.
Java Is a Strongly Typed Language
13
JAVA PROGRAMMING
It is important to state at the outset that Java is a strongly typed language. Indeed,
part of Java’s safety and robustness comes from this fact. Let’s see what this means. First,
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.
The Primitive Types:
Java defines eight primitive types of data: byte, short, int, long, char, float, double,
and boolean.
The primitive types are also commonly referred to as simple types, and both terms will be
used in this book. 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.
You can use these types as-is, or to construct arrays or your own class types. Thus, they
form the basis for all other types of data that you can create.
The primitive types represent single values—not complex objects. Although Java
isotherwise completely object-oriented, the primitive types are not. They are analogous to
the simple types found in most other non–object-oriented languages. The reason for this is
efficiency.Making the primitive types into objects would have degraded performance too
much.
The primitive types are defined to have an explicit range and mathematical
behavior. Languages such as C and C++ allow the size of an integer to vary based upon
the dictates of the execution environment. However, Java is different. Because of Java’s
portability requirement, all data types have a strictly defined range.
For example, an int is always 32 bits,
14
JAVA PROGRAMMING
Regardless of the particular platform. This allows programs to be written that are
guaranteed to run without porting on any machine architecture. While strictly specifying
the size of an integer may cause a small loss of performance in some environments, it is
necessary in order to achieve portability.
Let’s look at each type of data in turn.
Integers
Java defines four integer types: byte, short, int, and long.
All of these are signed, positive and negative values. Java does not support
unsigned, positive-only integers. Many other computer languages support both signed and
unsigned integers. However, Java’s designers felt that unsigned integers were
unnecessary. Specifically, they felt that the concept of unsigned was used mostly to
specify the behavior of the high-order bit, which defines the sign of an integer value. Java
manages the meaning of the high-order bit differently, by adding a special “unsigned right
shift” operator. Thus, the need for an unsigned integer type was eliminated.
The width of an integer type should not be thought of as the amount of storage it
consumes, but rather as the behavior it defines for variables and expressions of that type.
The Java run-time environment is free to use whatever size it wants, as long as the types
behave as you declared them. The width and ranges of these integer types vary widely, as
shown in this table:
15
JAVA PROGRAMMING
byte b, c;
short:
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably
the least-used Java type. Here are some examples of short variable declarations:
short s;
short t;
int:
The most commonly used integer type is int. It is a signed 32-bit type that has a
range from 2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int
are commonly employed to control loops and to index arrays. Although you might think
that using a byte or short would be more efficient than using an int in situations in which
the larger range of an int is not needed, this may not be the case. The reason is that when
byte and short values are used in an expression they are promoted to int when the
expression is evaluated. Therefore, int is often the best choice when an integer is needed.
Long:
long is a signed 64-bit type and is useful for those occasions where an int type is
not large enough to hold the desired value. The range of a long is quite large. This makes
it useful when big, whole numbers are needed. For example, here is a program that
computes the number of miles that light will travel in a specified number of days.
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
16
JAVA PROGRAMMING
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
Clearly, the result could not have been held in an int variable.
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.
Java implements the standard (IEEE–754) set of floating-point types and operators. There
are two kinds of floating-point types, float and double, which represent single- and double-
precision numbers, respectively. Their width and ranges are shown here:
Float:
The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double precision,
but will become imprecise when the values are either very large or very small. Variables of
type float are useful when you need a fractional component, but don’t require a large
degree of precision.
For example, float can be useful when representing dollars and cents.
Here are some example float variable declarations:
float hightemp, lowtemp;
double:
Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double precision is actually faster than single precision on some modern processors that
have been optimized for high-speed mathematical calculations.
All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.
When you need to maintain accuracy many iterative calculations, or are manipulating
large-valued numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle:
17
JAVA PROGRAMMING
Characters
In Java, the data type used to store characters is char.
Note: char in Java is not the same as char in C or C++. In C/C++, char 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. It is a unification of dozens of character sets, such as Latin, Greek,
Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires
16 bits.
Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are
no negative chars.
The standard set of characters known as ASCII still ranges from 0 to 127 as always,
and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is
designed to allow programs to be written for worldwide use, it makes sense that it would
use Unicode to represent characters. Of course, the use of Unicode is somewhat inefficient
for languages such as English, German, Spanish, or French, whose characters can easily
be contained within 8 bits.
But such is the price that must be paid for global portability.
Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
18
JAVA PROGRAMMING
19
JAVA PROGRAMMING
Java has a primitive 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, as in
the case of a < b. boolean is also the type required by the conditional expressions that
govern the control statements such as if and for.
Here is a program that demonstrates the boolean type:
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statementChapter 3: Data Types, Variables, and
Arrays 39
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:
b is false
b is true
This is executed.
10 > 9 is true
There are three interesting things to notice about this program.
First, as you can see, when a boolean value is output by println( ), “true” or “false” is
displayed. Second, the value of a boolean variable is sufficient, by itself, to control the if
statement. There is no need to write an if statement like this:
if(b == true) ...
20
JAVA PROGRAMMING
Third, the outcome of a relational operator, such as <,isa boolean value. This is why the
expression 10>9 displays the value “true.” Further, the extra set of parentheses around
10>9 is necessary because the + operator has a higher precedence than the >.
Escape Sequence: Java supports all escape sequence which is supported by C/ C++. A
character preceded by a backslash (\) is an escape sequence and has special
meaning to the compiler. When an escape sequence is encountered in a print
statement, the compiler interprets it accordingly.
VARIABLES:
The variable is the basic unit of storage in a Java program. A variable is
defined by the combination of an identifier, a type, and an optional initializer. In addition,
all variables have a scope, which defines their visibility, and a lifetime. These elements are
examined next.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a
variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. (Class and
interface types are discussed later in Part I of this book.) The identifier is the name of the
variable. You can initialize the variable by specifying an equal sign and a value. Keep in
mind that the initialization expression must result in a value of the same (or compatible)
type as that specified for the variable. To declare more than one variable of the specified
type, use a comma-separated list.
21
JAVA PROGRAMMING
scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
Many other computer languages define two general categories of scopes: global and
local.
However, these traditional scopes do not fit well with Java’s strict, object-oriented model.
In Java, the two major scopes are those defined by a class and those defined by a method.
Even this distinction is somewhat artificial. However, since the class scope has several
unique properties and attributes that do not apply to the scope defined by a method, this
distinction makes some sense. Because of the differences, a discussion of class scope (and
variables declared within it) is deferred, when classes are described.
For now, we will only examine the scopes defined by or within a method.
The scope defined by a method begins with its opening curly brace. However, if that
method has parameters, they too are included within the method’s scope.
As a general rule, variables declared inside a scope are not visible (that is, accessible) to
code that is defined outside that scope. Thus, when you declare a variable within a scope,
you are localizing that variable and protecting it from unauthorized access and/or
modification.
Indeed, the scope rules provide the foundation for encapsulation.
Scopes can be nested.
For example, each time you create a block of code, you are creating a new, nested
scope. When this occurs, the outer scope encloses the inner scope. This means that
objects declared in the outer scope will be visible to code within the inner scope. However,
the reverse is not true. Objects declared within the inner scope will not be visible outside
it.
To understand the effect of nested scopes, consider the following program:
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
23
JAVA PROGRAMMING
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
As the comments indicate, the variable x is declared at the start of main( )’s scope
and is accessible to all subsequent code within main( ). Within the if block, y is declared.
Since a block defines a scope, y is only visible to other code within its block. This is why
outside of its block, the line y = 100; is commented out.
Within a block, variables can be declared at any point, but are valid only after they
are declared. Thus, if you define a variable at the start of a method, it is available to all of
the code within that method. Conversely, if you declare a variable at the end of a block, it
is effectively useless, because no code will have access to it.
For example, this fragment is invalid because count cannot be used prior to its
declaration:
// This fragment is wrong!
count = 100; // oops! cannot use count before it is declared!
int count;
Here is another important point to remember:
variables are created when their scope is entered, and destroyed when their scope
is left. This means that a variable will not hold its value once it has gone out of scope.
Therefore, variables declared within a method will not hold their values between calls to
that method. Also, a variable declared within a block will lose its value when the block is
left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, then that variable will be reinitialized each
time the block in which it is declared is entered. For example, consider the next program.
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
24
JAVA PROGRAMMING
26
JAVA PROGRAMMING
b = (byte) a;
Adifferent type of conversion will occur when a floating-point value is assigned to an
integer type: truncation. As you know, integers do not have fractional components. Thus,
when a floating-point value is assigned to an integer type, the fractional component is lost.
For example, if the value 1.23 is assigned to an integer, the resulting value will simply be
1. The 0.23 will have been truncated. Of course, if the size of the whole number
component is too large to fit into the target integer type, then that value will be reduced
modulo the target type’s range.
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
27
JAVA PROGRAMMING
d and b 323.142 67Let’s look at each conversion. When the value 257 is cast into a byte
variable, the result is the remainder of the division of 257 by 256 (the range of a byte),
which is 1 in this case.
When the d is converted to an int, its fractional component is lost. When d is converted to
a byte, its fractional component is lost, and the value is reduced modulo 256, which in this
case is 67.
Conclusion of Type Conversion:
• Size Direction of Data Type
– Widening Type Conversion (Casting down)
• Smaller Data Type à Larger Data Type
– Narrowing Type Conversion (Casting up)
• Larger Data Type à Smaller Data Type
• Conversion done in two ways
– Implicit type conversion
• Carried out by compiler automatically
– Explicit type conversion
• Carried out by programmer using casting
byte
byte ->
•
– -> short,
short, int,
int, long,
long, float,
Widening Type Converstion
float, double
double
Implicit conversion by compiler automatically
short
short -> -> int,
int, long,
long, float,
float, double
double
char
char -> -> int,
int, long,
long, float,
float, double
double
int
int ->
-> long,
long, float,
float, double
double
•
long
long ->-> float,
float, double
Narrowing Type Conversion
double
– float
float ->-> double
double
Programmer should describe the conversion explicitly
28
byte
JAVA ->
byte -> char
char
PROGRAMMING
short
short ->-> byte,
byte, char
char
char
char ->-> byte,
byte, short
short
int
int ->
-> byte,
byte, short,
short, char
char
long
long ->-> byte,
byte, short,
short, char,
char, intint
•
float
float ->
-> byte,
byte, short,
short, char,
char, int,
int, long
byte and short are always promoted to int long
double
double ->
•
-> byte,
byte, short,
short, char,
char, int,
int, long,
long, float
float
if one operand is long, the whole expression is promoted to long
• if one operand is float, the entire expression is promoted to float
• if any operand is double, the result is double
• General form: (targetType) value
• Examples:
• 1) integer value will be reduced module bytes range:
int i;
byte b = (byte) i;
• 2) floating-point value will be truncated to integer value:
float f;
int i = (int) f;
OPERATORS:
Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
The 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:
Assume integer variable A holds 10 and variable B holds 20, then:
Operator Description Example
29
JAVA PROGRAMMING
30
JAVA PROGRAMMING
Bitwise operator works on bits and performs bit-by-bit operation. Assume if A = 60; and B
= 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
31
JAVA PROGRAMMING
Shift right zero fill operator. The left operands value is moved A >>>2 will give
>>> right by the number of bits specified by the right operand and 15 which is 0000
shifted values are filled up with zeros. 1111
32
JAVA PROGRAMMING
C/A
C %= A is
Modulus AND assignment operator, It takes modulus using
%= equivalent to C =
two operands and assign the result to left operand
C%A
C <<= 2 is same
<<= Left shift AND assignment operator
as C = C << 2
C >>= 2 is same
>>= Right shift AND assignment operator
as C = C >> 2
C &= 2 is same
&= Bitwise AND assignment operator
as C = C & 2
C ^= 2 is same
^= bitwise exclusive OR and assignment operator
as C = C ^ 2
C |= 2 is same as
|= bitwise inclusive OR and assignment operator
C=C|2
Misc Operators:
There are few other operators supported by Java Language.
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the operator is to
decide which value should be assigned to the variable. The operator is written as:
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {
33
JAVA PROGRAMMING
}
This would produce the following result:
Value of b is : 30
Value of b is : 20
instanceof Operator:
This operator is used only for object reference variables. The operator checks
whether the object is of a particular type(class type or interface type). instanceof operator
is written as:
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check
for the class/interface type on the right side, then the result will be true. Following is the
example:
public class Test {
35
JAVA PROGRAMMING
statements are categorized into selection control statements, iteration control statements
and jump control statements.
Java’s Selection Statements:
Java supports two selection statements: if and switch. These statements allow
us to control the flow of program execution based on condition.
if Statement:
if statement performs a task depending on whether a condition is true or false.
Syntax: if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement
enclosed in
curly braces (that is, a block). The condition is any expression that returns a
boolean
value. The else clause is optional.
Program : Write a program to find biggest of three numbers.
//Biggest of three numbers
class BiggestNo
{ public static void main(String args[])
{ int a=5,b=7,c=6;
if ( a > b && a>c)
System.out.println ("a is big");
else if ( b > c)
System.out.println ("b is big");
else
System.out.println ("c is big");
}
}
Output:
D:/kumar>javac BiggestNo.java
D:/kumar>java BiggestNo
b is big
D:/kumar>
36
JAVA PROGRAMMING
Switch Statement:
When there are several options and we have to choose only one option from
the available ones, we can use switch statement.
Syntax: switch (expression)
{ case value1: //statement sequence
break;
case value2: //statement sequence
break;
………….…..
case valueN: //statement sequence
break;
default: //default statement sequence
}
Here, depending on the value of the expression, a particular corresponding case will be
executed.
Program : Write a program for using the switch statement to execute a particular task
depending on color value.
//To display a color name depending on color value
class ColorDemo
{ public static void main(String args[])
{ char color = ‘r’;
switch (color)
{ case ‘r’: System.out.println (“red”); break;
case ‘g’: System.out.println (“green”); break;
case ‘b’: System.out.println (“blue”); break;
case ‘y’: System.out.println (“yellow”); break;
case ‘w’: System.out.println (“white”); break;
default: System.out.println (“No Color Selected”);
}
}
}
Output:
D:/kumar>javac ColorDemo.java
D:/kumar>java ColorDemo
37
JAVA PROGRAMMING
red
D:/kumar>
38
JAVA PROGRAMMING
do-while Loop:
do…while loop repeats a group of statements as long as condition is
true. In do...while loop, the statements are executed first and then the condition is tested.
do…while loop is also called as exit control loop.
Syntax: do
{
statements;
} while (condition);
Program : Write a program to generate numbers from 1 to 20.
//Program to generate numbers from 1 to 20.
class Natural1
{ public static void main(String args[])
{ int i=1;
do
{ System.out.print (i + “\t”);
i++;
} while (i <= 20);
}
}
Output:
D:/kumar>javac Natural1.java
D:/kumar>java Natural1
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
D:/kumar>
for Loop:
The for loop is also same as do…while or while loop, but it is more compact
syntactically. The for loop executes a group of statements as long as a condition is true.
Syntax: for (expression1; expression2; expression3)
{ statements;
}
39
JAVA PROGRAMMING
{ int i=1;
while (true)
{ System.out.print (i + “\t”);
i++;
if (i <= 20 )
continue;
else
break;
}
}
}
Output:
D:/kumar>javac Natural.java
D:/kumar>java Natural
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
D:/kumar>
return statement:
Ø return statement is useful to terminate a method and come back to the calling method.
Ø return statement in main method terminates the application.
Ø return statement can be used to return some value from a method to a calling method.
Syntax: return; (or)
return value; // value may be of any type
}
}
Output:
D:/kumar>javac ReternDemo.java
D:/kumar>java ReturnDemo
Before the return
D:/kumar>
Note: goto statement is not available in java, because it leads to confusion and
forms infinite loops.
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. Aspecific element in an
array is accessed by its index. Arrays offer a convenient means of grouping related
information.
On which memory, arrays are created in java?
Arrays are created on dynamic memory by JVM. There is no question of static memory in
Java; everything (variable, array, object etc.) is created on dynamic memory only.
Arrays: An array represents a group of elements of same data type. Arrays are
generally categorized into two types:
Single Dimensional arrays (or 1 Dimensional arrays)
Multi-Dimensional arrays (or 2 Dimensional arrays, 3 Dimensional arrays, …)
43
JAVA PROGRAMMING
44
JAVA PROGRAMMING
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.
The advantage of using arrays is that they simplify programming by replacing a lot of
statements by just one or two statements. In C/C++, by default, arrays are created on
static memory unless pointers are used to create them. In java, arrays are created on
dynamic memory i.e., allotted at runtime by JVM.
Program : Write a program to accept elements into an array and display the same.
// program to accept elements into an array and display the same.
import java.io.*;
class ArrayDemo1
{
public static void main (String args[]) throws IOException
{ //Create a BufferedReader class object (br)
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System.out.println (“How many elements: “ );
int n = Integer.parseInt (br.readLine ());
//create a 1D array with size n
int a[] = new int[n];
System.out.print ("Enter elements into array : ");
for (int i = 0; i<n;i++)
a [i] = Integer.parseInt ( br.readLine ());
System.out.print (“The entered elements in the array are: “);
for (int i =0; i < n; i++)
System.out.print (a[i] + “\t”);
}
}
Output:
D:/kumar>javac ArrayDemo1.java
D:/kumar>java ArrayDemo1
How many elements:5
Enter elements into arry:10 20 30 40 50
The entered elements in the array are:10 20 30 40 50
D:/kumar>
45
JAVA PROGRAMMING
D:/kumar>java Matrix
1 2 3
4 5 6
D:/kumar>
47
JAVA PROGRAMMING
int arr[][][]={{{50,51,52},{60,61,62}},{{70,71,72},{80,81,82}},
{{65,66,67},{75,76,77}}};
for(dept=0;dept<3;dept++)
{
System.out.println("dept"+(dept+1)+":");
for(student=0;student<2;student++)
{
System.out.print("student"+(student+1)+"marks:");
for(marks=0;marks<3;marks++)
{
System.out.print(arr[dept][student][marks]+" ");
tot+=arr[dept][student][marks];
}
System.out.println("total:"+tot);
tot=0;
}
System.out.println();
}
}
}
arrayname.length:
If we want to know the size of any array, we can use the property ‘length’ of
an array. In case of 2D, 3D length property gives the number of rows of the array.
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array
variable.
For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
48
JAVA PROGRAMMING
args[4]: 100
args[5]: -1
REMEMBER All command-line arguments are passed as strings. You must convert numeric
values to their internal forms manually.
STRINGS
Strings:
A String represents group of characters. Strings are represented as String
objects in java.
The String class is defined in the java.lang package and hence is implicitly available
to all the programs in Java. The String class is declared as final, which means that it
cannot be subclassed. It extends the Object class and implements the Serializable,
Comparable, and CharSequence interfaces.
50
JAVA PROGRAMMING
51
JAVA PROGRAMMING
Modifier methods:
concat(g), replace(cWhich, cReplacement), toLowerCase(), toUpperCase(), trim().
The String class defines several constructors. The most common constructor of the
String class is the one given below:
This constructor constructs a new String object initialized with the same sequence
of the characters passed as the argument. In other words, the newly created String object
52
JAVA PROGRAMMING
public String()
This constructor creates an empty String object. However, the use of this
constructor is unnecessary because String objects are immutable.
This constructor creates a new String object initialized with the same sequence of
characters currently contained in the array that is passed as the argument to it.
This constructor creates a new String object initialized with the same sequence of
characters currently contained in the subarray. This subarray is derived from the character
array and the two integer values that are passed as arguments to the constructor. The int
variable startindex represents the index value of the starting character of the subarray,
and the int variable len represents the number of characters to be used to form the new
String object.
This constructor creates a new String object that contains the same sequence of
characters currently contained in the string buffer argument.
The array of bytes that is passed as an argument to the constructor contains the
ASCII character set. Therefore, this array of bytes is first decoded using the default charset
of the platform. Then the constructor creates a new String object initialized with same
sequence of characters obtained after decoding the array.
53
JAVA PROGRAMMING
This constructor creates the String object after decoding the array of bytes and by using
the subarray of bytes.
The String class defines the length() method that determines the length of a string.
The length of a string is the number of characters contained in the string. The signature of
the length() method is given below:
public int length()
The + operator is used to concatenate two strings, producing a new String object as
the result. For example,
This code will display the string "Our daily sale is 500 dollars".
The + operator may also be used to concatenate a string with other data types. For
example,
This code will display the string "Our daily sale is 500 dollars". In this case, the
variable sale is declared as int rather than String, but the output produced is the same.
54
JAVA PROGRAMMING
This is because the int value contained in the variable sale is automatically converted to
String type, and then the + operator concatenates the two strings.
String Comparison
The String class defines various methods that are used to compare strings or
substrings within strings. Each of them is discussed in the following sections:
Note: Since strings are stored as a memory address, the == operator can't be used for
comparisons. Use equals() and equalsIgnoreCase() to do comparisons. A simple example
is:
equals()
The equals() method is used to check whether the Object that is passed as the
argument to the method is equal to the String object that invokes the method. It returns
true if and only if the argument is a String object that represents the same sequence of
characters as represented by the invoking object. The signature of the equals() method is
as follows:
boolean i=str1.equals(str2)
equalsIgnoreCase()
The equalsIgnoreCase() method is used to check the equality of the two String
objects without taking into consideration the case of the characters contained in the two
strings. It returns true if the two strings are of the same length and if the corresponding
characters in the two strings are the same ignoring case. The signature of the
equalsIgnoreCase() method is:
55
JAVA PROGRAMMING
compareTo()
where, str is the String being compared to the invoking String. The compareTo()
method returns an int value as the result of String comparison. The meaning of these
values are given in the following table:
compareToIgnoreCase()
The String class also has the compareToIgnoreCase() method that compares two
strings without taking into consideration their case difference. The signature of the
method is given below:
regionMatches()
The regionMatches() method is used to check the equality of two string regions
where the two string regions belong to two different strings. The signature of the method
is given below:
public boolean regionMatches(int startindex, String str2, int startindex2, int len)
There is also an overloaded version of the method that tests the equality of the
substring ignoring the case of characters in the substring. Its signature is given below:
56
JAVA PROGRAMMING
In both signatures of the method, startindex specifies the starting index of the
substring within the invoking string. The str2 argument specifies the string to be
compared. The startindex2 specifies the starting index of the substring within the string to
be compared. The len argument specifies the length of the substring being compared.
However, in the latter signature of the method, the comparison is done ignoring the case
of the characters in the substring only if the ignoreCase argument is true.
startsWith()
The startsWith() method is used to check whether the invoking string starts with the
same sequence of characters as the substring passed as an argument to the method. The
signature of the method is given below:
public boolean startsWith(String prefix)
There is also an overloaded version of the startsWith() method with the following
signature:
public boolean startsWith(String prefix, int startindex)
In both signatures of the method given above, the prefix denotes the substring to
be matched within the invoking string. However, in the second version, the startindex
denotes the starting index into the invoking string at which the search operation will
commence.
endsWith()
The endsWith() method is used to check whether the invoking string ends with the
same sequence of characters as the substring passed as an argument to the method. The
signature of the method is given below:
Modifying a String
57
JAVA PROGRAMMING
The String objects are immutable. Therefore, it is not possible to change the original
contents of a string. However, the following String methods can be used to create a new
copy of the string with the required modification:
substring()
The substring() method creates a new string that is the substring of the string that
invokes the method. The method has two forms:
where, startindex specifies the index at which the substring will begin and endindex
specifies the index at which the substring will end. In the first form where the endindex is
not present, the substring begins at startindex and runs till the end of the invoking string.
Concat()
The concat() method creates a new string after concatenating the argument string
to the end of the invoking string. The signature of the method is given below:
replace()
The replace() method creates a new string after replacing all the occurrences of a
particular character in the string with another character. The string that invokes this
method remains unchanged. The general form of the method is given below:
trim()
The trim() method creates a new copy of the string after removing any leading and
trailing whitespace. The signature of the method is given below:
58
JAVA PROGRAMMING
The toUpperCase() method creates a new copy of a string after converting all the
lowercase letters in the invoking string to uppercase. The signature of the method is given
below:
toLowerCase()
The toLowerCase() method creates a new copy of a string after converting all the
uppercase letters in the invoking string to lowercase. The signature of the method is given
below:
Searching Strings
The String class defines two methods that facilitate in searching a particular
character or sequence of characters in a string. They are as follows:
IndexOf()
The indexOf() method searches for the first occurrence of a character or a substring
in the invoking string. If a match is found, then the method returns the index at which the
character or the substring first appears. Otherwise, it returns -1.
59
JAVA PROGRAMMING
lastIndexOf()
The lastIndexOf() method searches for the last occurrence of a character or a substring in
the invoking string. If a match is found, then the method returns the index at which the
character or the substring last appears. Otherwise, it returns –1.
60
JAVA PROGRAMMING
else
System.out.println ("str1 does not equal str3");
result = str1.compareTo (str3);
if(result == 0)
System.out.println ("str1 and str3 are equal");
else if(result < 0)
System.out.println ("str1 is less than str3");
else
System.out.println ("str1 is greater than str3");
str2 = "One Two Three One"; // assign a new string to str2
idx = str2.indexOf ("One");
System.out.println ("Index of first occurrence of One: " + idx);
idx = str2.lastIndexOf("One");
System.out.println ("Index of last occurrence of One: " + idx);
}
}
Output:
D:/kumar>javac StrOPs.java
D:/kumar>java StrOps
Length of str1:46
When it comes to web programming, Java is #1.
Str1 equals str2
Str1 does not equal str3
Str1 is greater than str3
Index of first occurrence of one:0
Index of last occurrence of one:14
D:/kumar>
StringBuffer:
StringBuffer:
StringBuffer objects are mutable, so they can be modified. The methods that
directly manipulate data of the object are available in StringBuffer class.
Creating StringBuffer:
We can create a StringBuffer object by using new operator and pass the string to the
object, as: StringBuffer sb = new StringBuffer ("Kiran");
61
JAVA PROGRAMMING
62
JAVA PROGRAMMING
64