:..Basic Elements Of Java..:
Like any other programming language, the Java programming language is defined by grammar rules that specify how syntactically legal constructs can be formed using the language elements, and by a semantic definition that specifies the meaning of syntactically legal constructs.
:..Lexical Tokens..:
The low-level language elements are called lexical tokens (or just tokens for short) and are the building blocks for more complex constructs. Identifiers, numbers, operators, and special characters are all examples of tokens that can be used to build high-level constructs like expressions, statements, methods, and classes.
:..Identifiers..:
A name in a program is called an identifier. Identifiers can be used to denote classes, methods, variables, and labels.In Java an identifier is composed of a sequence of characters, where each character can be either a letter, a digit, a connecting punctuation (such as underscore _), or any currency symbol (such as $, ¢, ¥, or £). However, the first character in an identifier cannot be a digit. Since Java programs are written in the Unicode character set (see p. 23), the definitions of letter and digit are interpreted according to this character set.
Identifiers in Java are case sensitive, for example, price and Price are two different identifiers.
Examples of Legal Identifiers:
number, Number, sum_$, bingo, $$_100, mål, grüß
Examples of Illegal Identifiers:
48chevy, all@hands, grand-sum
The name 48chevy is not a legal identifier as it starts with a digit. The character @ is not a legal character in an identifier. It is also not a legal operator so that all@hands cannot not be interpreted as a legal expression with two operands. The character - is also not a legal character in an identifier. However, it is a legal operator so grand-sum could be interpreted as a legal expression with two operands.
:..Keywords..:
Keywords are reserved identifiers that are predefined in the language and cannot be used to denote other entities. All the keywords are in lowercase, and incorrect usage results in compilation errors.
Keywords currently defined in the language are listed in Table (a). In addition, three identifiers are reserved as predefined literals in the language: the null reference and the Boolean literals true and false (see Table (b)). Keywords currently reserved, but not in use, are listed in Table (a). All these reserved words cannot be used as identifiers. The index contains references to relevant sections where currently defined keywords are explained.
Table (a) Keywords In Java
Table (b) Reserved Literals in Java
Table (c) Reserved Keywords not Currently in Use
:..Literals..:
A literal denotes a constant value, that is, the value a literal represents remains unchanged in the program. Literals represent numerical (integer or floating-point), character, boolean or string values. In addition, there is the literal null that represents the null reference.
Table (d) Examples of Literals
:..Integer Literals..:
Integer data types are comprised of the following primitive data types: int, long, byte, and short .
The default data type of an integer literal is always int, but it can be specified as long by appending the suffix L (or l) to the integer value. Without the suffix, the long literals 2000L and 0l will be interpreted as int literals. There is no direct way to specify a short or a byte literal.
In addition to the decimal number system, integer literals can also be specified in octal (base 8) and hexadecimal (base 16) number systems. Octal and hexadecimal numbers are specified with 0 and 0x (or 0X) prefix respectively. Examples of decimal, octal and hexadecimal literals are shown in Table (e). Note that the leading 0 (zero) digit is not the uppercase letter O. The hexadecimal digits from a to f can also be specified with the corresponding uppercase forms (A to F). Negative integers (e.g. -90) can be specified by prefixing the minus sign (-) to the magnitude of the integer regardless of number system (e.g., -0132 or -0X5A). Number systems and number representation. Java does not support literals in binary notation.
Table (e) Examples of Decimal, Octal, and Hexadecimal Literals
:..Floating-point Literals..:
Floating-point data types come in two flavors: float or double.The default data type of a floating-point literal is double, but it can be explicitly designated by appending the suffix D (or d) to the value. A floating-point literal can also be specified to be a float by appending the suffix F (or f).
Floating-point literals can also be specified in scientific notation, where E (or e) stands for Exponent. For example, the double literal 194.9E-2 in scientific notation is interpreted as 194.9*10-2 (i.e., 1.949).
Examples of double Literals
0.0 0.0d 0D
0.49 .49 .49D
49.0 49. 49D
4.9E+1 4.9E+1D 4.9e1d 4900e-2 .49E2
Examples of float Literals
0.0F 0f
0.49F .49F
49.0F 49.F 49F
4.9E+1F 4900e-2f .49E2F
Note that the decimal point and the exponent are optional and that at least one digit must be specified.
Boolean Literals
The primitive data type boolean represents the truth-values true or false that are denoted by the reserved literals true or false, respectively.
:..Character Literals..:
A character literal is quoted in single-quotes ('). All character literals have the primitive data type char.
Characters in Java are represented by the 16-bit Unicode character set, which subsumes the 8-bit ISO-Latin-1 and the 7-bit ASCII characters. In Table (f), note that digits (0 to 9), upper-case letters (A to Z), and lower-case letters (a to z) have contiguous Unicode values. Any Unicode character can be specified as a four-digit hexadecimal number (i.e., 16 bits) with the prefix \u.
:..Escape Sequences..:
Certain escape sequences define special character values. These escape sequences can be single-quoted to define character literals. For example, the character literals '\t' and '\u0009' are equivalent. However, the character literals '\u000a' and '\u000d' should not be used to represent newline and carriage return in the source code. These values are interpreted as line-terminator characters by the compiler, and will cause compile time errors. One should use the escape sequences '\n' and '\r', respectively, for correct interpretation of these characters in the source code.
We can also use the escape sequence \ddd to specify a character literal by octal value, where each digit d can be any octal digit (0–7), as shown in Table (h). The number of digits must be three or fewer, and the octal value cannot exceed \377, that is, only the first 256 characters can be specified with this notation.
:..String Literals..:
A string literal is a sequence of characters, which must be quoted in quotation marks and which must occur on a single line. All string literal are objects of the class String.
Escape sequences as well as Unicode values can appear in string literals:
"Here comes a tab.\t And here comes another one\u0009! (1)"What's on the menu?" (2)"\"String literals are double-quoted.\"" (3)"Left!\nRight!" (4)
In (1), the tab character is specified using the escape sequence and the Unicode value respectively. In (2), the single apostrophe need not be escaped in strings, but it would be if specified as a character literal('\''). In (3), the double apostrophes in the string must be escaped. In (4), we use the escape sequence \n to insert a newline. Printing these strings would give the following result:
Here comes a tab. And here comes another one !What's on the menu?"String literals are double-quoted."Left!Right!
One should also use the string literals "\n" and "\r", respectively, for correct interpretation of the characters "\u000a" and "\u000d" in the source code.
:..White Spaces..:
A white space is a sequence of spaces, tabs, form feeds, and line terminator characters in a Java source file. Line terminators can be newline, carriage return, or carriage return-newline sequence.
A Java program is a free-format sequence of characters that is tokenized by the compiler, that is, broken into a stream of tokens for further analysis. Separators and operators help to distinguish tokens, but sometimes white space has to be inserted explicitly as separators. For example, the identifier classRoom will be interpreted as a single token, unless white space is inserted to distinguish the keyword class from the identifier Room.
White space aids not only in separating tokens, but also in formatting the program so that it is easy for humans to read. The compiler ignores the white spaces once the tokens are identified.
:..Comments..:
A program can be documented by inserting comments at relevant places. These comments are for documentation purposes and are ignored by the compiler.
Java provides three types of comments to document a program:
- A single-line comment: // ... to the end of the line
- A multiple-line comment: /* ... */
- A documentation (Javadoc) comment: /** ... */
Single-line Comment
All characters after the comment-start sequence // through to the end of the line constitute a single-line comment.
pre>// This comment ends at the end of this line.
int age; // From comment-start sequence to the end of the line is a comment.
Multiple-line Comment
A multiple-line comment, as the name suggests, can span several lines. Such a comment starts with /* and ends with */.
/* A commenton severallines.*/
The comment-start sequences (//, /*, /**) are not treated differently from other characters when occurring within comments, and are thus ignored. This means trying to nest multiple-line comments will result in compile time error:
/* Formula for alchemy.gold = wizard.makeGold(stone);/* But it only works on Sundays. */*/
The second occurrence of the comment-start sequence /* is ignored. The last occurrence of the sequence */ in the code is now unmatched, resulting in a syntax error.
Documentation Comment
A documentation comment is a special-purpose comment that when placed before class or class member declarations can be extracted and used by the javadoc tool to generate HTML documentation for the program. Documentation comments are usually placed in front of classes, interfaces, methods and field definitions. Groups of special tags can be used inside a documentation comment to provide more specific information. Such a comment starts with /** and ends with */:
/*** This class implements a gizmo.* @author K.A.M.* @version 2.0*/
For details on the javadoc tool, see the documentation for the tools in the Java 2 SDK.
Volatile Variable in java
Volatile variable is more useful in java. Now a days we using multithread in many
Java projects. During this we can use the volatile keyword.
Best scenario for using volatile variable:
In multiple thread concept may be single instance can be used by multiple thread .That time the volatile variable will be use for programmer...Because without volatile variable means if one thread will be changed by user it will affect by other threads also.
During this time we can mention master copy variable we mention as volatile variable..because of this other than master variable will be update value it actually update in cache memory not in main memory variable memory
Declaring a volatile variable
Class exvolatile
{
volatile int val;
.....
}
JaVa ThE pUrE oBjEcT OrIeNtEd LaNguAgE
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “Oak” but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype. Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation was the need for a platform-independent (that is, architectureneutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. As you can probably guess, many different types of CPUs are used as controllers. The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific target. Although it is possible to compile a C++ program for just about any type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that compilers are expensive and time-consuming to create. An easier— and more cost-efficient—solution was needed. In an attempt to find such a solution, Gosling and others began work on a portable, platform-independent language that could be used to produce code that would run on a variety of CPUs under differing environments. This effort ultimately led to the creation of Java.
About the time that the details of Java were being worked out, a second, and ultimately more important, factor was emerging that would play a crucial role in the future of Java. This second force was, of course, the World Wide Web. Had the Web not taken shape at about the same time that Java was being implemented, Java might have remained a useful but obscure language for programming consumer electronics. However, with the emergence of the World Wide Web, Java was propelled to the forefront of computer language design, because the Web, too, demanded portable programs.
Most programmers learn early in their careers that portable programs are as elusive as they are desirable. While the quest for a way to create efficient, portable (platform-independent) programs is nearly as old as the discipline of programming itself, it had taken a back seat to other, more pressing problems. Further, because much of the computer world had divided itself into the three competing camps of Intel, Macintosh, and UNIX, most programmers stayed within their fortified boundaries, and the urgent need for portable code was reduced. However, with the advent of the Internet and the Web, the old problem of portability returned with a vengeance. After all, the Internet consists of a diverse, distributed universe populated with many types of computers, operating systems, and CPUs. Even though many types of platforms are attached to the Internet, users would like them all to be able to run the same program. What was once an irritating but low-priority problem had become a high-profile necessity.
By 1993, it became obvious to members of the Java design team that the problems of portability frequently encountered when creating code for embedded controllers are also found when attempting to create code for the Internet. In fact, the same problemthat Java was initially designed to solve on a small scale could also be applied to the Internet on a large scale. This realization caused the focus of Java to switch from consumer electronics to Internet programming. So, while the desire for an architectureneutral programming language provided the initial spark, the Internet ultimately led to Java’s large-scale success.
As mentioned earlier, Java derives much of its character from C and C++. This is by intent. The Java designers knew that using the familiar syntax of C and echoing the object-oriented features of C++ would make their language appealing to the legions of experienced C/C++ programmers. In addition to the surface similarities, Java shares some of the other attributes that helped make C and C++ successful. First, Java was designed, tested, and refined by real, working programmers. It is a language grounded in the needs and experiences of the people who devised it. Thus, Java is also a programmer’s language. Second, Java is cohesive and logically consistent. Third, except for those constraints imposed by the Internet environment, Java gives you, the programmer, full control. If you program well, your programs reflect it. If you program poorly, your programs reflect that, too. Put differently, Java is not a language with training wheels. It is a language for professional programmers.
Because of the similarities between Java and C++, it is tempting to think of Java as simply the “Internet version of C++.” However, to do so would be a large mistake. Java has significant practical and philosophical differences. While it is true that Java was influenced by C++, it is not an enhanced version of C++. For example, Java is neither upwardly nor downwardly compatible with C++. Of course, the similarities with C++ are significant, and if you are a C++ programmer, then you will feel right at home with Java. One other point: Java was not designed to replace C++. Java was designed to solve a certain set of problems. C++ was designed to solve a different set of problems. Both will coexist for many years to come.
As mentioned at the start of this chapter, computer languages evolve for two reasons: to adapt to changes in environment and to implement advances in the art of programming. The environmental change that prompted Java was the need for platform-independent programs destined for distribution on the Internet. However, Java also embodies changes in the way that people approach the writing of programs. Specifically, Java enhances and refines the object-oriented paradigm used by C++. Thus, Java is not a language that exists in isolation. Rather, it is part of an ongoing process begun many years ago. This fact alone is enough to ensure Java a place in computer language history. Java is to Internet programming what C was to systems programming: a revolutionary force that changed the world.
Polymorphism, Encapsulation, and Inheritance
When properly applied, polymorphism, encapsulation, and inheritance combine to produce a programming environment that supports the development of far more robust and scaleable programs than does the process-oriented model. A well-designed hierarchy of classes is the basis for reusing the code in which you have invested time and effort developing and testing. Encapsulation allows you to migrate your implementations over time without breaking the code that depends on the public interface of your classes. Polymorphism allows you to create clean, sensible, readable, and resilient code. Of the two real-world examples, the automobile more completely illustrates the power of object-oriented design. Dogs are fun to think about from an inheritance standpoint, but cars are more like programs. All drivers rely on inheritance to drive different types (subclasses) of vehicles. Whether the vehicle is a school bus, a Mercedes sedan, a Porsche, or the family minivan, drivers can all more or less find and operate the steering wheel, the brakes, and the accelerator. After a bit of gear grinding, most people can even manage the difference between a stick shift and an automatic, because they fundamentally understand their common superclass, the transmission.
People interface with encapsulated features on cars all the time. The brake and gas pedals hide an incredible array of complexity with an interface so simple you can operate them with your feet! The implementation of the engine, the style of brakes, and the size of the tires have no effect on how you interface with the class definition of the pedals.
The final attribute, polymorphism, is clearly reflected in the ability of car manufacturers to offer a wide array of options on basically the same vehicle. For example, you can get an antilock braking system or traditional brakes, power or rack-and-pinion steering, 4-, 6-, or 8-cylinder engines. Either way, you will still press the break pedal to stop, turn the steering wheel to change direction, and press the accelerator when you want to move. The same interface can be used to control a number of different implementations. As you can see, it is through the application of encapsulation, inheritance, and polymorphism that the individual parts are transformed into the object known as a car. The same is also true of computer programs. By the application of object-oriented principles, the various parts of a complex program can be brought together to for a cohesive, robust, maintainable whole.
Java is a pure object-oriented programming language developed by the chief programmer of Sun Microsystems James Gosling and his team-mates for controlling consumer electronic devices. It shares many superficial similarities with C, C++, and Objective C (for instance for loops have the same syntax in all four languages); but it is not based on any of those languages, nor have efforts been made to make it compatible with them. Java has following important features:
1. Simple – Java is simple to learn. If you already have a bit knowledge of object oriented programming like C++ then it will be some easier to learn Java because Java inherits the
C/C++ syntax and many of the object-oriented features of C++.
2. Object-Oriented – Java is a pure object-oriented programming language. Java believes – everything is an object. It provides the features of abstraction, encapsulation, inheritance and
polymorphism. Any thing in Java is embedded into a class.
3. Compiled and Interpreted – Java source programs are translated into bytecode by java compiler and this bytecode is interpreted by the Java interpreter, thus Java is both compiled
and interpreted. When a Java source program is compiled, it lists all the errors occurred in a program, if any. And when this program is error free, it is interpreted by the interpreter
which executes it line by line. Only when the execution reaches with an error is the error reported. Of course it takes some extra time for debugging a program.
4. Portable – The bytecode, produced by a Java compiler, can be run on any platform that has Java interpreter. Thus java code is portable.
5. Robust – Java is a strictly typed language. It checks your code at compile time as well as run-time. Thus java programs are less error prone.
6. Multithreaded – Java supports multithreading programming environment, which allows you to write programs that do many things simultaneously. Even the core of Java is
multithreaded.
7. Secure – Java does not allow a programmer to manipulate the memory of a system.
8. Distributed – Java programs can access data across a network, therefore it is distributed.
9. Architecture Neutral and Portable – Java first converts a source program into bytecode which can be run on a variety of computers having different operating systems.
10. A High Performance Programming Language – Java programs are faster as compared to programs written in other interpreter-based programming languages.
11. Dynamic – Java provides an efficient way for maintaining different versions of an application.
/* IMPLEMENT SIMPLE JAVA PROGRAM */
class lohit
{
public static void main(String arr[])
{
System.out.println("Welcome To My Java World:Lohit");
}
}
OUTPUT :
/* IMPLEMENT PROGRAM OF JAVA USING CONSTRUCTOR */
class nesting
{
int m,n;
nesting(int x,int y)
{
n=x;
n=y;
}
int largest()
{
if(m>=n)
return(m);
else
return(n);
}
void display()
{
int large=largest();
System.out.println("largest value="+large);
} }
class nestingtest
{
public static void main(String args[])
{
nesting nest=new nesting(50,40);
nest.display();
}
}
OUTPUT:
/* IMPLEMENT PROGRAM OF JAVA USING INHERITANCE */
class room
{
int length,breadth;
room(int x,int y)
{
length=x;
breadth=y;
}
int area()
{
return(length*breadth);
} }
class broom extends room
{
int height;
broom(int x,int y,int z)
{
super(x,y);
height=z;
}
int volume()
{
return(length*breadth*height);
} }
class test
{
public static void main(String args[])
{
broom room1=new broom(15,10,20);
int area1=room1.area();
int volume1=room1.volume();
System.out.println("area1="+area1);
System.out.println("volume1="+volume1);
}
}
OUTPUT:
/* IMPLEMENT JAVA PROGRAM USING MULTITHREADING */
class A extends Thread
{
public void run()
{
for (int i=0; i<=2;i++)
{
System.out.println("\t From thread a"+i);
}}}
class B extends Thread
{
public void run(){
for (int j=0;j<=2;j++)
{
System.out.println("\t From thread b"+j);
}}}
class Thread1
{
public static void main(String args[])
{
new A().start();
new B().start();
}}
OUTPUT:
/* IMPLEMENT JAVA PROGRAM USING EXCEPTION HANDLING */
class Error4
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x=a[2]/b;
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(Exception e)
{
System.out.println("ArrayIndexOutofBound");
}
finally
{
System.out.println("Finally executed");
}}}
OUTPUT:
/* IMPLEMENT JAVA PROGRAM USING INTERFACES */
interface area
{
final static float pi=3.14f;
float compute(float x, float y);
}
class rectangle implements area
{
public float compute(float x, float y)
{
return(x*y);
}
}
class circle implements area
{
public float compute(float x, float y)
{
return(pi*x*x);
}
}
class interfacetest
{
public static void main(String args[])
{
rectangle rect=new rectangle();
circle cir=new circle();
area are;
are=rect;
System.out.println("Area of rect="+are.compute(10,20));
are=cir;
System.out.println("Area of cir="+are.compute(10,0));
}
}
OUTPUT:
/* IMPLEMENT JAVA PROGRAM USING APPLETS */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/**/
public class tools extends Applet implements ActionListener
{
String msg=" ";
Button b1,b2,b3;
TextField t1,t2,t3;
Label l1,l2,l3;
public void init()
{
b1=new Button("sum");
b2=new Button("multiply");
b3=new Button("divison");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
l1=new Label("enter ist no");
l2=new Label("enter 2nd no");
l3=new Label("result");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
t1.addActionListener(this);
t2.addActionListener(this);
t3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String msg =ae.getActionCommand();
int x,y,z;
x=Integer.parseInt(t1.getText());
y=Integer.parseInt(t2.getText());
if(msg.equals("sum"))
{
z=x+y;
}
else if (msg.equals("multiply"))
{
z=x*y;
}
else
{
z=x/y;
}
t3.setText(" "+z);
repaint();
}
public void paint (Graphics g)
{
g.drawString(msg,20,20);
}
}
OUTPUT: