Java Unit1
Java Unit1
Overview of Java
Java is a computer programming language.
Java was created based on C and C++.
Java uses C syntax and many of the object-oriented features are taken from C++.
Before Java was invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk,
etc. These languages had few disadvantages which were corrected in Java.
Java also innovated many new features to solve the fundamental problems which the previous
languages could not solve.
Java was invented by a team of 13 employees of Sun Microsystems, Inc. which is lead by James
Gosling, in 1991.
The team includes persons like Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan,
etc.,
Java was developed as a part of the Green project.
Initially, it was called Oak, later it was changed to Java in 1995.
History of Java
The C language developed in 1972 by Dennis Ritchie had taken a decade to become the most
popular language.
In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with included
OOP fundamentals and features.
A project named “Green” was initiated in December of 1990, whose aim was to create a
programming tool that could render obsolete the C and C++ programming languages.
Finally in the year of 1991 the Green Team was created a new Programming language named
“OAK”.
After some time they found that there is already a programming language with the name “OAK”.
So, the green team had a meeting to choose a new name. After so many discussions they want to
have a coffee. They went to a Coffee Shop which is just outside of the Gosling’s office and there
they have decided name as “JAVA”.
1
JAVA BUZZ WORDS
Java is the most popular object-oriented programming language.
Java has many advanced features, a list of key features is known as Java Buzz Words.
The Following list of Buzz Words
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++.
In a java programming language, many complicated features like pointers, operator
overloading, structures, unions, etc. have been removed.
One of the most useful features is the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers
concept.
java provides a feature "applet" which can be embedded into a web application.
The applet in java does not allow access to other parts of the computer, which keeps away from
harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java .
If a program yields the same result on every machine, then that program is called portable.
Java programs are portable
2
This is the result of java System independence nature.
Object-oriented
Java is an object oriented programming language.
This means java programs use objects and classes.
Robust
Robust means strong. Java programs are strong and they don’t crash easily like a C or C++ programs
There are two reasons
Java has got excellent inbuilt exception handling features. An exception is an error that occurs
at
runtime. If an exception occurs, the program terminates suddenly giving rise to problems like
loss of data. Overcoming such problem is called exception handling.
Most of the C and C++ programs crash in the middle because of not allocating sufficient memory
or forgetting the memory to be freed in a program. Such problems will not occur in java
because the user need not allocate or deallocate the memory in java. Everything will be taken
care of by JVM only.
Architecture-neutral (or) Platform Independent
Java has invented to archive "write once; run anywhere, anytime, forever".
The java provides JVM (Java Virtual Machine) to archive architectural-neutral or platform-
independent.
The JVM allows the java program created using one operating system can be executed on any
other operating system.
Multi-threaded
Java supports multi-threading programming.
Which allows us to write programs that do multiple operations simultaneously.
Interpreted
Java programs are compiled to generate byte code.
This byte code can be downloaded and interpreted by the interpreter in JVM.
If we take any other language, only an interpreter or a compiler is used to execute the program.
But in java, we use both compiler and interpreter for the execution.
3
High performance
The problem with interpreter inside the JVM is that it is slow.
Because of Java programs used to run slow.
To overcome this problem along with the interpreter.
Java soft people have introduced JIT (Just in Time ) compiler, to enhance the speed of execution.
So now in JVM, both interpreter and JIT compiler work together to run the program.
Distributed
Information is distributed on various computers on a network.
Using Java, we can write programs, which capture information and distribute it to the client.
This is possible because Java can handle the protocols like TCP/IP and UDP.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running system
and it has a dynamic memory allocation and deallocation (objects and garbage collector).
JAVA KEYWORDS:
Keywords are pre-defined words (or) reserved words.
They can't be used as a variable name, object name, or any other identifier.
All keywords must be written in lowercase.
There are 51 reserved keywords in Java.
The following table shows the standard Java keywords.
4
try void voltaile while const goto
Documentation Section
The documentation section is an important section but optional for a Java program.
It includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the documentation section, the Java
compiler ignores the statements during the execution of the program. To write the statements in the
documentation section, we use comments.
Comments there are three types
1. Single-line Comment: It starts with a pair of forwarding slash (//).
2. Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
5
Example : /* It is an example of
multiline comment */
3. Documentation Comment: It starts with the delimiter (/**) and ends with */.
Sample Java Program :
/* This is First Java Program */
class Sample
{
public static void main(String arg[]);
{
System.out.println(“ Welcome to CSE Department”);
}
}
Parameters used in First Java Program
What is the meaning of class, public, static, void, main, String[], System.out.println().
class keyword is used to declare a class in Java.
public keyword is an access modifier that represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The
core advantage of the static method is that there is no need to create an object to invoke the
static method. The main() method is executed by the JVM, so it doesn't require creating an
object to invoke the main() method. So, it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args or String args[] is used for command line argument.
System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class.
How to Compile and Run the Java Program
To Compile : javac Sample.java [ program name]
To Run : java Sample
Output : Welcome to CSE Department
6
Execution Process of Java Program
What is JVM :
Java Virtual Machine is the heart of entire java program execution process. It is responsible for taking
the .class file and converting each byte code instruction into the machine language instruction that can
be executed by the microprocessor.
Architecture of Java Virtual Machine
7
Class Loader Subsystems:
First of all we compile the .java program is converted into a .class file. The .class file consisting of byte
code instructions by the java compiler. In JVM there is a module called class loader subsystem. Which
performs the following functions.
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 code instructions are proper, then it allocates necessary memory to execute the
program.
Runtime data areas: This memory is divided into 5 parts
1. Method area: Class (Method) area is a block of memory that stores the class code, code of variables,
and methods of the Java program. Here methods mean functions declared in the class.
2. Heap area : Java objects reside in an area called the heap. The heap is created when the JVM starts
up and may increase or decrease in size while the application runs. When the heap becomes full,
garbage is collected. During the garbage collection objects that are no longer used are cleared, thus
making space for new objects.
3. Java stacks:
8
Method code is stored in the Method area. But during the execution of a method, it requires
some more memory to store the data and results. This memory is allocated on Java stacks.
Java stacks are those memory areas where Java methods are executed. In Java stacks, a separate
frame is created where the method is executed.
Each time a method is called, a new frame is created into the stack. When method invocation is
completed, a frame associated with it is destroyed.
JVM always creates a separate thread (or process) to execute each method.
4. PC Registers: The JVM supports multiple threads at the same time. Each thread has its own PC
Registers to hold the address of the currently executing JVM instruction. Once the instruction is
executed the PC register is updated with the next instruction.
5. Native method stacks: JVM contains stacks that support native methods. These methods are
written in a language other than the java programming language , such as C and C++.
Execution Engine: Execution engine contains interpreter and JIT 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.
JAVA DATA TYPES
Java programming language has a rich set of data types. The data type is a category of data stored in
variables. In java, data types are classified into two types and they are as follows.
Primitive Data Types
Non-primitive Data Types
9
Primitive Data Types
The primitive data types are built-in data types and they specify the type of value stored in a variable
and the memory size.
Integer Data Types: Integer Data Types represent integer numbers, i.e numbers without any fractional
parts or decimal points.
Minimum and Maximum
Data Type Memory Size Default Value
values
byte 1 byte -128 to +128 0
Note: Float data type can represent up to 7 digits accurately after decimal point.
Double data type can represent up to 15 digits accurately after decimal point.
Character Data Type: Character data type are represents a single character like a, P, &, *,..etc.
Boolean Data Types: Boolean data types represent any of the two values, true or false. JVM uses 1 bit to
represent a Boolean value internally.
10
Minimum and Maximum
Data Type Memory Size Default Value
values
boolean 1 byte 0 or 1 0 ( false )
VARIABLES: Variable is a name given to a memory location where we can store different values of the
same data type during the program execution.
The following are the rules to specify a variable name...
A variable name may contain letters, digits and underscore symbol
Variable name should not start with digit.
Keywords should not be used as variable names.
Variable name should not contain any special symbols except underscore(_).
Variable name can be of any length but compiler considers only the first 31 characters of the
variable name.
Declaration of Variable
Declaration of a variable tells to the compiler to allocate required amount of memory with specified
variable name and allows only specified datatype values into that memory location.
Syntax: datatype variablename;
Example : int a;
Syntax : data_type variable_name_1, variable_name_2,...;
Example : int a, b;
Initialization of a variable:
Syntax: datatype variablename = value;
Example : int a = 10;
Syntax : data_type variable_name_1=value, variable_name_2 = value;
11
Example : int a = 10, b = 20;
Types of Variables
There are three types of variables in Java:
local variable
instance variable
static variable
Local Variables:
Variables declared inside the methods or constructors or blocks are called as local variables.
The scope of local variables is within that particular method or constructor or block in which
they have been declared.
Local variables are allocated memory when the method or constructor or block in which they
are declared is invoked and memory is released after that particular method or constructor or
block is executed.
Stack memory is allocated for storing local variables.
JVM takes no responsibility for assigning default value to the local variables. It is the
responsibility of the programmer to initialize the local variables explicitly before using them
otherwise syntax error is raised.
Access modifiers cannot be assigned to local variables.
It can’t be defined by a static keyword.
Local variables can be accessed directly with their name.
Program :
public class LocalVariables
{
public void show()
{
int a = 10;
System.out.println("Inside show method, a = " + a);
12
}
public void display()
{
int b = 20;
System.out.println("Inside display method, b = " + b);
//System.out.println("Inside display method, a = " + a); // error
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}
Instance Variables:
Variables declared outside the methods or constructors or blocks but inside the class are called
as instance variables.
The scope of instance variables is inside the class and therefore all methods, constructors and
blocks can access them.
Instance variables are allocated memory during object creation and memory is released during
object destruction. If no object is created, then no memory is allocated.
For each object, a separate copy of instance variable is created.
Heap memory is allocated for storing instance variables.
Access modifiers can be assigned to instance variables.
It is the responsibility of the JVM to assign default value to the instance variables as per the type
of
Variable.
Instance variables can be called directly inside the instance area.
Instance variables cannot be called directly inside the static area and necessarily requires an
object reference for calling them.
Program :
public class ClassVariables
{
int x = 100;
13
public void show()
{
System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display()
{
System.out.println("Inside display method, x = " + x);
}
public static void main(String[] args)
{
ClassVariables obj = new ClassVariables();
obj.show();
obj.display();
}
}
Static variables:
Static variables are also known as class variable.
Static variables are declared with the keyword ‘static ‘ .
Static keyword in java is used for memory management, i.e it saves memory.
Static variable can be used to refer to the common property of all objects.
Static variables gets memory only once in the class area at the time of class loading.
Static variables contain values by default. For integers, the default value is 0. For Booleans, it is
false. And for object references, it is null.
Static variables can be invoked without the need for creating an instance of a class.
These static variables can be accessed in two ways.
1. if a program consist of single class, the static variable can be accessed directly
2. if a program consist of multiple class, the static variable can be accessed with the help of class
name
Syntax: classname.variablename;
Example1 :
class Employee
{
static int empid=500;
14
static void emp1()
{
empid++;
System.out.println("Employee id:"+empid);
}
}
class Sample
{
public static void main(String[] args)
{
Employee.emp1();
Employee.emp1();
Employee.emp1();
}
}
class Employee
{
static int empid;
static String empname;
static double empsal;
public static void main(String[] args)
{
System.out.println(empid);
System.out.println(empname);
System.out.println(empsal);
}
}
Example2 :
class Employee
{
static int empid;
static String empname;
static double empsal;
}
15
class Sample
{
public static void main(String[] args)
{
System.out.println(Employee.empid);
System.out.println(Employee.empname);
System.out.println(Employee.empsal);
}
}
Static method: A static method is declared by using the keyword ‘static’, it is known as static method.
Rules:
A static method can be invoked without the need for creating an instance of a class.
A static method can access only static data members.
The static method cannot use non-static data member or call non-static method directly.
this and super keyword cannot be used in static context.
These static variables can be accessed in two ways.
1. if a program consist of single class, the static variable can be accessed directly
2. if a program consist of multiple class, the static variable can be accessed with the help of class
name
Syntax: classname.methodname;
Example 1:
class Employee
{
static int empid;
static String empname;
static double empsal;
static void empinfo()
16
{
System.out.println("Employee id:"+empid);
System.out.println("Employee Name:"+empname);
System.out.println("Employee Salary:"+empsal);
}
public static void main(String[] args)
{
empinfo();
}
}
Example 2 :
class Employee
{
static int empid;
static String empname;
static double empsal;
static void empinfo()
{
System.out.println("Employee id:"+empid);
System.out.println("Employee Name:"+empname);
System.out.println("Employee Salary:"+empsal);
}
}
class Sample
{
public static void main(String[] args)
{
Employee.empinfo();
}
17
}
OPERATORS: An operator is a symbol that performs an operation. An operator acts on some variables
called operands to get the desired result.
Example: a+b
Here a, b are operands and + is operator.
Types of Operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
18
% Modular
class ArithmeticOperators
{
public static void main(String[] args)
{
int a = 12, b = 5;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
2. Relational Operators: Relational operators are used to compare two values and return a true or false
result based upon that comparison. Relational operators are of 6 types
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
19
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
3. Logical Operator: The Logical operators are used to combine two or more conditions .Logical
operators are of three types
1. Logical AND (&&),
2. Logical OR (||)
3. Logician NOT (!)
1. Logical AND (&&) : Logical AND is denoted by double ampersand characters (&&).it is used to check
the combinations of more than one conditions. if any one condition false the complete condition
becomes false.
Truth table of Logical AND
Condition1 Condition2 Condition1 && Condition2
True True True
True False False
False True False
False False False
20
System.out.println(x!=10 && x>=5));
System.out.println(x>=20 && x<=50));
}
}
2. Logical OR ( || ) : Logical OR is denoted by double pipe characters (||). it is used to check the
combinations of more than one conditions. if any one condition true the complete condition becomes
true.
Truth table of Logical OR
Condition1 Condition2 Condition1 && Condition2
True True True
True False True
False True True
False False False
Example of Logical OR (||) operator :
import java.io.*;
class LogicalOR
{
public static void main(String[] args)
{
int x=10;
System.out.println(x==10 || x>=5));
System.out.println(x>=5 || x<=50));
System.out.println(x!=10 || x>=5));
System.out.println(x>=20 || x<=50));
}
}
3. Logician NOT (!): Logical NOT is denoted by exclamatory characters (!), it is used to check the
opposite result of any given test condition. i.e, it makes a true condition false and false condition true.
Truth table of Logical NOT
Condition1 !Condition2
True False
False True
21
{
public static void main(String[] args)
{
int x=10;
System.out.println ( ! ( x==10 ));
System.out.println (!( x!=10));
System.out.println (!( x>5));
System.out.println ( !( x<5));
}
}
4. Assignment Operator: Assignment operators are used to assign a value (or) an expression (or) a
value of a variable to another variable.
Syntax : variable name=expression (or) value
Example : x=10;
y=20;
The following list of Assignment operators are.
class AssignmentOperator
{
public static void main(String[] args)
{
int a = 4;
22
int var;
var = a;
System.out.println("var using =: " + var);
var += a;
System.out.println("var using +=: " + var);
var *= a;
System.out.println("var using *=: " + var);
}
}
5: Increment And Decrement Operators : The increment and decrement operators are very
useful. ++ and == are called increment and decrement operators used to add or subtract. Both are unary
operators.
The syntax of the operators is given below.
23
int var=5;
System.out.println (var++);
System.out.println (++var);
System.out.println (var--);
System.out.println (--var);
}
}
6 : Conditional Operator: A conditional operator checks the condition and executes the statement
depending on the condition. Conditional operator consists of two symbols.
1 : question mark (?).
2 : colon ( : ).
Syntax: condition ? exp1 : exp2;
It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the condition is false
(zero) then the “exp2” is evaluated.
Example :
class ConditionalOperator
{
public static void main(String[] args)
{
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
7. Bitwise Operators:
Bitwise operators are used for manipulating a data at the bit level, also called as bit level
programming. Bit-level programming mainly consists of 0 and 1.
They are used in numerical Computations to make the calculation process faster.
The bitwise logical operators work on the data bit by bit.
Starting from the least significant bit, i.e. LSB bit which is the rightmost bit, working towards
the MSB (Most Significant Bit) which is the leftmost bit.
24
A list of Bitwise operators as follows…
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
<< Left Shift
>> Right Shift
25
Condition1 Condition2 Condition1 | Condition2
0 0 0
0 1 1
1 0 1
1 1 1
26
The bitwise complement operator is a unary operator.
It is denoted by ~, which is pronounced as tilde.
It changes binary digits 1 to 0 and 0 to 1.
bitwise complement of any integer N is equal to - (N + 1).
Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 + 1) = -
36.
27
Example:
int x = 10;
x >> 2 = ?
28
Ex: public
void
import
Control Statements
In java, the control statements are the statements which will tell us that in which order the
instructions are getting executed. The control statements are used to control the order of execution
according to our requirements.
In java, the control statements are classified as follows.
Selection Control Statements ( Decision Making Statements )
Iterative Control Statements ( Looping Statements )
Jump Statements
Selection Control Statements
In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed based on a
condition. Java provides the following selection statements.
1. if statement
2. if-else statement
3. if-elseif statement
4. nested if statement
5. switch statement
1. if statement : if statement is the simplest decision control statement that is frequently used in
decision making.
The general form of a simple if statement is
29
The if block may include 1 statement or n statements enclosed within curly brackets. First the test
expression is evaluated. If the test expression is true, the statements of the if block are executed,
otherwise these statements will be skipped and the execution will jump to statement x.
Note : In case the statement block contains only one statement, putting curly brackets becomes optional.
If there are more than one statement in the statement block, putting curly brackets becomes mandatory.
Example :
class Sample
{
public static void main(String[] args)
{
int x=10;
if(x>0)
x++;
System.out.println("x value is:"+x);
}
}
2. if–else statement : The if-else statement is an extension of the simple if statement. Its usage is very
simple.
The general form of simple if–else statement is :
30
In the if–else statement, first the test expression is evaluated. If the expression is true, statement block 1
is executed and statement block 2 is skipped. Otherwise, if the expression is false, statement block 2 is
executed and statement block 1 is ignored. In any case after the statement block 1 or 2 gets executed, the
control will pass to statement x. Therefore, statement x is executed in every case.
Example: Write a program to find whether a number is even or odd.
class Sample
{
public static void main(String[] args)
{
int a=29;
if(a % 2==0)
System.out.println("Even Number is :"+a);
else
System.out.println("Odd Number is :"+a);
}
}
3. if–else–if statement : C language supports if–else–if statements to test additional conditions apart
from the initial test expression. The if–else–if construct works in the same way as a normal if statement.
The general form of simple if–else–if statement is :
31
class Test
{
public static void main(String args[])
{
int x = 30;
if( x == 10 )
{
System.out.print("Value of X is 10");
}
else if( x == 20 )
{
System.out.print("Value of X is 20");
}
else if( x == 30 )
{
System.out.print("Value of X is 30");
}
32
else
{
System.out.print("This is else statement");
}
}
}
5. switch–case statement: when there are several options and we have to choose only one option from
the available ones, we can use switch statement. Depending on the selected option, a particular task can
be performed. A task represents one or more statements.
The general form of switch–case statement is :
33
The expression following the keyword switch in any ‘C’ expression that must yield an integer value. It
must be an integer constants like 1,2,3 .
The keyword case is followed by an integer or a character constant, each constant in each must be
different from all the other.
First the integer expression following the keyword switch is evaluated. The value it gives is searched
against the constant values that follow the case statements. When a match is found, the program
executes the statements following the case. If no match is found with any of the case statements, then the
statements following the default are executed.
class SwitchStatementTest
{
public static void main(String[] args)
{
char color ='g';
switch( color )
34
{
case 'r':
System.out.println("RED") ; break ;
case 'g':
System.out.println("GREEN") ; break ;
case 'b':
System.out.println("BLUE") ; break ;
case 'w':
System.out.println("WHITE") ; break ;
default:
System.out.println("No color") ;
}
}
}
Iterative Statements
The java programming language provides a set of iterative statements that are used to execute a
statement or a block of statements repeatedly as long as the given condition is true. The iterative
statements are also known as looping statements or repetitive statements. Java provides the following
iterative statements.
35
1. while statement
2. do-while statement
3. for statement
1.while statement : The while statement is used to execute a single statement or block of statements
repeatedly as long as the given condition is TRUE. The while statement is also known as Entry control
looping statement.
The syntax and execution flow of while statement is as follows.
class WhileTest
{
public static void main(String[] args)
{
int num = 1;
while(num <= 10)
{
System.out.println(num);
num++;
}
System.out.println("Statement after while!");
}
}
2.do-while statement : The do-while statement is used to execute a single statement or block of
statements repeatedly as long as given the condition is TRUE. The do-while statement is also known as
the Exit control looping statement.
The do-while statement has the following syntax.
36
class DoWhileTest
{
public static void main(String[] args)
{
int num = 1;
do
{
System.out.println(num);
num++;
}while(num <= 10);
System.out.println("Statement after do-while!");
}
}
3.for loop statement : The for statement is used to execute a single statement or a block of statements
repeatedly as long as the given condition is TRUE.
The for statement has the following syntax and execution flow diagram.
37
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution,
the modification statement gets executed, followed by condition again.
class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
System.out.println("i = " + i);
}
System.out.println("Statement after for!");
}
}
38
39