Java Notes

37
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 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

Transcript of Java Notes

Page 1: Java Notes

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 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.

Page 2: Java Notes

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 make 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

Page 3: Java Notes

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.

COMPARISION OF C++ AND JAVA

1. Java has generics,  to provide type-safe containers. C++ has templates and they provide

more extensive support for generic programming.

2. C++ enumerations are primitive types. Java enumerations are actually instances of a class

and they extend java.lang.Enum<E.

Page 4: Java Notes

3. Java offers automatic garbage collection for memory allocation and deallocations. Memory

management in C++ is usually done through CLR - constructors, destructors, and smart

pointers.

4. All C++ compilers implement a phase of compilation known as the preprocessor and most

of the preprocessor definitions in C++ are stored in header files, which complement the actual

source code files. Whereas Java does not have a preprocessor. Java programs don't use

header files; the Java compiler builds class definitions directly from the source code files.

5. C++ use pointers to create and maintain dynamic data structures. It's powerful, but complex

and sometimes cause bugs because of having unguarded memory access. The Java language

does not support pointers but provides similar functionality through references and references

don't allow direct memory address manipulation, thus making it more safe.

6. C++ is not bounds checked. Java is bounds check.

7. C++ is non portable as it is restricted to run on the same platform it was compiled, Java

generally compiles to Java bytecode, which then runs on a  virtual machine (the JVM), and

bytecode is portable across different operating systems and processors.

8. C++ supports multiple inheritance. Whereas Java does not directly support multiple

inheritance, but you can achieve multiple inheritance functionality by implementing interfaces in

Java.

9. C++ supports Operator overloading . It is not supported in Java, but + and += operators are

the exceptions, for string concatenation functionality.

10. C++ supports goto statement whereas java doesn't.

11. C++ and java also differs in passing the command-line arguments from the system into a

program :

In C++, the system passes two arguments to a program:

argc and

argv.

argc specifies the number of arguments stored in argv. argv is a pointer to an array of characters

containing the actual arguments. Whereas in Java, the system passes a single value to a program:

args. ‘args’ is an array of Strings that contains the command-line arguments.

STRUCTURE OF JAVA PROGRAM

A Java program is a collection of classes. Each class is normally written in a separate file and the name of the file is the name of the class contained in the file, with the extension .java. Thus, the class stack defined earlier would be stored in a file called stack.java.

Page 5: Java Notes

As we noted in Chapter 1, we have to fix where the program starts to execute. Java requires that at least one of the classes has a public static method called main. More precisely we need a method with the following signature:

public static void main(String[] args)

We have already seen what public and static mean. The word void has the same connotation as in C -- this function does not return a value. The argument to main is an array of strings (we'll look at strings and arrays in Java in more detail later)--this corresponds to the argv argument to the main function in a C program. We don't need argc because in Java, unlike in C, it is possible to extract the length of an array passed to a function. Also, unlike C, the argument to main is compulsory. Of course, the name of the argument is not important: in place of args we could have used xyz or any other valid identifier.

Here then, is a Java equivalent of the canonical Hello world program.

class helloworld{ public static void main(String[] args){ System.out.println("Hello world!"); } }

Here println is a static method in the class System.out which takes a string as argument and prints it out with a trailing newline character.

As noted earlier, we have to save this class in a file with the same name and the extension .java; that is, helloworld.java.

JAVA TOKENS

In a Java program, all characters are grouped into symbols called tokens. Larger language features are built from the first five categories of tokens (the sixth kind of token is recognized, but is then discarded by the Java compiler from further processing). We must learn how to identify all six kind of tokens that can appear in Java programs. In EBNF we write one simple rule that captures this structure:

token <= identifier | keyword | separator | operator | literal | comment

The different types of Tokens are:

1. Identifiers: names the programmer chooses 2. Keywords: names already in the programming language

3. Separators (also known as punctuators): punctuation characters and paired-delimiters

4. Operators: symbols that operate on arguments and produce results

5. Literals (specified by their type)

Page 6: Java Notes

o Numeric: int and double

o Logical: boolean

o Textual: char and String

o Reference: null

6. Comments

o Line

JAVA CHARACTER SET

The full Java character set includes all the Unicode characters; there are 216 = 65,536 unicode characters. Since this character set is very large and its structure very complex, in this class we will use only the subset of unicode that includes all the ASCII (pronounced "Ask E") characters; there are 28 = 256 ASCII characters, of which we will still use a small subset containing alphabetic, numeric, and some special characters.

We can describe the structure of this character set quite simply in EBNF, using only alternatives in the right hand sides.

lower-case <= a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|zupper-case <= A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Zalphabetic <= lower-case | upper-casenumeric     <= 0|1|2|3|4|5|6|7|8|9alphanumeric <= alphabetic | numericspecial       <= !|%|^|&|*|(|)|-|+|=|{|}|||~|[|]|\|;|'|:|"|<|>|?|,|.|/|#|@|`|_graphic     <= alphanumeric | special

In the special rule, the bracket/brace characters stand for themselves (not EBNF options nor repetitions) and one instance of the vertical bar stands for itself too: this is the problem one has when the character set of the language includes special characters that also have meanings in EBNF.

White space consists of spaces (from the space bar), horizontal and vertical tabs, line terminators (newlines and formfeeds): all are non-printing characters, so we must describe them in English. White space and tokens are closely related: we can use white space to force the end of one token and the start of another token (i.e., white space is used to separate tokens). For example XY is considered to be a single token, while X Y is considered to be two tokens. The "white space separates tokens" rule is inoperative inside String/char literals, and comments (which are all discussed later).

Page 7: Java Notes

Adding extra white space (e.g., blank lines, spaces in a line -often for indenting) to a program changes its appearance but not its meaning to Java: it still comprises exactly the same tokens in the same order. Programmers mostly use white space for purely stylistic purposes: to isolate/emphasize parts of programs and to make them easier to read and understand. Just as a good comedian know where to pause when telling a joke; a good programmer knows where to put white space when writing code.

JAVA KEYWORDS

The second category of token is a Keyword, sometimes called a reserved word. Keywords are identifiers that Java reserves for its own use. These identifiers have built-in meanings that cannot change. Thus, programmers cannot use these identifiers for anything other than their built-in meanings. Technically, Java classifies identifiers and keywords as separate categories of tokens.

The following is a list of all 49 Java keywords we will learn the meaning of many, but not all,of them in this course. It would be an excellent idea to print this table, and then check off the meaning of each keyword when we learn it; some keywords have multiple meanings, determined by the context in which they are used.

abstract continue goto package switch

assert default if private this

boolean do implements protected throw

break double import public throws

byte else instanceof return transient

case extends int short try

catch final interface static void

char finally long strictfp volatile

class float native super while

const for new synchronized  

Notice that all Java keywords contain only lower-case letters and are at least 2 characters long; therefore, if we choose identifiers that are very short (one character) or that have at least one upper-case letter in them, we will never have to worry about them clashing with (accidentally being mistaken for) a keyword. Also note that in the Metrowerks IDE (if you use my color preferences), keywords always appear in yellow (while identifiers, and many other tokens, appear in white).

Page 8: Java Notes

We could state this same tabular information as a very long (and thus harder to read) EBNF rule of choices (and we really would have to specify each of these keywords, and not use "...") looking like

keyword <= abstract | boolean | ... | while

Finally, assert was recently added (in Java 1.4) to the original 48 keywords in Java.

SEPARATORS

The third category of token is a Separator (also known as a punctuator). There are exactly nine, single character separators in Java, shown in the following simple EBNF rule.

separator <= ; | , | . | ( | ) | { | } | [ | ]

In the separator rule, the bracket/brace characters stand for themselves (not EBNF options or repetitions).

Note that the first three separators are tokens that separate/punctuate other tokens. The last six separators (3 pairs of 2 each) are also known as delimiters: wherever a left delimiter appears in a correct Java program, its matching right delimiter appears soon afterwards (they always come in matched pairs). Together, these each pair delimits some other entity.

For example the Java code Math.max(count,limit); contains nine tokens

1. an identifier (Math), followed by 2. a separator (a period), followed by

3. another identifier (max), followed by

4. a separator (the left parenthesis delimiter), followed by

5. an identfier (count), followed by

6. a separator (a comma), followed by

7. another identifier(limit), followed by

8. a separator (the right parenthesis delimiter), followed by

9. a separator (a semicolon)

OPERATORS

The fourth category of token is an Operator. Java includes 37 operators that are listed in the table below; each of these operators consist of 1, 2, or at most 3 special characters.

= > < ! ~ ? :        

Page 9: Java Notes

== <= >= != && || ++ --      

+ - * / & | ^ % << >> >>>

+= -= *= /= &= |= ^= %= <<= >>= >>=

The keywords instanceof and new are also considered operators in Java. This double classification can be a bit confusing; but by the time we discuss these operators, you'll know enough about programmig to take them in stride.

It is important to understand that Java always tries to construct the longest token from the characters that it is reading. So, >>= is read as one token, not as the three tokens > and > and =, nor as the two tokens >> and =, nor even as the two tokens > and >=.

Of course, we can always use white space to force Java to recognize separate tokens of any combination of these characters: writing >   >= is the two tokens > and >=.

We could state this same tabular information as a very long (and thus harder to read) EBNF rule of choices (and we really would have to specify each of these operators, and not use "...") looking like

operator <=   = | > | ... | >>= | instanceof | new

LITERALS AND TYPES

The fifth, and most complicated category of tokens is the Literal. All values that we write in a program are literals: each belongs to one of Java's four primitive types (int, double, boolean, char) or belongs to the special reference type String. All primitive type names are keywords in Java; the String reference type names a class in the standard Java library, which we will learn much more about soon. A value (of any type) written in a Java program is called a literal; and, each written literal belongs in (or is said to have) exactly one type.

literal <= integer-literal | floating-point-literal | boolean-literal                | character-literal | string-literal | null-literal

Here are some examples of literals of each of these types.

Literal type

1 int

3.14 double (1. is a double too)

true boolean

'3' char ('P' and '+' are char too)

Page 10: Java Notes

Literal type

"CMU ID" String

null any reference type

The next six sections discuss each of these types of literals, in more detail.

INT LITERALS

Literals of the primitive type int represent countable, discrete quantities (values with no fractions nor decimal places possible/necessary). We can specify the EBNF for an int literal in Java as

non-zero-digit     <= 1|2|3|4|5|6|7|8|9digit                     <= 0 | non-zero-digitdigits                   <= digit{digit}decimal-numeral <= 0 | non-zero-digit[digits]integer-literal      <= decimal-numeral                              | octal-numeral                              | hexidecimal-numeral

This EBNF specifies only decimal (base 10) literals. In Java literals can also be written in ocal (base 8) and hexidecimal (base 16). I have omitted the EBNF rules for forming these kinds of numbers, because we will use base 10 exclusively. Thus, the rules shown above are correct, but not complete.

By the EBNF rules above, note that the symbol 015 does not look like a legal integer-literal; it is certainly not a decimal-numeral, because it starts with a zero. But, in fact, it is an octal-numeral (whose EBNF is not shown). Never start an integer-literal with a 0 (unless its value is zero), because starting with a 0 in Java signifies the literal is being written as an octal (base 8) number: e.g., writing 015 refers to an octal value, whose decimal (base 10) value is 13! So writing a leading zero in an integer can get you very confused about what you said to the computer.

Finally, note that there are no negative literals: we will see soon how to compute such values from the negate arithmetic operator and a positive literal (writing -1 is exactly such a construct). This is a detail: a distinction without much difference.

DOUBLE LITERAL

Literals of the primtive type double represent measureable quantities. Like real numbers in mathematics, they can represent fractions and numbers with decimal places. We can specify the EBNF for a double literal in Java as

exponent-indicator   <= e | E exponent-part           <= exponent-indicator [+|-]digitsfloating-point-literal <= digits exponent-part

Page 11: Java Notes

                                    | digits.[digits][exponent-part]                                    | .digits[exponent-part]

This EBNF specifies a floating-point-literal to contain various combinations of a decimal point and exponent (so long as one -or both- are present); if neither is present then the literal must be classified as an int-literal. The exponent-indicator (E or e) should be read to mean "times 10 raised to the power of".

Like literals of the type int, all double literals are non-negative (although they may contain negative exponents). Using E or e means that we can specify very large or small values easily (3.518E+15 is equivalent to 3.518 times 10 raised to the power of 15, or 3518000000000000.; and 3.518E-15 is equivalent to 3.518 times 10 raised to the power of -15, or .000000000000003518) In fact, any literal with an exponent-part is a double: so even writing 1E3 is equivalent to writing 1.E3, which are both equivalent to writing 1000. Note this does not mean the int literal 1000!

Finally, all double literals must be written in base 10 (unlike int literals, which can be written in octal or hexadecimal)

BOOLEAN LITERAL

The type name boolean honors George Boole, a 19th century English mathematician who revolutionized the study of logic by making it more like arithmetic. He invented a method for calculating with truth values and an algebra for reasoning about these calculations. Boole's methods are used extensively today in the engineering of hardware and software systems.

Literals of the primitive type boolean represent on/off, yes/no, present/absent, ... data. There are only two values of this primtive type, so its ENBF rule is trivially written as

boolean-literal <= true | false

In Java, although these values look like identifiers, they are classified as literal tokens (just as all the keywords also look like identifiers, but are classified differently). Therefore, 100 and true are both literal tokens in Java (of type int and boolean respectively).

Students who are familiar with numbers sometimes have a hard time accepting true as a value; but that is exactly what it is in Java. We will soon learn logical operators that compute with these values of the type boolean just as arithmetic operators compute with values of the type int.

CHARACTER LITERAL

The first type of text literal is a char. This word can be pronounced in many ways: care, car, or as in charcoal (I'll use this last pronunciation). Literals of this primitive type represent exactly one character inside single quotes. Its EBNF rule is written

character-literal <= 'graphic' | 'space' | 'escape-sequence'

Page 12: Java Notes

where the middle option is a space between single quotes. Examples are 'X', or 'x', or '?', or ' ', or '\n', etc. (see below for a list of some useful escape sequences).

Note that 'X' is classified just as a literal token (of the primitive type char); it is NOT classified as an identifier token inside two separator tokens!

STRING LITERAL

The second type of text literal is a String. Literals of this reference type (the only one in this bunch; it is not a primitive type) represent zero, one, or more characters: Its EBNF is written

string-literal <= "{graphic | space | escape-sequence}"

Examples are: "\n\nEnter your SSN:", or "" (the empty String), or "X" (a one character String, which is different from a char).

Note that "CMU" is classified just as a literal token (of the reference type String); it is NOT classified as an identifier token inside two separator tokens!

ESCAPE SEQUENCES

Sometimes you will see an escape-sequence inside the single-quotes for a character-literal or one or more inside double-quotes for a string-literal (see above); each escape sequence is translated into a character that prints in some "special" way. Some commonly used escape sequences are

Escape Sequence Meaning

\n new line

\t horizontal tab

\v vertical tab

\b backspace

\r carriage return

\f form feed

\a bell

\\ \ (needed to denote \ in a text literal)

\' ' (does not act as the right ' of a char literal)

\" " (does not act as the right " of a String literal)

Page 13: Java Notes

So, in the String literal "He said, \"Hi.\"" neither escape sequence \" acts to end the String literal: each represents a double-quote that is part of the String literal, which displays as He said, "Hi."

If we output "Pack\nage", Java would print on the console

Package

with the escape sequence \n causing Java to immediately terminate the current line and start at the beginning of a new line.

There are other ways in Java to write escape sequences (dealing with unicode represented by octal numbers) that we will not cover here, nor need in the course. The only escape sequence that we will use with any frequency is \n.

THE NULL REFERENCE LITERAL

There is a very simple, special kind of literal that is used to represent a special value with every reference type in Java (so far we know only one, the type String). For completeness we will list it here, and learn about its use a bit later. Its trivial EBNF rule is written

null-literal <= null

So, as we learned with boolean literals, null is a literal in Java, not an identifier.

BOUNDED NUMERIC TYPES

Although there are an infinite number of integers in mathematics, values in the int type are limited to the range from -2,147,483,648 to 2,147,483,647. We will explore this limitation later in the course, but for now we will not worry about it.

Likewise, although there are an infinite number of reals in mathematics, values in the double type are limited to the range from-1.79769313486231570x10308 to 1.79769313486231570x10308; the smallest non-zero, positive value is 4.94065645841246544x10-324. Values in this type can have up to about 15 significant digits. For most engineering and science calculations, this range and precision are adequate.

In fact, there are other primitive numeric types (which are also keywords): short, long, and float. These types are variants of int and double and are not as widely useful as these more standard types, so we will not cover them in this course.

Finally, there is a reference type named BigInteger, which can represent any number of digits in an integer (up to the memory capacity of the machine). Such a type is very powerful (because it can represent any integer), but costly to use (in execution time and computer space) compared to int. Most programs can live with the "small" integer values specified above; but, we will also study this reference type soon, and write programs using it.

Page 14: Java Notes

COMMENTS

The sixth and final category of tokens is the Comment. Comments allow us to place any form of documentation inside our Java code. They can contain anything that we can type on the keyboard: English, mathematics, even low-resolution pictures. In general, Java recognizes comments as tokens, but then excludes these tokens from further processing; technically, it treats them as white space when it is forming tokens.

Comments help us capture aspects of our programs that cannot be expressed as Java code. Things like goals, specification, design structures, time/space tradeoffs, historical information, advice for using/modifying this code, etc. Programmers intensely study their own code (or the code of others) when maintaining it (testing, debugging or modifying it). Good comments in code make all these tasks much easier.

Java includes two style for comments.

Line-Oriented: begins with // and continues until the end of the line. Block-Oriented: begins with /* and continues (possibly over many lines) until */ is

reached.

o So, we can use block-oriented comments to create multiple comments within a line    display(/*Value*/ x, /*on device*/ d);In contrast, once a line-oriented comment starts, everything afterward on its line is included in the comment.

o We can also use block-oriented comments to span multiple lines/*    This is a multi-line comment.    No matter home many lines    it includes, only one pair    of delimiters are needed.*/In contrast, a line-oriented comment stops at the end of the line it starts on.

Technically, both kinds of comments are treated as white space, so writing X/*comment*/Y has the same meaning in Java as writing the tokens X and Y, not the single token XY.

Typically Java comments are line-oriented; we will save block-oriented comments for a special debugging purpose (discussed later).

The EBNF rule for comments is more complicated than insightful, so we will not study here. This happens once in a while.

BASICS OF CLASS & OBJECT

Page 15: Java Notes

Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts:

Polymorphism Inheritance

Encapsulation

Abstraction

Classes

Objects

Instance

Method

Message Parsing

In this chapter we will look into the concepts Classes and Objects.

Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.

Objects in Java:

Let us now look deep into what are objects. If we consider the real-world we can find many objects around us, Cars, Dogs, Humans etc. All these objects have a state and behavior.

If we consider a dog then its state is . name, breed, color, and the behavior is . barking, wagging, running

If you compare the software object with a real world object, they have very similar characteristics.

Software objects also have a state and behavior. A software object's state is stored in fields and behavior is shown via methods.

So in software development methods operate on the internal state of an object and the object-to-object communication is done via methods.

Classes in Java:

A class is a blue print from which individual objects are created.

Page 16: Java Notes

A sample of a class is given below:

public class Dog{ String breed; int age; String color;

void barking(){ } void hungry(){ } void sleeping(){ }}

A class can contain any of the following variable types.

Local variables . variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

Instance variables . Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

Class variables . Class variables are variables declared with in a class, outside any method, with the static keyword.

A class can have any number of methods to access the value of various kind of methods. In the above example, barking(), hungry() and sleeping() are variables.

Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language.

Constructors:

When discussing about classes one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.

Each time a new object is created at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.

Example of a constructor is given below:

Page 17: Java Notes

class Puppy{ public puppy(){ }

public puppy(String name){ // This constructor has one parameter, name. }}

Java also supports Singleton Classes where you would be able to create only one instance of a class.

Creating an Object:

As mentioned previously a class provides the blueprints for objects. So basically an object is created from a class. In java the new key word is used to create new objects.

There are three steps when creating an object from a class:

Declaration . A variable declaration with a variable name with an object type. Instantiation . The 'new' key word is used to create the object.

Initialization . The 'new' keyword is followed by a call o a constructor. This call initializes the new object.

Example of creating an object is given below:

class Puppy{ public Puppy(String name){ // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public static void main(String []args){ // Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy" ); }}

If we compile and run the above program then it would produce following result:

Passed Name is :tommy

Accessing Instance Variables and Methods:

Page 18: Java Notes

Instance variables and methods are accessed via created objects. To access an instance variable the fully qualified path should be as follows:

/* First create an object */ObjectReference = new Constructor();

/* Now call a variable as follows */ObjectReference.variableName;

/* Now you can call a class method as follows */ObjectReference.MethodName();

Example:

This example explains how to access instance variables and methods of a class:

class Puppy{ int puppyAge;

public Puppy(String name){ // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public setAge( int age ){ puppyAge = age; }

public getAge( ){ System.out.println("Puppy's age is :" + puppyAge ); return puppyAge; } public static void main(String []args){ /* Object creation */ Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */ myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */ myPuppy.getAge( );

/* You can access instance variable as follows as well */ System.out.println("Variable Value :" + myPuppy.puppyAge ); }}

Page 19: Java Notes

If we compile and run the above program then it would produce following result:

Passed Name is :tommyPuppy's age is :2Variable Value :2

CONSTRUCTORS

Here, you will learn more about Constructor and how constructors are overloaded in Java. This

section provides you a brief introduction about the Constructor that are overloaded in the given

program with complete code absolutely in running state i.e. provided for best illustration about

the constructor overloading in Java.

Constructors are used to assign initial values to instance variables of the class. A default

constructor with no arguments will be called automatically by the Java Virtual Machine (JVM).

Constructor is always called by new operator. Constructor are declared just like as we declare

methods, except that the constructor don't have any return type. Constructor can be overloaded

provided they should have different arguments because JVM differentiates constructors on the

basis of arguments passed in the constructor.

Whenever we assign the name of the method same as  class name. Remember this method should

not have any return type. This is called as constructor overloading. 

We have made one program on a constructor overloading, after going through it the concept of

constructor overloading will get more clear. In the example below we have made three

overloaded constructors each having different arguments  types so that the JVM can

differentiates between the various constructors.

The code of the program is given below:

public class ConstructorOverloading{  public static void main(String args[]){  Rectangle rectangle1=new Rectangle(2,4);  int areaInFirstConstructor=rectangle1.first();  System.out.println(" The area of a rectangle in   first constructor is :  " + areaInFirstConstructor);  Rectangle rectangle2=new Rectangle(5);  int areaInSecondConstructor=rectangle2.second();  System.out.println(" The area of a rectangle in    first constructor is :  " + areaInSecondConstructor);

Page 20: Java Notes

  Rectangle rectangle3=new Rectangle(2.0f);  float areaInThirdConstructor=rectangle3.third();  System.out.println(" The area of a rectangle in first   constructor is :  " + areaInThirdConstructor);  Rectangle rectangle4=new Rectangle(3.0f,2.0f);  float areaInFourthConstructor=rectangle4.fourth();  System.out.println(" The area of a rectangle in first   constructor is :  " + areaInFourthConstructor);  }}

class Rectangle{  int l, b;  float p, q;  public Rectangle(int x, int y){  l = x;  b = y;  }  public int first(){   return(l * b);  }  public Rectangle(int x){  l = x;  b = x;  }  public int second(){  return(l * b);  }  public Rectangle(float x){  p = x;  q = x;  }  public float third(){  return(p * q);  }  public Rectangle(float x, float y){  p = x;  q = y;  }  public float fourth(){  return(p * q);  }}

Output of the program is given below:

Page 21: Java Notes

C:\java>java ConstructorOverloadingThe area of a rectangle in first constructor is : 8The area of a rectangle in first constructor is : 25The area of a rectangle in first constructor is : 4.0The area of a rectangle in first constructor is : 6.0

METHOD OVERLOADING

In Java it is possible to define two or more methods within the same class that share the

same name, as long as their parameter declarations are different. When this is the case, the

methods are said to be overloaded, and the process is referred to as method overloading.

Method overloading is one of the ways that Java implements polymorphism.

If you have never used a language that allows the overloading of methods, then the concept

may seem strange at first. But as you will see, method overloading is one of Java's most

exciting and useful features. When an overloaded method is invoked, Java uses the type

and/or number of arguments as its guide to determine which version of the overloaded

method to actually call. Thus, overloaded methods must differ in the type and/or number of

their parameters. While overloaded methods may have different return types, the return type

alone is insufficient to distinguish two versions of a method. When Java encounters a call to

an overloaded method, it simply executes the version of the method whose parameters

match the arguments used in the call. Here is a simple example that illustrates method

overloading:

// Demonstrate method overloading.

class OverloadDemo {

void test() {

System.out.println("No parameters");

}

// Overload test for one integer parameter.

void test(int a) {

System.out.println("a: " + a);

}

// Overload test for two integer parameters.

void test(int a, int b) {

Page 22: Java Notes

System.out.println("a and b: " + a + " " + b);

}

// overload test for a double parameter

double test(double a) {

System.out.println("double a: " + a);

return a*a;

}

}

class Overload {

public static void main(String args[]) {

OverloadDemo ob = new OverloadDemo();

double result;

// call all versions of test()

ob.test();

ob.test(10);

ob.test(10, 20);

result = ob.test(123.2);

System.out.println("Result of ob.test(123.2): " + result);

}

}

This program generates the following output:

No parameters

a: 10

a and b: 10 20

double a: 123.2

Result of ob.test(123.2): 15178.24

As you can see, test( ) is overloaded four times. The first version takes no parameters, the

second takes one integer parameter, the third takes two integer parameters, and the fourth

takes one double parameter. The fact that the fourth version of test( ) also returns a value is

of no consequence relative to overloading, since return types do not play a role in overload

resolution.

When an overloaded method is called, Java looks for a match between the arguments used

to call the method and the method's parameters. However, this match need not always be

Page 23: Java Notes

exact. In some cases Java's automatic type conversions can play a role in overload

resolution. For example, consider the following program:

// Automatic type conversions apply to overloading.

class OverloadDemo {

void test() {

System.out.println("No parameters");

}

// Overload test for two integer parameters.

void test(int a, int b) {

System.out.println("a and b: " + a + " " + b);

}

// overload test for a double parameter

void test(double a) {

System.out.println("Inside test(double) a: " + a);

}

}

class Overload {

public static void main(String args[]) {

OverloadDemo ob = new OverloadDemo();

int i = 88;

ob.test();

ob.test(10, 20);

ob.test(i); // this will invoke test(double)

ob.test(123.2); // this will invoke test(double)

}

}

This program generates the following output:

No parameters

a and b: 10 20

Inside test(double) a: 88

Inside test(double) a: 123.2

As you can see, this version of OverloadDemo does not define test(int). Therefore, when

test( ) is called with an integer argument inside Overload, no matching method is found.

However, Java can automatically convert an integer into a double, and this conversion can

Page 24: Java Notes

be used to resolve the call. Therefore, after test(int) is not found, Java elevates i to double

and then calls test(double). Of course, if test(int) had been defined, it would have been

called instead. Java will employ its automatic type conversions only if no exact match is

found.

Method overloading supports polymorphism because it is one way that Java implements the

"one interface, multiple methods" paradigm. To understand how, consider the following. In

languages that do not support method overloading, each method must be given a unique

name. However, frequently you will want to implement essentially the same method for

different types of data. Consider the absolute value function. In languages that do not

support overloading, there are usually three or more versions of this function, each with a

slightly different name. For instance, in C, the function abs( ) returns the absolute value of

an integer, labs( ) returns the absolute value of a long integer, and fabs() returns the

absolute value of a floating-point value. Since C does not support overloading, each

function has to have its own name, even though all three functions do essentially the same

thing. This makes the situation more complex, conceptually, than it actually is. Although the

underlying concept of each function is the same, you still have three names to remember.

This situation does not occur in Java, because each absolute value method can use the same

name. Indeed, Java's standard class library includes an absolute value method, called abs( ).

This method is overloaded by Java's Math class to handle all numeric types. Java

determines which version of abs() to call based upon the type of argument.

The value of overloading is that it allows related methods to be accessed by use of a

common name. Thus, the name abs represents the general action which is being performed.

It is left to the compiler to choose the right specific version for a particular circumstance.

You, the programmer, need only remember the general operation being performed. Through

the application of polymorphism, several names have been reduced to one. Although this

example is fairly simple, if you expand the concept, you can see how overloading can help

you manage greater complexity.

When you overload a method, each version of that method can perform any activity you

desire. There is no rule stating that overloaded methods must relate to one another.

However, from a stylistic point of view, method overloading implies a relationship. Thus,

while you can use the same name to overload unrelated methods, you should not. For

example, you could use the name sqr to create methods that return the square of an integer

and the square root of a floating-point value. But these two operations are fundamentally

Page 25: Java Notes

different. Applying method overloading in this manner defeats its original purpose. In

practice, you should only overload closely related operations.

STATIC MEMBERS

Static variable

This Java programming example will teach you how you can define the static class variable in a class.

When a number of objects are created from the same class, each instance has its own copy of class

variables. But this is not the case when it is declared as static static.

static  method or a variable is not attached to a particular object, but rather to the class as a whole. They

are allocated when the class is loaded. Remember, each time you call the instance the new value of the

variable is provided to you. For example in the class StaticVariable each instance has different copy of a

class variable. It will be updated each time the instance has been called. We can call class variable

directly inside the main method.

To see the use of a static variable first of all create a class StaticVariable. Define one static variable in

the class. Now make a  constructor  in which you will increment the value of the static variable. Now make

a object of StaticVariable class and call the static variable of the class. In the same way now make a

second object of the class and again repeats the process. Each time you call the static variable you will

get a new value.

public class StaticVariable {

static int noOfInstances;

StaticVariable(){

noOfInstances++;

}

public static void main(String[] args){

StaticVariable sv1 = new StaticVariable();

System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);

StaticVariable sv2 = new StaticVariable();

System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);

Page 26: Java Notes

System.out.println("No. of instances for st2 : " + sv2.noOfInstances);

StaticVariable sv3 = new StaticVariable();

System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);

System.out.println("No. of instances for sv2 : " + sv2.noOfInstances);

System.out.println("No. of instances for sv3 : " + sv3.noOfInstances);

StaticVariable sv4 = new StaticVariable();

System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);

System.out.println("No. of instances for sv2 : " + sv2.noOfInstances);

System.out.println("No. of instances for sv3 : " + sv3.noOfInstances);

System.out.println("No. of instances for sv4 : " + sv4.noOfInstances);

StaticVariable sv5 = new StaticVariable();

System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);

System.out.println("No. of instances for sv2 : " + sv2.noOfInstances);

System.out.println("No. of instances for sv3 : " + sv3.noOfInstances);

System.out.println("No. of instances for sv3 : " + sv4.noOfInstances);

System.out.println("No. of instances for sv3 : " + sv5.noOfInstances);

}

}

STATIC METHOD

This Java programming example will teach you the way to define a static methods. In java we

have two types of methods, instance methods and static methods. Static methods can't use any

instance variables. The this keyword can't be used in a static methods. You can find it difficult to

understand when to use a static method and when not to use. If you have a better understanding

of the instance methods and static methods then you can know where to use instance method and

static method. 

Page 27: Java Notes

A static method can be accessed without creating an instance of the class. If you try to use a non-

static method and variable defined in this class then the compiler will say that non-static variable

or method cannot be referenced from a static context. Static method can call only other static

methods and  static variables defined in the class. 

The concept of static method will get more clear after this program. First of all create a class

HowToAccessStaticMethod. Now define two variables in it, one is instance variable and other

is class variable. Make one static method named staticMethod() and second named as

nonStaticMethod(). Now try to call both the method without constructing a object of the class.

You will find that only static method can be called this way. 

public class HowToAccessStaticMethod

{

int i;

static int j;

public static void staticMethod(){

System.out.println("you can access a static method this way");

}

public void nonStaticMethod(){

i=100;

j=1000;

System.out.println("Don't try to access a non static method");

}

public static void main(String[] args) {

//i=100;

j=1000;

//nonStaticMethod();

Page 28: Java Notes

staticMethod();

}

}