Images

Core Java - PART I


Core Java
Core Java offers a total immersion approach for C\C++ programmer wanting to learn java.Core Java
The course will use JDK(Java Development Kit) and covers all the new language features.
This course inclues worked out examples illustrating new JDKfeatures that are fully explained thoughout the course.
Core Java has been carefully planned to help students create faster, smaller and more efficient Java application.


Java Evolution
Java History
• Java is a general purpose , object-oriented programming language.
• The fastest growing programming language in the history of computing
• Developed by Sun Microsystems of USA in 1991.
• Originally it is called Oak by James Gosling.
• Originally designed in 1991 for use in embedded consumer applications
• Java team which headed James Gosling developed a Web browser called “Hot Java” to
locate and run applet programs on Internet in 1994.
• Oak was renamed “Java” in 1995. 
• Redesigned in early 1995 with Internet application capabilities
• Introduced in May, 1995 and immediately supported by the Netscape Web browser.
• Rapidly overtaking C++ in popularity among commercial software developers
• Java established itself not only as a leader for Internet programming but also as a
general purpose, object-oriented programming language.
• Java found its home in the heart of the modern programmer.
• Java is the first programming language that is not tied to any particular hardware or
operating system.
• Programs developed in java can be executed anywhere on any system.
• Therefore Java comes as a revolutionary technology because it has brought in a
fundamental shift in how we develop and use programs.
ebiz

Java Evolution
Java Features 
• Simple • Architecture-neutral  
• Object-oriented  • Portable 
• Distributed • High-performance 
• Interpreted • Multithreaded 
• Robust • Dynamic 
• Secure 
Simple: 
       Java is a simple language as it does not use pointers, preprocessor header files; go to statement and many more others. 
Object oriented: 
       In Java everything is object. All program code and data within objects and classes. 
Distributed: 
       Java is designed as a distributed language for creating applications on networks. It has ability to share both data and programs. 
Interpreted: 
       Interpreting means actually compiling the program line by line and generates the machine code. Java interpreter generates machine code that can be directly executed by the machine is that running the Java program. 
Robust: 
       Java is a robust language as it provides many safeguards to ensure reliable code. It has strict compile time and run time checking for data types. 
Secure: 
       No viruses can affect the Java program as Java ensures that program cannot gain access to memory locations without proper authorization. Java systems not only verify all memory access but also ensure that no viruses are communicated with an applet. 
Architecture-neutral: 
       In Java, changes and upgrade in operating system, processors and system resources will not force any changes in Java programs. 
Portable: 
       Java programs can be easily moved from one computer system to another, anytime, and anywhere. Java ensures portability in two ways. First, Java compiler generates bytecode instructions that can be implemented on any machin. Secondly the sizes of the primitive data type are machin-independent. 
High-performance: 
       Java performance is impressive for an interpreted language , mainly due to the use of intermediate bytecode. 
Multithreaded: 
       Java support multithreaded programs means handling multiple task simultaneously. 
Dynamic: 
       Java is capable of dynamically linking in new class libraries, methods and objects. 
    

Java Evolution
Benefits of Java over C and C++ 
• Architecturally neutral. Once written, the same Java program can be run on any   
platform computer and operating system) that supports Java.
• Entirely object-oriented. Existing code can be easily re-used and maintained.
• Secure. Dangerous program actions are prohibited. 
• Supports Internet programming. Java applets are run by Web browsers.
• Robust. Language features and packaged code support graphical programming,   
exception handling, networking, multi-threading, I/O, and more.

Java Evolution
How Java works
• To develop and distribute a Java program  
1. Programmer codes Java source statements 
2. Java compiler converts source statements into bytecode (platform-independent object     language)  
3. Bytecode is copied to the target platform 
• To execute a Java program  
1. Platform-dependent Java Virtual Machine (JVM) software must be installed  
2. A copy of the JVM is started  
3. Each bytecode statement is interpreted (translated) by the JVM into platform-dependent     machine language and executed under JVM control.
Java has two things: a programming language and a platform.
    

Java Evolution
The Java Programming Language
Java is a high-level programming language that is all of the following:
• Simple• Architecture-neutral
• Object-oriented• Portable
• Distributed• High-performance
• Interpreted• Multithreaded
• Robust• Dynamic
• Secure
Java is also unusual in that each Java program is both compiled and interpreted.
With a compiler, it translates a Java program into an intermediate language called Java bytecodes--the platform-independent codes interpreted by the Java interpreter.

With an interpreter, each Java bytecode instruction is parsed and run on the computer. Compilation happens just once; interpretation occurs each time the program is executed. This figure show how it works.
The Java bytecodes is the machine code instructions for the Java Virtual Machine (Java VM). Every Java interpreter, whether it's a Java development tool or a Web browser that can run Java applets, is an implementation of the Java VM. The Java VM can also be implemented in hardware.

Java bytecodes help make "write once, run anywhere" possible.

One can compile your Java program into bytecodes on any platform that has a Java compiler. The bytecodes can then be run on any implementation of the Java VM.
    

Java Evolution
The Java Platform
A platform is the hardware or software environment in which a program runs. The Java
platform differs from most other platforms in that it's a software-only platform that runs on
top of other, hardware-based platforms. Most other platforms are described as a combination of hardware and operating system.
 The Java platform has two components:
• The Java Virtual Machine (Java VM)
• The Java Application Programming Interface (Java API)
The Java VM is the base for the Java platform and is ported onto various hardware-based platforms.
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. The Java API(application programming interface) is grouped into libraries (packages) of related components.

Java Evolution
Java Development Kit
The Java Development Kit comes with a collection of tools that are used for developing and running Java programs. They include:
• appletviewer ( for viewing Java applet)
• javac (Java compiler)
• java (Java Interpreter)
• javap (Java disassembler)
• javah (for C header files)
• javadoc (for creating HTML documents)
• jdb (Java debugger)
The below figure depicts a Java program, such as an application or applet, that's running on the Java platform. As the figure shows, the Java API and Virtual Machine insulates the Java program from hardware dependencies.
To View the Installation Process of JDK (Java Development Kit)(With Sound), Click Here!
    

Java Evolution
HARDWARE AND SOFTWARE REQUIREMENTS
Java is currently supported on Window 95, Window NT, Sun Solaries, Macintosh and UNIX machine.
The minimum software and hardware requirement for 95 version of Java are as follows:
     • IBM-compatible 486 system
     • Minimum of 8 MB memory
     • Windows 95 software
     • A Windows-compatible sound card
     • A hard drive;
     • A CD-ROM drive
     • A Microsoft-compatible mouse

Java Evolution
Disadvantages of Java
• Not supported by all platforms (though third-party JVM software is usually available)
• Slower in execution than compiled languages
• Restricts or prohibits machine-level operations required by certain applications    (operating systems, etc.)

Overview of Java Language
Developing the Java Application
A Java application is a standalone Java program-- a program written in the Java language that runs independently of any browser.
Example:
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}
Output
To view, how to write,compile and run the Java Program.(With Sound) Click Here!
    

Overview of Java Language
Comments in Java Code
The bold characters in the following listing are comments.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/

class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}
The Java language supports three kinds of comments:
/* text */
The compiler ignores everything from /* to */.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compilerignores this kind of comment, just like it ignores comments that use /* and */.
// text
The compiler ignores everything from // to the end of the line
    

Overview of Java Language
Defining a Class
The first bold line in the following listing begins a class definition block.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}
A class--the basic building block of an object-oriented language such as Java--is a template that describes the data and behavior associated with instances of that class.

The data associated with a class or object is stored in variables; the behavior associated with a class or object is implemented with methods. Methods are similar to the functions or procedures in procedural languages such as C.

In the Java language, the simplest form of a class definition is
class name {
. . .
}
The keyword class begins the class definition for a class named name.
The variables and methods of the class are embraced by the curly brackets that begin and end the class definition block. The "Hello World" application has no variables and has a single method named main.
    

Overview of Java Language
The main Method
The first bold line in the following listing begins the definition of a main method.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/

class HelloWorldApp {
public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}

Every Java application must contain a main method whose signature looks like this:

public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}


Every Java application must contain a main method whose signature looks like this:

public static void main(String[] args)

The method signature for the main method contains three modifiers:

• public indicates that the main method can be called by any object.
• static indicates that the main method is a class method.
• void indicates that the main method doesn't return any value.
How the main Method Gets Called
The main method in the Java language is similar to the main function in C and C++. When the Java interpreter executes an application (by being invoked upon the application's controlling class), it starts by calling the class's main method. The main method then calls all the other methods required to run your application. If you try to invoke the Java interpreter on a class that does not have a main method, the interpreter refuses to compile your program and displays an error message similar to this: In class NoMain: void main(String argv[]) is not defined
Arguments to the main Method
Here the main method accepts a single argument: an array of elements of type String.
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. Each String in the array is called a command-line argument.
    

Overview of Java Language
Using Classes and Objects
The "Hello World" application is about the simplest Java program one can write that actually does something. Because it is such a simple program, it doesn't need to define any classes except for HelloWorldApp.

The "Hello World" application does use another class--the System class--that is part of the API (application programming interface) provided with the Java environment. The System class provides system-independent access to system-dependent functionality.

The bold code in the following listing illustrates the use of a class variable of the System class, and of an instance method.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/

class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}
Using a Class Method or Variable
Let's take a look at the first segment of the statement:
System.out .println("Hello World!");  The construct System.out is the full name of the out variable in the System class.
Using an Instance Method or Variable
Methods and variables that are not class methods or class variables are known as instance methods and instance variables.

While System's out variable is a class variable, it refers to an instance of the PrintStream class (a class provided with the Java development environment) that implements the standard output stream.

When the System class is loaded into the application, it instantiates PrintStream and assigns the new PrintStream object to the out class variable.

System.out.println("Hello World!");


This line of code displays "Hello World!" to the application's standard output stream
    

Overview of Java Language
Java Program Structure
A Java program may contain one or more section which is as follow:
1. Documentation section (suggested)
The documentation section comprises a set of comment line of the program, the author
and other details, which the programmer would like to refer to at a later stage.
2. Package statement (Optional)
This statement declares a package name and inform the compiler that the class defined here belong to this package.
Ex: package student;
3. Import Statement (Optional)
This statement instructs the interpreter to load the specific class contained in the package.
Ex: import student. test;
4. Interface Statement (Optional)
An interface is like a class but include a group of method declarations.
5. Class Definitions (Optional)
Classes are the primary and essential elements of Java program. These classes are used
to map the object of real world problems.
6. Main Method Class (Essential)
As every Java stand-alone program requires a main method as its starting point, this class is the essential part of the program.
    

Overview of Java Language
Java Tokens
The smallest individual units in a program are known as TOKEN.
A java program is a collection of tokens, comments and white spaces.
Java language includes five types of tokens
They are:
1) Reserved Keyword
2) Identifiders
3) Literals
4) Operator
5) Separators
Reserved Keyword
Keywords have specific meaning and implement specific features of the language.
Java language has reserved 60 words as keywords.
Identifiers
Identifiers are programmer-designed tokens. They are used for naming class,
methods, variables, objects, labels, packages, and interface in a program.
Literals
Literal is a programming language term that essentially means that what you type is what you get. Numbers, characters, and strings are all examples of literals.
Therefore literals
1) Are constants having no identifier?
2) Have their value specified within the program's source code?
3) Can only appear on the right side of an assignment operator (=) or within an      expression?
4) Have a data type associated with them?
Java program has five major types of literals:
1) Integer Literals
2) Floating type literals
3) Character literals
4) String literals
5) Boolean Literals
Integer literals
1. Represent an integer value
2. Can be expressed in decimal (the default), octal (base 8, or hexadecimal (base 16)
3. Are not enclosed in any special characters
4. Are automatically int (32 bits) unless the suffix 'L' is appended to make it long (64 bits)
Floating-point literals
1. Represent a real number (having a decimal point)
2. Can be expressed as a standard decimal value or in scientific notation
3. Are not enclosed in any special characters
4. Are automatically double (64 bits) unless the suffix 'F' is appended to make it float (32     bits)
char literals
1. Represent a single Unicode character (16 bits)
2. Must be enclosed within single quotes (apostrophes)
3. Are often associated with a single key stroke
4. Can represent special characters ("escape sequences") used for device control
String literals
1. Represent a string of characters, such as "Java is fun"
2. Must be enclosed in double quotes
3. Are automatically stored as String class objects by the compiler. They will be covered     later.
boolean literals
1. Can only have the value true or false
2. Can only be assigned to boolean variables
Constants
1. Are similar to variables but, once initialized, their contents may NOT be changed?
2. Are declared with the keyword final?
3. By convention, have all capital letters in their identifier. This makes them easier to see within the code.
Operators
An operator is a symbols that takes one or more arguments and operates on them to produce a result.
Separators
Separators are symbols used to indicate where groups of code are divided and arranged. They are basically define the shape and function of our code.
Ex: {}, [], ; , . , () etc.
    

Constaant, Variable and Datatype
Variables
Variables are locations in memory in which values can be stored. Each one has a name, a type, and a value.

Before we can use a variable, we have to declare it. After it is declared, we can then assign values to it.
Java actually has three kinds of variables:
1. instance variables,
2. class variables,
3. And local variables.
Instance variables, are used to define the attributes of a particular object.
Class variables are similar to instance variables, except their values apply to all that class's instances (and to the class itself) rather than having different values for each object.

Local variables are declared and used inside method definitions,

Although all three kinds of variables are declared in much the same ways, class and instance variables are accessed and assigned in slightly different ways from local variables.

Java does not have global variables-that is, variables that are global to all parts of a program. Instance and class variables can be used to communicate global information between and among objects.
    

Constaant, Variable and Datatype
Declaring Variables
To use any variable in a Java program, we must first declare it. Variable declarations consist of a type and a variable name:
int myAge;
String myName;
boolean isTired;
Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java statement can go), although they are most commonly declared at the beginning of the definition before they are used:
public static void main (String args[]) {
int count;
String title;
boolean isAsleep;
...
}
We can string together variable names with the same type on one line:
int x, y, z;
String firstName, LastName;
We can also give each variable an initial value when we declare it:
int myAge, mySize, numShoes = 28;
String myName = "eBIZ";
boolean isTired = true;
int a = 4, b = 5, c = 6;
If there are multiple variables on the same line with only one initializer the initial
value applies to only the last variable in a declaration.

We can also group individual variables and initializers on the same line using
commas, as with the last example.
    

Constaant, Variable and Datatype
Rules on Variable Names
Variable names in Java can start with a letter, an underscore (_), or a dollar sign ($). They cannot start with a number. After the first character, our variable names can include any letter or number. Symbols, such as %, *, @, and so on, are often reserved for operators in Java, so we should be careful when using symbols in variable names. The Java language uses the Unicode character set. The Java language is case sensitive, which means that uppercase letters are different from lowercase letters. This means that the variable X is different from the variable x, and a rose is not a Rose is not a ROSE.

Constaant, Variable and Datatype
Variable Types
In addition to the variable name, each variable declaration must have a type, which defines what values that variable can hold.
The variable type can be one of three things:
• One of the eight primitive data types
• The name of a class or interface
• An array

Constaant, Variable and Datatype
Primitive Data Types
The eight primitive data types handle common types for integers, floating-point numbers, characters, and boolean values (true or false).
They're called primitive because they're built into the system and are not actual objects, which makes them more efficient to use.
Integer Type
There are four Java integer types, each with a different range of values.
All are signed, which means they can hold either positive or negative numbers.
Table 3.1. Integer types
TypeSizeRange
byte8 bits-128 to 127
short16 bits-32,768 to 32,767
int32 bits-2,147,483,648 to 2,147,483,647
long64 bits-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Floating-point type:
Floating-point numbers are used for numbers with a decimal part.
There are two floating-point types: float (32 bits, single precision) and double (64 bits, double precision).
Char type:
The char type is used for individual characters. Because Java uses the Unicode character set, the char type has 16 bits of precision, unsigned.
    

Constaant, Variable and Datatype
Constants
• Are similar to variables but, once initialized, their contents may NOT be changed?
• Are declared with the keyword final?
• By convention, have all capital letters in their identifier. This makes them easier to see   within the code.
Example 1:
This program defines a number of constants and then displays some of their values.
public class App
{
public static void main(String[] args)
{

final boolean YES = true;
final char DEPOSIT_CODE = 'D';
final byte INCHES_PER_FOOT = 12;
final int FEET_PER_MILE = 5280;
final float PI = 3.14F;
final double SALES_TAX_RATE = .06;
final String ADDRESS = "119 South Street";

// Display some of the values

System.out.println(INCHES_PER_FOOT);
System.out.println(ADDRESS);
}
}
Output
Example 2:
This program will not compile because an attempt is made to change the value of its constant.
public class App1
{
public static void main(String[] args)
{

final double SALES_TAX_RATE = .06;
SALES_TAX_RATE = .04;

// Display the sales tax rate

System.out.println(SALES_TAX_RATE);
}
}
Here the compiler error will occur like this
Output
    

0 comments: