Javanotes
Javanotes
What Is Java?
New object-oriented programming (OOP) language developed by
SUN Microsystems
Similar to C and C++, except without some of the confusing,
poorly understood features of C++
Extensive networking facilities
Extensive set of APIs for GUIs, distributed computing, 2D/3D
graphics, mail, and others
Portable: Write Once, Run Anywhere
Multithreading support built into the language
The JVM was first implemented inside Web browsers, but is now available on
a wide variety of platforms
Java Keywords:-
Keyword Meaning
if a conditional statement
protected a feature that is accessible only by methods of this class, its children, and other classes in
the same package
static a feature that is unique to its class, not to objects of its class
while a loop
History of Java
Around 1990 James Gosling , Bill Joy and others at Sun Microsystems began developing a language
called Oak. The wanted it primarily to control microprocessors embedded in consumer items such as
cable set-top boxes,VCR's, toasters, and also for personal data assistants (PDA).
Extremely reliable
Compact.
However, as of 1993, interactive TV and PDA markets had failed to take off. Then the Internet and Web
explosion began, so Sun shifted the target market to Internet applications and changed the name of the
project to Java.
By 1994 Sun's HotJava browser appeared. Written in Java in only a few months, it illustrated the power
of applets, programs that run within a browser, and also the capabilities of Java for speeding program
development.
Riding along with the explosion of interest and publicity in the Internet, Java quickly received widespread
recognition and expectations grew for it to become the dominant software for browser and consumer
applications.
However, the early versions of Java did not possess the breadth and depth of capabilities needed for client
(i.e. consumer) applications. For example, the graphics in Java 1.0 seemed crude and clumsy compared to
mature software developed with C and other languages.
Applets became popular and remain common but don't dominate interactive or multimedia displays on
web pages. Many other "plug-in" types of programs also run within the browser environment.
So Java has not succeeded at development of consumer applications. However, Java's capabilities grew
with the release of new and expanded versions (see below) and it became a very popular language for
development of enterprise, or middleware, applications such as on line web stores, transactions
processing, database interfaces, and so forth.
Java has also become quite common on small platforms such as cell phones and PDAs. Java is now used
in several hundred cell phone models. Over 600 million JavaCards, smart cards with additional features
provided by Java, have been sold as of the summer of 2004.
What is java
This section introduces you the Java programming language. These days Java programming
language is being used for programming web applications. It is also widely used for mobile
and electronic items.
1. What is Java?
Java is a high-level object-oriented programming language developed by the Sun
Microsystems. Though it is associated with the World Wide Web but it is older than the
origin of Web.
2. Java as an Internet Language</B< a>
Java is an object oriented language and a very simple language. Because it has no space
for complexities. At the initial stages of its development it was called as OAK. OAK was
designed for handling set up boxes and devices.
3. Java as general purpose language
Java is an Object oriented application programming language developed by Sun
Microsystems.
Java Features
4. Case sensitivity
What is case sensitivity: Case sensitivity is the mechanism in which words can be differ
in meaning based on different use of uppercase and lowercase letters.
5. Java is Simple and platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of
the important key feature of java language that makes java as the most powerful
language.
6. Java Enabled browsers
Java language is the most powerful language and is widely used in the web application.
Today most of the web browser are java compatible.
Java Tools
7. Java Compiler
To commence with Java programming, we must know the significance of Java Compiler.
8. Java Interpreter
We can run Java on most platforms provided a platform must has a Java interpreter.
9. Java Debugger
Java debugger helps in finding and the fixing of bugs in Java language programs.
10. Java Header File Generator
In Java programming we need to implement some native methods. To implement these
methods Javah generates C header and source files that are used by C programs to
reference an Object's instance variables from native source code.
11. JavaDoc
This tool is used to generate API documentation into HTML format from Java source
code.
12. Applet Viewer
Applet viewer is a command line program to run Java applets.
Features of JAVA
Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the
important key feature of java language that makes java as the most powerful language. Not
even a single language is idle to this feature but java is more closer to this feature. The
programs written on one platform can run on any platform provided the platform must have
the JVM.
Simple
There are various features that makes the java as a simple language. Programs are easy to
write and debug because java does not use the pointers explicitly. It is much harder to write
the java programs that can crash the system but we can not say about the other programming
languages. Java provides the bug free system due to the strong memory management. It also
has the automatic memory allocation and deallocation system.
Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.
● Inheritance : It is the process of creating the new classes and using the behavior
of the existing classes by extending them just to reuse the existing code and adding the.
● additional features as needed
● Encapsulation: : It is the mechanism of combining the information and providing
the abstraction.
● Polymorphism: : As the name suggest one name multiple form, Polymorphism is
the way of providing the different functionality by the
functions having the same name based on the signatures of the
methods.
● Dynamic binding : Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the maximum
functionality to a program about the specific type at runtime.
As the languages like Objective C, C++ fulfills the above four characteristics yet they are not
fully object oriented languages because they are structured as well as object oriented
languages. But in case of java, it is a fully Object Oriented language because object is at the
outer most level of data structure in java. No stand alone methods, constants, and variables are
there in java. Everything in java is object even the primitive data types can also be converted
into object by using the wrapper class.
Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It
provides the powerful exception handling and type checking mechanism as compare to other
programming languages. Compiler checks the program whether there any error and interpreter
checks any run time error and makes the system secure from crash. All of the above features
makes the java language robust.
Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers
can call functions on these protocols and can get access the files from any remote machine on
the internet rather than writing codes on their local system.
Portable
The feature Write-once-run-anywhere makes the java language portable provided that the
system must have interpreter for the JVM. Java also have the standard data size irrespective of
operating system or the processor. These features makes the java as a portable language.
Dynamic
While executing the java program the user can get the required files dynamically from a local
drive or from a computer thousands of miles away from the user just by connecting with the
Internet.
Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area
known as the sand box. Security manager determines the accessibility options of a class like
reading and writing a file to the local disk. Java uses the public key encryption system to allow
the java applications to transmit over the internet in the secure encrypted form. The bytecode
Verifier checks the classes after loading.
Performance
Java uses native code usage, and lightweight process called threads. In the beginning
interpretation of bytecode resulted the performance slow but the advance version of JVM uses
the adaptive and just in time compilation technique that improves the performance.
Multithreaded
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will
be more delighted to know another feature of Java which is Multithreaded.
Java is also a Multithreaded programming language. Multithreading means a single program
having different threads executing independently at the same time. Multiple threads execute
instructions according to the program code in a process or a program. Multithreading works
the similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs
not even a single thread disturbs the execution of other thread. Threads are obtained from the
pool of available ready to run threads and they run on the system CPUs. This is how
Multithreading works in Java which you will soon come to know in details in later chapters.
Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as
Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations.
Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages.
The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to
this any error occurring in the program gets traced. This is how it is different to work with
Java.
Architecture Neutral
The term architectural neutral seems to be weird, but yes Java is an architectural neutral
language as well. The growing popularity of networks makes developers think distributed. In
the world of network it is essential that the applications must be able to migrate easily to
different computer systems. Not only to computer systems but to a wide variety of hardware
architecture and Operating system architectures as well. The Java compiler does this by
generating byte code instructions, to be easily interpreted on any machine and to be easily
translated into native machine code on the fly. The compiler generates an architecture-neutral
object file format to enable a Java application to execute anywhere on the network and then
the compiled code is executed on many processors, given the presence of the Java runtime
system. Hence Java was designed to support applications on network. This feature of Java has
thrived the programming language.
Java Compiler
To commence with Java programming, we must know the significance of Java Compiler.
When we write any program in a text editor like Notepad, we use Java compiler to compile it.
A Java Compiler javac is a computer program or set of programs which translates java source
code into java byte code.
The output from a Java compiler comes in the form of Java class files (with .class extension).
The java source code contained in files end with the .java extension. The file name must be
the same as the class name, as classname.java. When the javac compiles the source file
defined in a .java files, it generates bytecode for the java source file and saves in a class file
with a .class extension.
The most commonly used Java compiler is javac, included in JDK from Sun Microsystems.
Following figure shows the working of the Java compiler:
Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It
interprets byte code (.class file) and converts into machine specific binary code. Then JVM
runs the binary code on the host machine.
How to use Java Compiler
When you run javac command on the command prompt, it shows the following output.
C:\>javac
Usage: javac <options> <source files>
where possible options include:
-g Generate all debugging info
used
-processor <class1>[,<class2>,<class3>...]
Names of the annotation processors to run;
bypasses default discovery process
Syntax error, if there is any. Like in this example, we haven't initialized 'a' and we are using it
in the next statement as 'int c=a+b'. That is why its showing a syntax error.
class A{
public static void
main(String[] args){
int a;
int b=2;
int c=a+b;
System.out.println(c);
}
}
Output of program:
C:\Program Files\Java\
jdk1.6.0_01\bin>javac A.java
A.java:6: variable a might not
have been initialized
int c=a+b;
^
1 error
C:\Program Files\Java\
jdk1.6.0_01\bin>
Now, lets tweak this example. In this we have initialized 'a' as 'int a =2'. Hence, no syntax
error has been detected.
class A{
public static void
main(String[] args) {
int a=2;
int b=2;
int c=a+b;
System.out.println(c);
}
}
Output of program:
C:\Program Files\Java\
jdk1.6.0_01\bin>javac A.java
C:\Program Files\Java\
jdk1.6.0_01\bin>java A
4
Java Interpreter
We can run Java on most platforms provided a platform must has a Java interpreter. That is
why Java applications are platform independent. Java interpreter translates the Java bytecode
into the code that can be understood by the Operating System. Basically, A Java
interpreter is a software that implements the Java virtual machine and runs Java applications.
As the Java compiler compiles the source code into the Java bytecode, the same way the Java
interpreter translates the Java bytecode into the code that can be understood by the Operating
System.
When a Java interpreter is installed on any platform that means it is JVM (Java virtual
machine) enabled platform. It (Java Interpreter) performs all of the activities of the Java run-
time system. It loads Java class files and interprets the compiled byte-code. You would be glad
to know that some web browsers like Netscape and the Internet Explorer are Java enabled.
This means that these browsers contain Java interpreter. With the help of this Java interpreter
we download the Applets from the Internet or an intranet to run within a web browser. The
interpreter also serves as a specialized compiler in an implementation that supports dynamic or
"just in time," compilation which turns Java byte-code into native machine instructions.
Throughout Java programming, we'll build both, the standalone Java programs and
applets.
Sun's Java interpreter is called java. Lets learn how to start a standalone application with it.
Load an initial class and specify it. Some options can also be specified to the interpreter, and
any command-line arguments needed for the application as well:
% java [interpreter options] class name [program arguments]
The class should be specified as a fully qualified class name including the class package, if
any.
Note : Moreover, we don't include the .class file extension. Here are a few examples:
% java animals.birds.BigBird
% java test
Once the class is loaded, java follows a C-like convention and searches for the class that
contains a method called main(). If it finds an appropriate main() method, the interpreter
starts the application by executing that method. From there, the application starts additional
threads, reference other classes, and create its user interface.
Now, lets see how to go about an Applet. Although Java applet is a compiled Java code, the
Java interpreter can't directly run them because they are used as part of a larger applications.
For this we use Java Applet Viewer. It is a command line program to run Java applets. It is
included in the SDK. It helps you to test an applet before you run it in a browser.
Java programming language is a language in which all the variables must be declared first and then to be
used. That means to specify the name and the type of the variable. This specifies that Java is a strongly-
typed programming language. Like
int pedal = 1;
This shows that there exists a field named 'pedal' that holds a data as a numerical value '1'. The values
contained by the variables determines its data type and to perform the operations on it.
There are seven more primitive data types which are supported by Java language programming in
addition to int. A primitive data type is a data type which is predefined in Java. Following are the eight
primitive data types:
int
It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647.
This data type is used for integer values. However for wider range of values use long.
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127 (inclusive). We
can save memory in large arrays using byte. We can also use byte instead of int to increase the limit of
the code.
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. short is
used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range of values.
float
The float data type is a single-precision 32-bits of storage . It ranges from 1.4e-45 to 3.4e+38 (positive or
negative). Use a float (instead of double) to save memory in large arrays. We do not use this data type for
the exact values such as currency.
Double
This data type is a double-precision 64-bits of storage . It ranges from 4.9e-324 to 1.8e +308 (positive or
negative). This data type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use this data type for
conditional statements. true and false are not the same as True and False. They are defined constants of
the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535. They are not
same as ints, shorts etc.
The following table shows the default values for the data types: Keyword Description Size/Format
When we declare a field it is not always essential that we initialize it too. The compiler sets a default
value to the fields which are not initialized which might be zero or null. However this is not
recommended.
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
byte byteident = 3;
short shortident=100;
System.out.println(byteident + " is the value of identifier named 'byteident' which primitive data type is
byte.");
System.out.println(shortident + " is the value of identifier named 'shortident' which primitive data type
is short.");
System.out.println(intident + " is the value of identifire named 'intident' which primitive data type is
int.");
System.out.println(longident + " is the value of identifier named 'longident' which primitive data type is
long.");
System.out.println(charident + " is the value of identifire named 'charident' which primitive data type is
char.");
System.out.println(stringident + " is the value of identifire named 'stringident' which primitive data
type is string.");
System.out.println(floatident + " is the value of identifier named 'floatident' which primitive data type
is float.");
System.out.println(doubleident + " is the value of identifier named 'doubleident' which primitive data
type is double.");
Class Declaration:
Class is the building block in Java, each and every methods & variable exists within the class
or object. (instance of program is called object ). The public word specifies the accessibility of
the class. The visibility of the class or function can be public, private, etc. The following code
declares a new class "HelloWorld" with the public accessibility:
public class HelloWorld {
The main Method:
The main method is the entry point in the Java program and java program can't run without
main method. JVM calls the main method of the class. This method is always first thing that is
executed in a java program. Here is the main method:
public static void main(String[] args) {
......
.....
}
{ and is used to start the beginning of main block and } ends the main block. Every thing in
the main block is executed by the JVM.
The code:
System.out.println("Hello, World");
prints the "Hello World" on the console. The above line calls the println method of System.out
class.
The keyword static:
The keyword static indicates that the method is a class method, which can be called without
the requirement to instantiate an object of the class. This is used by the Java interpreter to
launch the program by invoking the main method of the class identified in the command to
start the program.
This example illustrates that what is type casting? Type Casting refers to changing an entity of
one datatype into another. This is important for the type conversion in developing any
application. If you will store a int value into a byte variable directly, this will be illegal operation.
For storing your calculated int value in a byte variable you will have to change the type of
resultant data which has to be stored. This type of operation has illustrated below :
In this example we will see that how to convert the data type by using type casting. In the
given line of the code c = (char)(t?1:0); illustrates that if t which is boolean type
variable is true then value of c which is the char type variable will be 1
but 1 is a numeric value. So, 1 is changed into character according to the
Unicode value. But in this line c = (char)(t?'1':'0'); 1 is already given as a
character which will be stored as it is in the char type variable c.
code of the program :
public class conversion{
public static void main(String[] args){
boolean t = true;
byte b = 2;
short s = 100;
char c = 'C';
int i = 200;
long l = 24000;
float f = 3.14f;
double d = 0.000000000000053;
String g = "string";
System.out.println("Value of all the variables like");
System.out.println("t = " + t );
System.out.println("b = " + b );
System.out.println("s = " + s );
System.out.println("c = " + c );
System.out.println("i = " + i );
System.out.println("l = " + l );
System.out.println("f = " + f );
System.out.println("d = " + d );
System.out.println("g = " + g );
System.out.println();
//Convert from boolean to byte.
b = (byte)(t?1:0);
System.out.println("Value of b after conversion : " + b);
//Convert from boolean to short.
s = (short)(t?1:0);
System.out.println("Value of s after conversion : " + s);
//Convert from boolean to int.
i = (int)(t?1:0);
System.out.println("Value of i after conversion : " + i);
//Convert from boolean to char.
c = (char)(t?'1':'0');
System.out.println("Value of c after conversion : " + c);
c = (char)(t?1:0);
System.out.println("Value of c after conversion in unicode : " + c
);
//Convert from boolean to long.
l = (long)(t?1:0);
System.out.println("Value of l after conversion : " + l);
//Convert from boolean to float.
f = (float)(t?1:0);
System.out.println("Value of f after conversion : " + f);
//Convert from boolean to double.
d = (double)(t?1:0);
System.out.println("Value of d after conversion : " + d);
//Convert from boolean to String.
g = String.valueOf(t);
System.out.println("Value of g after conversion : " + g);
g = (String)(t?"1":"0");
System.out.println("Value of g after conversion : " + g);
int sum = (int)(b + i + l + d + f);
System.out.println("Value of sum after conversion : " + sum);
}
}
Operators
The operator is unary if it acts on a single operand; binary if it requres two operands. The
conditional operator is the only ternary operator in Java.
Each operator places specific requirements on the operand types allowed. For example, the
subtractive operator "- " in x=a-b; requires that a and b variables be numeric types. The
assignment operator "=" then requires that x also be a numeric type. (If a and b were wider
types than x, a casting operation would also be required.)
Returned Value
A value is "returned" at the completion of an operation. The following statements use the
assignment operator "=" and the addition operator "+"
int x = 3;
int y = x+5;
and result in x holding the value 3 and y holding the value 8. The entire expression y= x+5
could be used in another expression:
int x=3;
int y;
int z = (y=x+5) * 4;
which results in y holding 8 and z holding 32. The assignment operator "=" in the expression "y=x+5"
produces a new value for y and also returns the value of y to be used in the expression for z.
Effects on Operands
In most of the operations, the operands themselves are not changed. However, for some
operators, the operand(s) do undergo a change:
● Assignment operators: "x=y" replaces the value of the first operand with that of the second.
The other assignment operators, " *=, +=, etc" will also replace the value of the first operand
but only after using its initial value in the particular operation indicated by the symbol before
the = sign.
If an operand is changed by the operation, note that if the statement holding that expression is
processed again, e.g. in a loop, the resulting value can be different for each pass.
Expression Evaluation
The operands of an operator are always evaluated left to right. For example, in
x = a + b;
the first "+" operator will determine the value of a and then b.
Do not get this rule confused with the precedence and associativity rules.
● Precedence determines the order in which operators act in an expression of more than one
operator. The table below gives the rating for each operator, the higher number indicating
higher precedence.
● Associativity rules determine the grouping of operands and operators in an expression with
more than one operator of the same precedence.
the first "+" operator still first determines its left operand ("a" in this case) and then its right
operand. But in this case the right operand consists of the expression "b*c". The
multiplication operator "*" has a higher precedence than the additive "+".
Precedence can be overridden with parentheses, e.g.
x = (a + b) * c;
Here, addition and subtraction have the same precedence rating and so a and b are added and
then from this sum c is subtracted. Again, parentheses can be used to overrule the default
associativity, e.g.
x = a + (b - c);
However, the assignment and unary operators, are associated right to left, e.g.
x += y -= -~4;
is equivalent to
x += (y -= (-(~4)));
or in long hand,
int a = ~4;
a = -a;
y = y - a;
x = x + y;
which first sets x to 5, then returns that value for the test of b. You should not overuse this
technique else it makes the code unreadable. Occasionally, though, it can be a neat approach.
Assignment Operators
x operation= y
is equivalent to
x = x operation y
x and y must be numeric or char types except for "=", which allows x and y also to be
object references. In this case, x must be of the same type of class or interface as y. If
mixed floating-point and integer types, the rules for mixed types in expressions apply.
Assignment operator.
x = y;
=
y is evaluated and x set to this value.
The value of x is then returned.
Arithmetic Operators
x and y are numeric or char types. If mixed floating-point and integer types, then floating-
point arithmetic used and a floating-point value returned. If mixed integer types, the
wider type is returned. If double and float mixed, double is returned.
x + y Addition
x - y Subtraction
x * y Multiplication
Division
If FP arithmetic and y = 0.0, then infinity returned if x is not zero,
x / y
NaN if x is zero.
ArthmeticException thrown if x & y are integer types and y is zero.
Unary minus
-x
Negation of x value
Increment & Decrement Operators
x and y are numeric (FP & integer) or char types.
Boolean Operators
x and y are boolean types. x and y can be expressions that result in a boolean value.
Result is a boolean true or false value.
If both x and y are true, result is true.
Conditional
x && y If either x or y are false, the result is false
AND
If x is false, y is not evaluated.
Comparison Operators
x and y are numeric or char types only except for "==" and "!="
operators, which can also compare references. If mixed types, then
the narrower type converted to wider type. Returned value is boolean
true or false.
x == y Is x equal to y ?
x != y Is x not equal to y ?
Bitwise Operators
x and y are integers. If mixed integer types, such as int and long, the result will be of the
wider type.
Note: Operations on byte and short types may give unexpected results since operands are
promoted to integers during intermediate operations. For example,
byte x = (byte)0xFF;
x >>>= 1;
will result in 0xFF in x rather than 0x7F. That is because the operation is carried out on a
signed integer rather than simply on 8 bits. Here the signed byte is promoted to the signed
integer 0xFFFFFFFF.
i >>>= 1;
This results in 0x7F in the variable i.
Shift Right - Shift x to the right by y bits. Low order bits lost.
x >>> y
Unsigned Zeros fill in left bits regardless of sign.
Class and Object Operators
Other Operators
Operator Precedence
The larger the number, the higher the precedence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Operator Associativity
The following operators have Right to Left associativity. All other operators (see
precedence table above) are evaluated left to right.
?:
=
*= new
/= (type cast)
%= ++x
+= --x
-= +x
<<= -x
>>=
~
>>>=
&= !
^=
|=
Literals
double x = 3.1;
int i = 43;
the compiler needs to translate the character strings "3.1" and "43" into numerical values of a
particular type. Such explicit values in a computer language are called "literals" (for the
obvious reason that they are literally equivalent to their stated value.)
(In the bytecode each literal in your class code gets put into a so-called constants pool.)
Floating Point Literals
The compiler will see the decimal point and decide that the string "3.1" is a valid floating
point string. It must next decide what type to assign it. In Java a floating point literal defaults
to the double type.
double x = 3.1;
causes an error. You must instead explicitly type the floating point literal,
float y = 3.1f;
Integer Literals
Integer literals default to the int type.
You can assign a long type to the int literal since this will result in a widening conversion,
which does not require an explicit cast.
long m = 3; // allowed
You might think, then, that the following narrowing conversions would result in an error
byte b = -2;
short i = 3;
but Java allows this if the literals are within the allowed ranges for byte and short types.
However, this only works with the direct literal assignment. An assignment to an int variable,
int i = 3;
short i = i; // error
i = -2;
byte b = i; // error
long m = 2147483648L;
Besides the decimal base, you can use hexadecimal and octal formats for the integer literals:
short i = 0x00AF; // hex for 175
byte b = 017; // octal for 15
where hex numbers begin with "0x" and octal with "0".
Note: Assigning a literal value larger than the range for a particular integer type will NOT
result in an overflow warning (and no underflow warning for large negative values.) Instead
the value will wrap around to the lowest value. For example,
int i = 130;
byte bb = (byte)i;
Special Literals
For boolean type data, only two types of data are available: true and false. So these literals
are defined already in the core language:
Boolean b = true;
Boolean b1 = false;
Similarly, for references to objects, the null literal can be used when no object is yet chosen
for the reference variable:
String str = null;
Operators
An expression produces a result and returns a value. Examples include:
● i = 2 : the assignment puts 2 into the i variable and returns the value 2
● x < y : logical "less than" comparison, returns a Boolean true or false value
Expressions involve at least one operator. A single operator can have 1, 2 or 3 operands.
Effects on Operands
In most of the operations, the operands themselves are not changed. However, for some
operators, the operand(s) do undergo a change:
Assignment operators
"x = y" replaces the value of the first operand with that of the second.
The other assignment operators, "*=, +=, -=, /=" also replace the value of the first operand
but only after using its initial value in the operation indicated by the symbol before the equals
sign.
For example,
x *= y
results in x replaced by x * y. Also, this is the value returned from the operation.
Increment and decrement operators:
(++x) x is incremented before its value is returned.
(--x) x is decremented before its value is returned.
(x++) the initial value of x is returned and then x is incremented.
(x--) the initial value of x is returned and then x is decremented.
For the increment and decrement operations, note that in a standalone expression such as
x++;
there is no effective difference between x++ and ++x. Both expressions increment the value
stored in the variable x. However, in expressions such as
y = x++;
and
z = ++i;
the order of the appearance of the increment operator is important. In the former case, y takes
on the value of x before the increment occurs. If x is initially 3, then y becomes 3 and x
becomes 4. In the latter case the increment occurs before the value is used. So an initial value
of 3 for i leads to i incrementing to 4 and then z taking on the new value, 4.
Remember that if an operand is changed by the operation and the statement holding that
expression is processed again, as in a loop, the operand's value will be different for each pass.
Returned Value
A value is returned from the expression. The following statements use the assignment operator
"=" and the addition operator "+"
int x = 3;
int y = x + 5;
These statements result in x holding the value 3 and y holding the value 8. The entire
expression y = x + 5 could be used in another expression:
int x = 3;
int y;
int z = (y = x + 5) * 4;
This results in y holding 8 and z holding 32. The assignment operator "=" in the expression
(y = x + 5)
produces a new value for y and also returns the value of y to be used in the expression for z.
Expression Evaluation
The operands of an operator are always evaluated left to right. For example, in
x = a + b;
the "+" operator will determine the value of expression a and then expression b. Do not get
this rule confused with the precedence and associativity rules, discussed next.
Precedence determines the order in which operators act in an expression with more than one
operator. The Operator Precedence Table gives the precedence rating for each operator, the
higher number indicating higher precedence.
Associativity rules determines how the compiler groups the operands and operators in an
expression with more than one operator of the same precedence. For example, in the
expression
x = a + b * c;
the evaluation begins with a and then the "+" operator determines its right operand. But in this
case the right operand consists of the expression "b * c". The multiplication operator "*" has a
higher precedence than the additive operator "+" so b multiplies c rather than sums with a.
Precedence can be overridden with parentheses, as in
x = (a + b) * c;
The parentheses force the addition of b to a, and then c multiplies this sum.
Although the precedence ratings, which are similar to those in C/C++, were chosen for the
most "natural" ordering of the operator evaluations, it never hurts to use the parentheses if you
are unsure of the precedence and to make the code more readable.
When the operations in an expression all have the same precedence rating, the associativity
rules determine the order of the operations. For most operators, the evaluation is done left to
right, as in
x = a - b + c;
Here, addition and subtraction have the same precedence rating and so a and b are subtracted
and then c added to the difference. Again, parentheses can be used to overrule the default
associativity, as in
x = a - (b + c);
The assignment and unary operators, on the other hand, are associated right to left. For
example, the statement
x += y -= -~4;
is equivalent to
x += (y -= (-(~4)));
Casting
Converting one type of data into another must follow the rules of casting. If a conversion results
in the loss of precision, as in an int value converted to a short, then the compiler will issue an
error message unless an explicit cast is made.
To convert type AA data into type BB data, put the type BB name in parentheses in front of the
type AA data:
AA a = aData;
BB b = (BB)a; // cast type AA to type BB
int i=0;
float f;
f=(float)i; // Cast int as float
int i=1;
long j=3L; // Literals are int types so require L suffix
j=i; // OK
However, you can not assign a value to a more narrow type without an explicit cast:
So a data type with lower precision (fewer bits) can be converted to a type of higher precision
without explicit casting. To convert a higher precision type to a lower precision, however, an
explicit cast is required or the compiler will flag an error.
Note that when you cast a value of a wider type down to a more narrow type, such as an int
value to a byte variable, the upper bytes will be truncated. That is, the lowest order byte in the
int value will be copied to the byte value.
Below is a table that indicates to which of the other primitive types you can cast a given
primitive data type. The symbol C indicates that an explicit cast is required since the precision is
decreasing. The symbol A indicates that the precision is increasing so an automatic cast occurs
without the need for an explicit cast. N indicates that the conversion is not allowed.
The * asterisk indicates that the least significant digits may be lost in the conversion even though
the target type allows for bigger numbers. For example, a large value in an int type value that
uses all 32 bits will lose some of the lower bits when converted to float since the exponent uses
8 bits of the 32 provided for float values.
If an expression holds a mix of types, the lower precision or narrower value operand is converted
to a higher precision or wider type. This result then must be cast if it goes to a lower precision
type:
float x,y=3;
int j,i=3;
x= i*y; // OK since i will be promoted to float
j= i*y; // Error since result is a float value
j= (int)(i*y) // OK
The process of converting a value to a wider or higher precision integer or floating point type is
called "numeric promotion". The Java VM specification states the following rules for promotion
in an expression of two operands, as in x+i:
The java programming language supports the following types of controlling statements such as:
1.The break statement
2.The continue statement
3.The return statement
Continue: The continue statement is used in many programming languages such as C, C++, java
etc. Sometimes we do not need to execute some statements under the loop then we use the
continue statement that stops the normal flow of the control and control returns to the loop
without executing the statements written after the continue statement. There is the difference
between break and continue statement that the break statement exit control from the loop but
continue statement keeps continuity in loop without executing the statement written after the
continue statement according to the conditions.
In this program we will see that how the continue statement is used to stop the execution after
that.
Here is the code of the program :
public class Continue{
public static void main(String[] args){
Thread t = new Thread();
int a = 0;
try{
for (int i=1;i<10;i++)
{
if (i == 5)
{
continue;
//control will never reach here (after the continue statement).
//a = i;
}
t.sleep(1000);
System.out.println("chandan");
System.out.println("Value of a : " + a);
}
}
catch(InterruptedException e){}
}
}
Output of the program :
If we write the code in the given program like this :
if (i == 5 )
{
continue;
a = i;
}
Then the program will generate a error on compile time like :
C:\chandan>javac
Continue.java
Continue.java:12:
unreachable statement
a = i;
^
1 error
If we write the code in the given program like this :
if (i == 5 )
{
continue;
}
Then the program prints the output like :
C:\chandan>javac
Continue.java
C:\chandan>java
Continue
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
Break in Java
Break: The break statement is used in many programming languages such as c, c++, java etc.
Some times we need to exit from a loop before the completion of the loop then we use break
statement and exit from the loop and loop is terminated. The break statement is used in while
loop, do - while loop, for loop and also used in the switch statement.
Code of the program :
public class Break{
public static void main(String[] args){
int i,j;
System.out.println("Prime numbers between 1 to 50 : ");
for (i = 1;i < 50;i++ ){
for (j = 2;j < i;j++ ){
if(i % j == 0)
{
break;
}
}
if(i == j)
{
System.out.print(" " + i);
}
}
}
}
Output of the program :
C:\chandan>javac Break.java
C:\chandan>java Break
The Prime number in between 1 -
50 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43
47
The data type of the returned value must match the type of the method's declared return value.
When a method is declared void, use the form of return that doesn't return a value.
return;
The if-then statement is the most basic of all the control flow statements. It tells
your program to execute a certain section of code only if a particular test evaluates to
true. For example, the Bicycle class could allow the brakes to decrease the
bicycle's speed only if the bicycle is already in motion. One possible implementation
of the applyBrakes method could be as follows:
void applyBrakes(){
if (isMoving){ // the "if" clause: bicycle must be moving
currentSpeed--; // the "then" clause: decrease current speed
}
}
If this test evaluates to false (meaning that the bicycle is not in motion), control
jumps to the end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then"
clause contains only one statement:
void applyBrakes(){
if (isMoving) currentSpeed--; // same as above, but without
braces
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can
make the code more brittle. If a second statement is later added to the "then" clause, a
common mistake would be forgetting to add the newly required braces. The compiler
cannot catch this sort of error; you'll just get the wrong results.
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test
score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
Grade = C
You may have noticed that the value of testscore can satisfy more than one
expression in the compound statement: 76 >= 70 and 76 >= 60. However, once
a condition is satisfied, the appropriate statements are executed (grade = 'C';) and
the remaining conditions are not evaluated.
The following program, SwitchDemo, declares an int named month whose value
represents a month out of the year. The program displays the name of the month,
class SwitchDemo {
public static void main(String[] args) {
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}
Of course, you could also implement the same thing with if-then-else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
Another point of interest is the break statement after each case. Each break
statement terminates the enclosing switch statement. Control flow continues with
the first statement following the switch block. The break statements are necessary
because without them, case statements fall through; that is, without an explicit
break, control will flow sequentially through subsequent case statements. The
following program, SwitchDemo2, illustrates why it might be useful to have case
statements fall through:
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
Number of Days = 29
Technically, the final break is not required because flow would fall out of the
switch statement anyway. However, we recommend using a break so that
modifying the code is easier and less error-prone. The default section handles all
values that aren't explicitly handled by one of the case sections.
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If
the expression evaluates to true, the while statement executes the statement(s) in
the while block. The while statement continues testing the expression and
executing its block until the expression evaluates to false. Using the while
statement to print the values from 1 through 10 can be accomplished as in the
following WhileDemo program:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be
expressed as follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its
expression at the bottom of the loop instead of the top. Therefore, the statements
within the do block are always executed at least once, as shown in the following
DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}
When using this version of the for statement, keep in mind that:
● The initialization expression initializes the loop; it's executed once, as the
loop begins.
● When the termination expression evaluates to false, the loop terminates.
● The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print
the numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The
scope of this variable extends from its declaration to the end of the block governed
by the for statement, so it can be used in the termination and increment expressions
as well. If the variable that controls a for statement is not needed outside of the loop,
it's best to declare the variable in the initialization expression. The names i, j, and k
are often used to control for loops; declaring them within the initialization
expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as
follows:
The for statement also has another form designed for iteration through Collections
and arrays This form is sometimes referred to as the enhanced for statement, and can
be used to make your loops more compact and easy to read. To demonstrate, consider
the following array, which holds the numbers 1 through 10:
The following program, EnhancedForDemo, uses the enhanced for to loop through
the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array.
The output from this program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form
whenever possible.
Variables
As you learned in the previous lesson, an object stores its state in fields.
int cadence = 0;
int speed = 0;
int gear = 1;
The What Is an Object? discussion introduced you to fields, but you probably have
still a few questions, such as: What are the rules and conventions for naming a field?
Besides int, what other data types are there? Do fields have to be initialized when
they are declared? Are fields assigned a default value if they are not explicitly
initialized? We'll explore the answers to such questions in this lesson, but before we
do, there are a few technical distinctions you must first become aware of. In the Java
programming language, the terms "field" and "variable" are both used; this is a
common source of confusion among new developers, since both often seem to refer
to the same thing.
because their values are unique to each instance of a class (to each object, in
other words); the currentSpeed of one bicycle is independent from the
currentSpeed of another.
● Class Variables (Static Fields) A class variable is any field declared with
the static modifier; this tells the compiler that there is exactly one copy of
this variable in existence, regardless of how many times the class has been
instantiated. A field defining the number of gears for a particular kind of
bicycle could be marked as static since conceptually the same number of
gears will apply to all instances. The code static int numGears = 6;
would create such a static field. Additionally, the keyword final could be
added to indicate that the number of gears will never change.
● Local Variables Similar to how an object stores its state in fields, a method
will often store its temporary state in local variables. The syntax for declaring
a local variable is similar to declaring a field (for example, int count =
0;). There is no special keyword designating a variable as local; that
determination comes entirely from the location in which the variable is
declared — which is between the opening and closing braces of a method. As
such, local variables are only visible to the methods in which they are
declared; they are not accessible from the rest of the class.
Having said that, the remainder of this tutorial uses the following general guidelines
when discussing fields and variables. If we are talking about "fields in general"
(excluding local variables and parameters), we may simply say "fields". If the
discussion applies to "all of the above", we may simply say "variables". If the context
calls for a distinction, we will use specific terms (static field, local variables, etc.) as
appropriate. You may also occasionally see the term "member" used as well. A type's
fields, methods, and nested types are collectively called its members.
Naming
Every programming language has its own set of rules and conventions for the kinds
of names that you're allowed to use, and the Java programming language is no
different. The rules and conventions for naming your variables can be summarized as
follows:
● If the name you choose consists of only one word, spell that word in all
lowercase letters. If it consists of more than one word, capitalize the first
letter of each subsequent word. The names gearRatio and currentGear
are prime examples of this convention. If your variable stores a constant
value, such as static final int NUM_GEARS = 6, the convention
changes slightly, capitalizing every letter and separating subsequent words
with the underscore character. By convention, the underscore character is
never used elsewhere.
Arrays
An array is a container object that holds a fixed number of values of a single type.
The length of an array is established when the array is created. After creation, its
length is fixed. You've seen an example of arrays already, in the main method of the
"Hello World!" application. This section discusses arrays in greater detail.
The following program, ArrayDemo, creates an array of integers, puts some values in
it, and prints each value to standard output.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers
The above program declares anArray with the following line of code:
Like declarations for variables of other types, an array declaration has two
components: the array's type and the array's name. An array's type is written as
type[], where type is the data type of the contained elements; the square brackets are
special symbols indicating that this variable holds an array. The size of the array is
not part of its type (which is why the brackets are empty). An array's name can be
anything you want, provided that it follows the rules and conventions as previously
discussed in the naming section. As with variables of other types, the declaration
does not actually create an array — it simply tells the compiler that this variable will
hold an array of the specified type.
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
You can also place the square brackets after the array's name:
However, convention discourages this form; the brackets identify the array type and
should appear with the type designation.
One way to create an array is with the new operator. The next statement in the
ArrayDemo program allocates an array with enough memory for ten integer
elements and assigns the array to the anArray variable.
If this statement were missing, the compiler would print an error like the following,
and compilation would fail:
The next few lines assign values to each element of the array:
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900,
1000};
Here the length of the array is determined by the number of values provided between
{ and }.
You can also declare an array of arrays (also known as a multidimensional array) by
using two or more sets of square brackets, such as String[][] names. Each
element, therefore, must be accessed by a corresponding number of index values.
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]); //Mr. Smith
System.out.println(names[0][2] + names[1][1]); //Ms. Jones
}
}
Mr. Smith
Ms. Jones
Finally, you can use the built-in length property to determine the size of any array.
The code
System.out.println(anArray.length);
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy
data from one array into another:
The two Object arguments specify the array to copy from and the array to copy to.
The three int arguments specify the starting position in the source array, the starting
position in the destination array, and the number of array elements to copy.
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
caffein