Java Unit-1 R&R
Java Unit-1 R&R
INTRODUCTION TO JAVA
History of java :
In 1990, Sun Microsystems Inc. (US) was conceived a project to develop software for
consumer electronic device 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 to 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 device 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.
James Gosling and his team members were consuming a lot of coffee while developing this
language. They felt that they were able to develop a better language because of the good quality
coffee they consumed. So the coffee had its own role in developing this language and good quality
coffee was exported to the entire world from a place called java island .Hence they fixed the name of
the place for the language as Java. And the symbol for Java language is coffee cup and saucer.
By September of 1994, Naughton and Jonathan payne started writing Web Runner (a java
based web browser),which was later renamed as Hot java. By October 1994, Hot java as stable and
was demonstrated to sun Executives. Hot java was the first browser, having the capabilities of
executing applets, which are programs designed to run dynamically on internet. This time , java is
potential in the context of the world wide web was recognized.
Sun formally announced java and Hot java at Sun World conference in 1995.soon
after, Netscape Inc. announced that it would incorporate java support in its browser Netscape
Navigator. Later, Microsoft also announced that they
would support java in their Internet Explorer Web browser; further solidifying java is
role in the World Wide Web. On January 23rd 1996, JDK 1.0 version was released. Today
more than 4 million developers use java and more than 1.75 billion devices run java
FEATURES OF JAVA
1. Simple
2. Object Oriented
3. Distributed
1. Simple: Java is a Simple Programming language. For Example, the concept of Pointers,
which is very difficult for both learners and programmers, has been completely
eliminated from java.
2. Object Oriented: Java is an Object Oriented Programming Language. This means java
programs use objects and classes. An Object is anything that really exists in the world and
can be distinguished from others. A Group of Objects exhibiting same behaviour
(Properties + Actions) will come under same group called a Class.
For Example, Flower is a class but if we take Rose, Lily, Jasmine- they are all
Objects of Flower Class. The class Flower does not exist physically but its objects like
Rose, Lily, Jasmine exists physically.
Java Virtual Machine (JVM) 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 instructions that can be executed by the microprocessor.
First of all the .java program is converted into a .class file consisting of byte code
instructions by the java compiler. In JVM, there is a module (or program) called class loader
sub system, which performs the following functions.
2. Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.
3. If the byte instructions are proper, then it allocate necessary memory to execute the
program.
This memory is divided into 5 parts, called run time data area, which contain the data
and results while running the program. There areas are as follows.
Method Area: Used to store class code, code of variables, and code of the java
program.
Heap Area: This is the place where objects are created. Whenever JVM loads a
class, a method and a heap are immediately created in it.
Java Stack: 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. So, Java stack are memory areas where java methods are executed.
While executing methods, a separate frame will be created in the java stack, where
the method is executed.
Program Counter Registers: These are the registers, which contain memory
address of the instructions of the methods,. If there are 4 methods, 4 PC registers
while be used to track the instructions of the methods.
Native method stacks: Java methods are executed on java stack. Similarly native
methods are executed on native method area.
The execution engine contains interpreter and JIT compiler, which are responsible for
converting the byte code instructions into machine code so that the processor while execute
them. Most of the JVM implementation use both the interpreter and JIT compiler
simultaneously to convert the byte code. This technique is also called adaptive optimizer.
Parts Of Java
1. Java SE
2. Java EE
3. Java ME
1. Java SE: It is the java Standard Edition that contains basic core java classes. This
edition is used to develop standard applets and applications.
2. Java EE: It is the java Enterprise Edition and it contains classes that are beyond java
SE. Java EE mainly concentrates on providing business solutions on a network.
3. Java ME: It stands for java Micro Edition. Java ME is for Developers who develop
code for portable devices.
1. Single line comments: - These comments starts with double slash symbol // and after
this, whatever is written till the end of the line is taken as comment.
For Example,
//This is Comment of one line
2. Multi line Comments:- These comments are used for representing several lines as
comments. These comments starts with /* and end with */.
For Example,
API document
The API document generated from the .java program is similar to a help file where all
features are available with their descriptions. The user can refer to any feature in this file
and get some knowledge regarding how he can use it in his program.
Before we start writing our first java program, let us see how a java program looks like,
import java.lang.System;
import java.lang.String;
import java.lang.*;
class First
{
{
System.out.println(“Welcome to Java”);
}
}
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, 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 into
our program.
After importing the classes into the program, the next step is to write a class. Since
java is purely an object oriented programming language, 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.
class {
statement;
A Code starts with { and }. We know that a class contains variables and methods. So we
create any number variables and methods inside the class. So we create only one method that
is compulsory in it i.e. main () method
Because, if main () method is not written in a java program, JVM will not execute it. main
() is the starting point for JVM to start execution of a Java Program.
Here, args[] is an array name and it is of String type. This means that it can store a group of
strings. The values passed to main() method are called arguments. These arguments are
stored into args[] array.
A method can return some results. If we want the method to return the results in form of an
integer, then we should write int before method name. If a method is not meant to return any
value , then we should write void before the method name. void means no value. main()
method does not return any value so void should be written before main() method.
A method is executed only when it is called. Methods are called using two steps in java,
Ex:
class First
{
public static void main (String args[])
{
First obj=new First(); //object is created
}
}
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 JVM calls main() method using its class name
as First.main() at time of running the program.
If at all we want to make any changes, we can interchange public and static as,
We can use a different name for the string type array and write as,
import java.lang.*;
class First
{
public static void main (String args[])
{
Statements ; //executed by JVM
}
}
A Unit Of Krishna Chaitanya Group Of Institutions phani
22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
Here, System is the class name and out is a static variable in System class. So we call
print() method as
System.out.print(“Welcome To Java”);
Save the above program in text editor like Notepad with the name First.java . Now,
go to System prompt i.e. C:\> and compile it using javac compiler as,
C:\> javac First.java
The compiler generates a file called First.class that contains byte code instructions.
This file is executed by calling JVM as,
C:\> java Fisrt
Then we get the results Welcome To Java
import java.lang.*;
class Sum
{
public static void main (String args[])
{
int x,y;
x=10;
y=25;
int z=x+y;
System.out.print(z);
}
}
Output:
35
Note : Formatting output means we will generate output with different formats
i.e. naturally in the above program the result is 35. If we want to display result with some
other special format i.e. “ The sum of two numbers= 35 “.., we should write it in the print
statement.. i.e.
A Package represents a sub directory that contains a group of classes and interfaces.
Names of packages in java are written in small letters as,
java.awt
java.io
javax.swing
A Class is a model for creating objects. A Class specifies the properties and actions of
objects. An Interface is also similar to a class. Each word of class names and
interface names start with a capital letter as,
A Class and an interface contain methods and variables. The first word of method
name is in small letters; then from second word onwards , each new word starts with
capital letter as,
println()
readLine()
getNumberInstance()
The naming conventions for variables names is same as that for methods as,
age
empName
employee_Net_Sal
Constants represent fixed values that cannot be altered. For Example, PI is a constant
whose value is 22/7 or 3.14159, which is fixed, such constants should be written by
all capital letters as,
PI
MAX_VALUE
Font.BOLD
Here, BOLD is a constant in Font class.
Data types are the domains which determain what type of contents can be stored in a
variable.
The variables are used to store data. Internally, a variable represents a memory
location which holds data. When we want to use a variable in a program, we should first
declare it as,
int x;
Here, we declare x is a variable, which can store int (integer) type data. This means int is
representing the nature of data to be stored into x. int is also called a data type.
For example, x can store an integer like 125 as,
x= 125;
data types are two types
1.Primitive data types
2Reference data types
DATA TYPES
Integer data types are used to represent integer values. For Example, 125, - 225678 , 0,
1022 , etc. Integer data types are again sub divided into byte, short, int, and long.
For Example,
byte rno=10;
In the above example, byte is a data type for the variable rno which stores the value 10.
long x=150L;
Here, 150 is stored into x, which is declared as long type, L at the end of the statement. If L is
not there , then JVM allots only 2 bytes of memory to x as against usual 8 bytes memory that
should be allotted to a long type.
Float data types are used to represent numbers with decimal point. For Example, 3.14,
0.0012,-123.11, etc. is called Floating point Numbers. These are again classified as float
Character data type is used to represent single character like a, P, &, *,.. , etc.
Here, String type variable str contains “New Delhi”. Note that any string written directly in
a program should be enclosed by using double quotes.
Boolean data type represents any of the two values- true or false. JVM uses 1 bit to
represents a Boolean value internally,
For Example,
LITERALS
A Literal represents a value that is stored into a variable directly in the program.
Ex:
Boolean result= false;
A Unit Of Krishna Chaitanya Group Of Institutions phani
22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
char gender=’m’;
short s=10000;
int i=-1256;
In the above example, the right side values are called literals because these values are being
stored into variable at left hand side.
There are different types of literals in java,
Integer Literals
Float Literals
Character Literals
String Literals
Boolean Literals
Binary Literals
Integer Literals :-
Integer Literals represent the fixed integer values like 100,-55 ,123450, etc. All these
number belong to decimal system, which uses 10 digits (from 0 to 9) to represent any
number. Suppose we want to write an integer in octal number system (octal number system
uses 8 digits, from 0 to 7), then we should prefix 0 before the number. To represent
hexadecimal number (hexadecimal number system uses 16 digits from 0 to 9 and from A to
F), we should prefix 0x before the value.
Ex:-
int decVal=26;
int octVal=032;
int hexVal=0x1A;
Float Literals :-
Float Literals represent fractional numbers. There are the numbers with decimal
points like 2.0, -0.005, 3.14, 6.1e-22 etc. which should be used with float or double type
variables. While writing these literals, we can use E or e for scientific notation, F or f for
float literal, and D or d for double literal.
Ex:
double d1=123.4;
double d2=1.234e2; // same value as d1, but in scientific notation
float f1= 123.4f;
Character Literals :-
Character Literals indicate the following:
General characters like A, b, 9, etc.
Special Characters like ? , @ , etc.
String Literals :-
String Literals represent objects of string class. For Example, Hello, Krishna Chaitanya,
AP1201, etc. will come under string literal, which can be directly stored into a String
object.
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.
Binary Literals :-
A Binary Literal can be represented with a prefix ob or OB, and represents a number
in binary number system, as:
OPERATORS IN JAVA
Operators:
Arithmetic Operators :-
Arithmetic Operators are used to perform fundamental arithmetic operations like
addition, subtraction, etc. there are five arithmetic operators in java. Since these operators act
on two operands at a time, so these are called binary operators.
Ex:-
If a=13 and b=5 then
Unary Operators :-
As the name indicates, unary operators act on only one operand. There are three kinds
of unary operators,
Unary minus Operator
Increment Operator
Decrement Operator
Unary minus Operator :- This operator is used to negate a given value. Negation means
converting a negative value into positive and vice versa,
Ex:
int x=5;
System.out.println(-x); //will display -5
System.out.println(-(-x)); //will display 5
Here, the value of variable x is incremented by 1 when ++ operator is used before and after
it.
++ Operator before a variable is called pre increment, ++ operator after a variable is
called post increment. In Pre Increment, Incrementation is done first and any operation is
done next. In Post Increment, All other operations are done first and Incrementation is done
only at the end.
Output: Output:
1 1
2 1
2 2
Here, the value of variable x is decremented by 1 when -- operator is used before and after it.
-- Operator before a variable is called pre decrement; -- operator after a variable is
called post decrement. In Pre decrement, decrementation is done first and any operation is
done next. In Post decrement, all other operations are done first and decrementation is done
only at the end.
Assignment Operator :-
This operator is used to store some value into a variable. It is used in three ways,
It is used to store a value into a variable, for example, int x=5;
It is used to store the value of a variable into another variable, for example:
int x=y; // here the value of y is stored into x
Relational Operator :-
Relational Operators are used to compare two variables. Relational operators are of
six types,
Logical Operators :-
Ex:
if ( a==1 || b==1 || c==1) System.out.println(“Yes”);
Here, there are three conditions, a==1, b==1, c==1 which are combined by || (Logical OR
Operator). In this case, if either of the a or b or c equal to 1, Yes will be displayed.
Here, there are two conditions, x>y and y<z. Since they are combined by using &&
(Logical AND Operator). If both the conditions are true , then only Hello is displayed.
Here, str1, str2 are two string objects, which are being compared. ! (NOT Operator)
and equals () method tells that if str1 is not equal to str2, then only Not Equal will be
displayed.
Boolean Operator :-
The Boolean Operator act on Boolean variables and produce Boolean type results.
The following three are Boolean operators,
& Boolean AND Operator
| Boolean OR Operator
! Boolean NOT Operator
Boolean & Operator returns true if both the variables are true. Boolean | Operator returns
true, if any one of variables is true. Boolean ! Operator converts true to false and vice
versa.
Ex:
Boolean a, b; //declare two Boolean type variables
a = true; //store Boolean value true into a
b= false; // store Boolean value false into b
a & b; //return false
a | b; //return true
a & a; //return true
b | b; //return false
!a //return false
!b //return true
Bitwise Operators :-
There are seven bitwise operators in java. These operators act on individual bits (0
and 1) of the operands. They act on only integer data types.
Bitwise Complement Operator ( ~):
This operator gives the complement form of a given number. This operator symbol is
~, which is pronounced as tilde. Complement form of positive number can be
obtained by changing 0’s as 1’s and vice versa.
if int x=10
x=10=0000 1010
By Changing 0’s as 1’s as 1111 0101
This is nothing but -11 (in decimal)
Bitwise OR Operator :-
This operator performs OR operation on the bits of the numbers. The symbol is |,
which is called pipe symbol.
This Operator is called ternary, because it acts on 3 variables. The other name for
this operator is conditional Operator, since it represents conditional statements. Two
Symbols are used for this operator ? and :
Syntax:
Variable=expression1? expression2: expression 3;
In the above syntax, first, expression1 is evaluated. If it is true then expression2 value is
stored into variable. If expression1 is false, then expression 3 value is stored into variable.
if (expression1 is true)
variable= expression2;
else
variable= expression3;
Ex:
max= (a>b) ? a : b ;
Here, (a>b) is evaluated first. If it is true then value of a is stored into variable max else the
value of b is stored into variable max.
We know that each class contains variables or methods. To refer to the variables of
class, we can use this operator.
Syntax:
classname.variablename;
Or
Objectname.variablename;
Ex:
System.out // out is static variable in System class
emp.id // id is variable in Employee class
// emp is Employee class object
We know that each class contains methods. To refer to the method of class, we can
use this operator.
Syntax:
classname.methodname;
Or
objectname.methodname;
Ex:
Math.sqrt( ) // sqrt() is a method in Math class
br.read() // read() is a method in BufferReader class
// br is an object of BufferReader class
instanceof Operator :-
This operator is used to test if an object belongs to a class or not. The word instance
means object. This operator can also used to check if an object belongs an interface or not.
Syntax:
boolean variable= object instanceof class;
boolean variable= object instanceof interface;
Ex:
boolean x= emp instanceof Employee;
new Operator :-
new Operator is often used to create objects to classes. We know that objects are
created on heap memory by JVM , dynamically( at run time).
Syntax:
Classname obj=new Classname( );
Ex:
Employee emp=new Employee( );
Here, emp is an object of Employee class
Cast Operator :-
Cast Operator is used to convert one data type into another data type. This operator
can be used by writing data type inside simple braces.
Ex:
double x=10.54;
int y = x; //Error, because data types of x and y are different
To store x value into y , we have to first convert the data type of x into data type of y. It
means double data type can be converted into int data type by writing int inside the simple
braces. This is called Cast Operator.
double x=10.54;
int y = (int) x;
Here, x data type is converted into int type and then stored into y.
A Java statement is the smallest unit that is a complete instruction in itself. Statements
in java generally contain expression and end with semi colon. The two most commonly used
statements in any programming language are as follows,
Sequential Statements: These are the statements which are executed one by one.
Control statements: These are the statements that are executed randomly and
repeatedly.
These are followed by java also.
System.out.println(“Hello”);
x= y + z;
System.out.println(“x”);
These statements are executed by JVM one by one in a sequential manner. So they
are called Sequential Statements. But this type of sequential execution is useful only to
write simple programs. If we want to write better and complex programs, we need better
control on the flow of execution. This is possible by using control statements.
Control statements are the statements which alter the flow of execution and provide better
control to the programmer on the flow of execution.
if ...else statement
do..while loop
while loop
for loop
for-each loop
switch statement
break statement
continue statement
return statement
if ...else statement:-
This statement is used to perform a task depending on whether a given condition is
true or false. Here, task, represents a single statement or group of statements.
Syntax:
if (condition)
statements 1;
else
statements 2;
Output:
C: \> javac Demo.java
C: \> java Demo
-5 is Negative
if( condition)
statements 1;
else if( condition)
statements 2;
else if( condition)
statements 3;
else
statements 4;
if(condition1)
{
if(condition2)
{
if(condition3)
{
statements 1;
}
else
statements 2;
}
else
Statements 3;
}
else
statements 4;
do....while Loop:-
do{
System.out.println(x);
x++;
}while(x<=10);
}
}
Output:
C: \> javac Demo.java
C: \> java Demo
1
2
3
4
5
6
7
8
9
10
while Loop :-
While loop is similar to do....while loop. This loop repeats a group of statements as
long as condition is true. Once the condition is false , the loop is terminated.
Syntax:
while( condition)
{
Statements;
}
In do...while loop ,the statements are executed first and then condition is tested. On the
other hand, while loop, the condition is tested first, if it is true then only statements are
executed.
Ex:
//To display numbers from 1 to 10
class Demo
{
public static void main(String args[])
{
int x;
x=1;
Output:
C: \> javac Demo.java
C: \> java Demo
1
2
3
4
5
6
7
8
9
10
for Loop:-
The for loop is same as do...while loop or while loop , but it is more compact
syntactically. The for loop executes a group statements as long as condition is true.
Syntax:
for( expression1; expression 2; expression 3)
{
Statements;
}
Ex:
//To display numbers from 1 to 10
class Demo
{
public static void main(String args[])
{
for( int x=1; x<=10; x++)
{
System.out.println(x);
}
}
}
Output:
C: \> javac Demo.java
C: \> java Demo
1
2
3
We can write for loop without expression1 or expression2 or expression3 or any two
expressions and still we get same results.
int x=1;
for( ; x<=10; x++)
{
System.out.println(x);
}
int x=1;
for( ; x<=10; )
{
System.out.println(x);
x++;
}
int x=1;
for( ; ; )
{
System.out.println(x);
x ++;
}
Here, there is no condition in the loop that tells where to stop. So above code, executes
without stoppage. It is called Infinite loop.
If a programmer got an infinite loop, he should break it when the condition is reached. For
this situation, break statement is used as ,
Ex:
//To display numbers from 1 to 10
class Demo
{
public static void main(String args[])
{
int x=1;
for( ; ; )
{
System.out.println(x);
x++;
if( x > 10) break;
}
}
}
Output:
C: \> javac Demo.java
C: \> java Demo
1
2
3
4
5
6
7
8
9
10
class Stars
{
public static void main(String args[])
{
int r=5;
Output:
C: \> javac Stars.java
C: \> java Stars
*
* *
* * *
* * * *
* * * * *
for –each loop repeatedly executes a group of statements for each element of
collection. It executes as many times as there are number of elements in the collection .
Syntax:
for ( var : collection)
{
Statements;
}
Here, var is attached to collection. This var represents each element of the collection one by
one.
Ex:
// Using for-each loop – to display array elements
class Demo
{
public static void main(String args[])
{
int arr[ ]={200, 19, -56, 44, 99};
for( int i : arr)
{
System.out.println(i );
}
}
}
Output:
C: \> javac Demo.java
C: \> java Demo
200
19
Switch 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 selected option, a particular task
can be performed. A task represents one or more statements.
Syntax:
switch (variable)
....
....
Here, depending on the value of variable, a particular task will be executed. If the variable
value is equal to value 1 ., then the statement one will be executed. if the variable value is
value 2 then the statement 2 will be executed..,and so on.If none of the statement will be
executed … in that case the default clause is executed
class Demo
switch (color)
Output :
red
green
blue
yellow
no color
we have to understand that we will not use break statement here .so it will display all colors
one by one.
Break Statement :-
switch (color)
break ;
break ;
break ;
break ;
Output :
Green
Continue statement :- Continue is used inside the loop to repeat the next iteration of the
loop. When continue is executed , subsequent statements in the loop are not executed and
control of the execution is goes back to the next repetition of the loop.
A Unit Of Krishna Chaitanya Group Of Institutions phani
22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
Syn : Continue;
{ if (I >5) continue ;
System.out.print(i+” “);
A method is executed when called from another method. The first method executed in java by
JVM is main( ) method and hence if we want to execute any other method ,we should call it
from main( ).
Return statement is used in a method to come out of it to the calling method. For example if
we call method xyz( ) from the main ( ) method, if return is used in the xyz ( ) method
….then the flow of execution comes out of it and goes back to main ( ) method. For this
purpose return should be used in java.
Ex.
Class Demo
{ int x=1;
System.out.println(“before return”
If (x==1) return;
System.out.println(“after return”);
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 a flow of data
from one place to another place. It islike a water pipe,where water flows likewise a stream
carries data from one place to another place. i.e.,from keyboard to memory or from
memory to printer or from memory to a file. So, a stream is required if we want to move
data from one place to another place.
All streams are represented by classes in java IO package. This package contains several
classes. All which can be classified into two basic categories i.e., input streams and output
streams and output streams keyboard is represented by a field called in 'System' class.
When we write System.in means we are representing a standard input device keyboard by
default. 'System' class is found in 'java.lang' package and this class has three fields.
1. System.in
2. System.out
3. System.err
1. System.in:-
This represents print stream object, which by default represents standard input device i.e.,
keyboard.
2. System.out:-
This represents print stream object which by default represents output device i.e., moniter.
3. System.err:-
This field also represents print stream object, which by default represents moniter.
NOTE:-
Both System.out and System.err represents the moniter but System.out is used to display
normal messages and result. Whereas, System.err display error messages.
STEP-1:-To accept a single character from the keyboard. Create a BufferedReader class
object i.e., 'br' and then read a single character from the keyboard we will use 'read()'
method.
EX:- char ch=br.read();
here, read() method reads a single character from the keyboard. But it returns ASCII number
which is an integer. Since, this integer cannot be stored into character type variable 'ch'. So,
we have to convert it into char type by using '(char)' typecasting before the method.
char ch=(char) br.read();
write a program to accept and display the employee detailswhich includes employee
id,gender,name.
import java.io.*;
class EmpData
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
System.out.println("enter name =");
String str=br.readLine();
System.out.println("enter gender =");
char gender=(char) br.read();
System.out.println("enter id =");
int id=Integer.parseInt(br.readLine());
System.out.println("name="+name+"gender="+gender+"id="+id);
}
}