JAVA UNIT-1 Notes PDF
JAVA UNIT-1 Notes PDF
History of Java:
Before starting to learn Java, let us plunge into its history and see how the language
originated. In 1990, Sun Microsystems Inc. (US) was conceived a project to develop software
for consumer electronic devices that could be controlled by a remote. This project was called
Stealth Project but later its name was changed to Green Project.
In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton, and
several others met in Aspen, Colorado to discuss this' project. Mike Sheradin was to focus on
business development; Patrick Naughton was to begin work on the graphics system; and
James Gosling was to identify the proper programming language for the project. Gosling
thought C and C++ could be used to develop the project.
But the problem he faced with them is that they were system dependent languages and
hence could not be used on various processors, which the electronic devices might use. So he
started developing a new language, which was completely system independent. This language
was initially called Oak. Since this name was registered by some other company, later it was
changed to Java.
Why the name Java? James Gosling and his team members were consuming a lot of
tea while developing this language. They felt that they were able to develop a better language
because of the good quality tea they had consumed. So the tea also had its own role in
developing this language and hence, they fixed the name for the language as Java. Thus, the
symbol for Java is tea cup and saucer.
Features of Java:
Simple: Java is a simple programming language. Rather than saying that this is the
feature of Java, we can say that this is the design aim of Java. JavaSoft (the team who
developed Java is called with this name) people maintained the same syntax of C and
C++ in Java, so that a programmer who knows C or C++ will find Java already familiar.
Object-oriented: Java is an object oriented programming language. This means Java
programs use objects and classes. What is an object? An object is anything that really
exists in the world and can be distinguished from others.
First of all, the .java program is converted into a .class file consisting of byte code
instructions by the java compiler. Remember, this java compiler is outside the JVM: Now this
.class file is given to the JVM. In JVM, there is a module (or program) called class loader
sub system, which performs the following functions:
First of all, it loads the .class file into memory.
Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.
If the byte instructions are proper, then it allocates necessary memory to execute the
program.
This memory is divided into 5 parts, called run time data areas, which contain the data and
results while running the program. These areas are as follows:
Method area: Method area is the memory block, which stores the class code, code of
the variables, and code of the methods in the Java program. (Method means functions
written in a class)
Heap: This is the area where objects are created. Whenever JVM loads a class, a
method and a heap area are immediately created in it.
Java Stacks: Method code is stored on Method area. But while running a method, it
needs some more memory to store the data and results. This memory is allotted on Java
stacks.
PC (Program Counter) registers: These are the registers (memory areas), which
contain memory address of the instructions of the methods. If there are 3 methods, 3 PC
registers will be used to track the instructions of the methods.
Native method stacks: Java methods are executed on Java stacks. Similarly, native
methods (for example C/C++ functions) are executed on Native method stacks. To
execute the native methods, generally native method libraries (for example C/C++
header files) are required. These header files are located and connected to JVM by a
program, called Native method interface.
Execution engine contains interpreter and JIT (Just In Time) compiler, which are
responsible for converting the byte code instructions into machine code so that the processor
will execute them. Most of the JVM implementations use both the interpreter and JIT
compiler simultaneously to convert the byte code. This technique is also called adaptive
optimizer. Generally, any language (like C/C++, Fortran, COBOL, etc.) will use either an
interpreter or a compiler to translate the source code into a machine code. But in JVM, we got
interpreter and JIT compiler both working at the same time on byte code to translate it into
machine code.
Java Program Structure:
Documentation Section
Package Statement
Import Statements
Interface Statement
Class Definition
Main Method Class
o Main Method Definition
Multi-line comments: These comments are used for representing several lines as
comments. These comments start with / * and end with * /. In between / * and * /,
whatever is written is treated as a comment. For example,
/* This is Multi line comment,
Line 2 is here
Line 3 is here */
Importing Classes:
In C/C++ compiler to include the header file <stdio.h>. What is a header file? A
header file is a file, which contains the code of functions that will be needed in a program. In
other words, to be able to use any function in a program, we must first include the header file
containing that function's code in our program. For example, <stdio.h> is the header me that
contains functions, like printf (), scanf (), puts (), gets (), etc. So if we want to use any of
these functions, we should include this header file in our C/C++ program.
A similar but a more efficient mechanism, available in case of Java, is that of
importing classes. First, we should decide which classes are 'needed in our program.
Generally, programmers are interested in two things:
Using the classes by creating objects in them.
Using the methods (functions) of the classes.
In Java, methods are available in classes or interfaces. What is an interface? An interface
is similar to a class that contains some methods. Of course, there is a lot of difference
between an interface and a class, which we will discuss later. The main point to be kept in
mind, at this stage, is that a class or an interface contains methods. A group of classes and
interfaces are contained in a package. A package is a kind of directory that contains a group
of related Classes and interfaces and Java has several such packages in its library,
Java library
|
Packages
|
Classes and interfaces
|
Methods
In our first Java program, we are using two classes namely, System and String. These
classes belong to a package called java .lang (here lang represents language). So these two
classes must be imported into our program, as shown below:
import java.lang.System;
import java.lang.String;
Whenever we want to import several classes of the same package, we need not write
several import statements, as shown above; instead, we can write a single statement as:
import java.lang.*;
Here, * means all the classes and interfaces of that package, i.e. java.lang, are
imported made available) into our program. In import statement, the package name that we
have written acts like a reference to the JVM to search for the classes there. JVM will not
copy any code from the classes or packages. On the other hand, when a class name or a
method name is used, JVM goes to the Java library, executes the code there, comes back, and
substitutes the result in that place of the program. Thus, the Java program size will not be
increased.
After importing the classes into the program, the next step is to write a class, Since
Java is purely an object-oriented programming language and we cannot write a Java program
without having at least one class or object. So, it is mandatory that every Java program should
have at least one class in it, How to write a class? We should use class keyword for this
purpose and then write the class name.
class Hello{
statements;
}
A class code starts with a { and ends with a }. We know that a class or an object
contains variables and methods (functions), 'So we can create any number of variables and
methods inside the class. This is our first program, so we will create only one method, i.e.
compulsory, main () method.
The main method is written as follows:
public static void main(String args[ ])
Here args[ ] is the array name and it is of String type. This means that it can store a
group of strings. Remember, this array can also store a group of numbers but in the
form of strings only. The values passed to main( ) method are called arguments. These
arguments are stored into args[ ] array, so the name args[ ] is generally used for it.
If a method is not meant to return any value, then we should write void before that
method's name. void means no value. main() method does not return any value, so void
should be written before that method's name.
static methods are the methods, which can be called and executed without creating the
objects. Since we want to call main()method without using an object, we should
declare main( ) method as static. Then, how is the main( ) method called and executed?
The answer is by using the classname.methodname(). JVM calls main() method
using its class name as Hello.main() at the time of running the program.
JVM is a program written by JavaSoft people (Java development team) and main() is
the method written by us. Since, main() method should be available to the JVM, it
should be declared as public. If we don't declare main() method as public, then. It
doesn't make itself available to JVM and JVM cannot execute it:
So, the main()method should always be written as shown here:
public static void main(String args[ ])
If at all we want to make any changes, we can interchange public and static and write it as
follows:
static public void main(String args[])
Or, we can use a different name for the string type array and write it as:
public static void main(String x[])
Q) When main() method is written without String args[args]:
public static void main ()
Ans: The code will compile but JVM cannot run the code because it cannot
recognize the main () method as the method from where it should start
execution of the Java program. Remember JVM always looks for main () method
with string type array as parameter.
System.out.print(“Welcome to java”);
System.out gives the PrintStream class object. This object, by default, represents the standard
output device, i.e. the monitor. So, the string "Welcome to Java" will be sent to the monitor.
class Hello
{
public static void main(String[] args)
{
System.out.print(“Welcome to java”);
}
}
Save the above program in a text editor like Notepad with the name Hello.java. Now, go to
System prompt and compile it using javac compiler as:
javac Hello.java
The compiler generates a file called Hello.class that contains byte code instructions. This file
is executed by calling the JVM as:
java Hello
Then, we can see the result.
Note: In fact, JVM is written in C language.
Output:
C:\> javac Hello.java
C:\> java Hello
Welcome to Java
Program: Write a program to find the sum of addition of two numbers.
class Add
{
public static void main(String args[])
{
int x, y;
x = 27;
y = 35;
int z = x + y;
System.out.print(“The Sum is “+z);
}
}
Variables:
A variable provides us with named storage that our programs can manipulate. Each
variable in Java has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.
You must declare all variables before they can be used. Following is the basic form
of a variable declaration −
DataType variable [ = value][, variable [ = value] ...] ;
Here DataType is one of Java's datatypes and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java −
Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'
b) Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access
modifiers.
Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned during
the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the
class. However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified
name. ObjectReference.VariableName.
Example 1
import java.io.*;
public class Employee {
public String name;
public Employee (String empName) {
name = empName;
}
public void printEmp() {
System.out.println("name : " + name );
}
public static void main(String args[]) {
Employee empOne = new Employee("Sai krishna");
empOne.printEmp();
}
}
This will produce the following result −
Output
name : Sai krishna
c) Class/Static Variables
Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables
never change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program
stops.
Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
Default values are same as instance variables. Static variables can be accessed by
calling with the class name ClassName.VariableName.
Example 1
import java.io.*;
public class Employee {
private static double salary;
public static void main(String args[]) {
salary = 1000;
System.out.println("average salary:" + salary);
}
}
This will produce the following result −
average salary:1000
Identifiers:
Identifiers are the names of variables, methods, classes, packages and interfaces. In the Hello
program, Hello, String, args, main and print are identifiers. There are a few rules and
conventions related to the naming of variables.
The rules are:
1. Java variable names are case sensitive. The variable name money is not the same
as Money or MONEY.
2. Java variable names must start with a letter, or the $ or _ character.
3. After the first character in a Java variable name, the name can also contain numbers
(in addition to letters, the $, and the _ character).
4. Variable names cannot be equal to reserved key words in Java. For instance, the
words int or forare reserved words in Java. Therefore you cannot name your
variables int or for.
Here are a few valid Java variable name examples:
myvar myVar MYVAR _myVar
$myVar myVar1 myVar_1
Data types:
Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning different data
types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java −
a) Primitive Data Types
b) Reference/Object Data Types
a) Primitive Data Types
There are eight primitive datatypes supported by Java. Primitive datatypes are
predefined by the language and named by a keyword. Let us now look into the eight
primitive data types in detail.
Java Literals
A literal is a value that is stored into a variable directly in the program. There are 5
types of literals.
a) Integer Literals
b) Float Literals
c) Character Literals
d) String Literals
e) Boolean Literals
a) Integer Literals
class Test {
public static void main(String[] args)
{
int dec = 101; // decimal-form literal
int oct = 0100; // octal-form literal
int hex = 0xFace; // Hexa-decimal form literal
System.out.println(dec); //101
System.out.println(oct); //64
System.out.println(hex); //64206
}
}
b) Float Literals
class Test {
public static void main(String[] args)
{
double d1 = 123.4;
double d2 = 1.234e2; //Same value as d1, but in scientific notation
float f1 = 123.4f;
System.out.println(d1); //123.4
System.out.println(d2); //123.4
System.out.println(f1); //123.4
}
}
c) Character Literals
public class Test {
public static void main(String[] args)
{
char ch1 = 'a';
char ch2 = '\"';
char ch3 = '\n';
char ch4 = '\u0015';
System.out.println(ch1); // a
System.out.println(ch2); // “
System.out.println(ch3); //
System.out.println(ch4); // §
}
}
d) String Literals
String literals represent objects of String class. For example, Hello, Anil
Kumar, AP1201, etc. will come under string literals, which can be directly stored into
a String object.
e) Boolean Literals
Boolean literals represent only two values-true and false, It means we can
store either true or false into a boolean type variable.
Operators:
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true : value if false
Example
public class Test {
instanceof Operator
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). instanceof operator is written as −
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true. Following is an example
Example
public class Test {
}
}
This will produce the following result −
Output
true
Precedence of Java Operators
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Category Operator Associativity
Postfix >() [] . (dot operator) Left toright
Unary >++ - - ! ~ Right to left
Multiplicative >* / Left to right
Additive >+ - Left to right
Shift >>> >>> << Left to right
Relational >> >= < <= Left to right
Equality >== != Left to right
Bitwise AND >& Left to right
Bitwise XOR >^ Left to right
Bitwise OR >| Left to right
Logical AND >&& Left to right
Logical OR >|| Left to right
Conditional ?: Right to left
Assignment >= += -= *= /= %= >>= <<= &= ^= |= Right to left
double d2 = 66.0;
char ch2 = (char) d2;
System.out.println(ch2); // prints B
}
}
Principles of OOP:
The key ideas of the object oriented approach are:
Class / Objects
Abstraction
Encapsulation
Inheritance
Polymorphism
Class / Objects
Entire OOP methodology has been derived from a single root concept, called 'object'.
An object is anything that really exists in the world and can be distinguished from others.
This definition specifies that everything in this world is an object. For example, a table, a
ball, a car, a dog, a person, etc., everything will come under objects.
Every object has properties and can perform certain actions. For example, let us take a
person whose name is 'Raju'. Raju is an object because he exists physically. He has properties
like name, age, gender, etc. These properties can be represented by variables in our
programming.
String name;
int age;
char gender;
Similarly, Raju can perform some actions like talking, walking, eating and sleeping.
We may not write code for such actions in programming. But, we can consider calculations
and processing of data as actions. These actions are performed by methods (functions), So an
object contains variables and methods.
Abstraction
There may be a lot of data, a class contains and the user does not need the entire data.
The user requires only some part of the available data. In this case, we can hide the
unnecessary data from the user and expose only that data that is of interest to the user. This is
called abstraction.
A bank clerk should see the customer details like account number, name and balance
amount in the account. He should not be entitled to see the sensitive data like the staff
salaries, profit or loss of the bank amount paid by the bank and loans amount to be recovered
etc,. So such data can abstract from the clerk's view. Whereas the bank manager is interested
to know this data, it will be provided to the manager.
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as a single unit. In encapsulation, the variables of a
class will be hidden from other classes, and can be accessed only through the methods of
their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
Inheritance
It creates new classes from existing classes, so that the new classes will acquire all the
features of the existing classes is called Inheritance. A good example for Inheritance in nature
is parents producing the children and children inheriting the qualities of the parents.
There are three advantages inheritance. First, we can create more useful classes
needed by the application (software). Next, the process of creating the new classes is very
easy, since they are built upon already existing classes. The last, but very important
advantage is managing the code becomes easy, since the programmer creates several classes
in a hierarchical manner, and segregates the code into several modules.
Polymorphism
The word polymorphism came from two Greek words 'poly' meaning 'many' and
'morphos' meaning 'forms'. Thus, polymorphism represents the· ability to assume several
different forms. In programming, we can use a single variable to refer to objects of different
types and thus using that variable we can call the methods of the different objects. Thus
method call can perform different tasks depending on the type of object.
Polymorphism provides flexibility in writing programs in such a way that the
programmer uses same method call to perform different operations depending on the
requirement.
Application of OOP:
The promising areas includes the followings,
1. Real Time Systems Design
2. Simulation and Modeling System
3. Object Oriented Database
4. Object Oriented Distributed Database
5. Client-Server System
6. Hypertext, Hypermedia
7. Neural Networking and Parallel Programming
8. Decision Support and Office Automation Systems
9. CIM/CAD/CAM Systems
10. AI and Expert Systems
Accessing Input from the keyboard:
Input represents data given to a program and output represents data displayed as a result
of a program.
A stream is required to accept input from the keyboard. A stream represents flow of
data from one place to another place.
It is like a water-pipe where water flows. Like a water-pipe carries water from one
place to another, a stream carries data from one place to another place.
A stream can carry data from keyboard to memory or from memory to printer or from
memory to a file.
A stream is always required if we want to move data from one place to another.
Basically, there are two types of streams: input streams and output streams.
Input streams are those streams which receive or read data coming from some other
place.
Output streams are those streams which send or write data to some other place.
All streams are represented by classes in java.io (input and output) package.
This package contains a lot of classes, all of which can be classified into two basic
categories: input streams and output streams.
Keyboard is represented by a field, called in System class. When we write System.in,
we are representing a standard input device, i.e. keyboard, by default. System class is
found in java.lang (language) package and has three fields' as shown below.
All these fields represent some type of stream:
System.in: This represents Ii1putStream object, which by default represents
standard input device, i.e., keyboard.
System.out: This represents PrintStream object, which by default represents
standard output device, i.e., monitor.
System.err: This field also represents PrintStream object, which by default
represents monitor.
Note that both System.out and System.err can be used to represent the monitor and hence
any of these two can be used to send data to the monitor.
To accept data from the keyboard i.e., System.in. we need to connect it to an input stream.
And input stream is needed to read data from the keyboard.
Connect the keyboard to an input stream object. Here, we can use InputStreamReader that
can read data from the keyboard.
InputStreamReader isr = new InputStreamReader(System.in);
Connect InputStreamReader to BufferedReader, which is another input type of stream.
BufferedReader br = new BufferedReader(isr);
Now we can read data coming from the keyboard using read( ) and readLine( ) methods
available in BufferedReader class.
Ex: Write a JAVA Program to read Single character from the keyboard.
import java.io.*;
import java.lang.*;
class Test {
public static void main(String[] args)throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print("Enter a single Character: ");
char ch = (char)br.read();
System.out.print("\n The Character is "+ch);
}
}
Output:
javac Test.java
java Test
Enter a single Character: m
The Character is m
}
}
Output:
javac Test.java
java Test
Enter id name sal: 09 sudheer 40000.00
Id is: 09
Name is: sudheer
Sal is: 40000.00