0% found this document useful (0 votes)
10 views

Java Unit-1 R&R

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java Unit-1 R&R

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Krishna chaitanya Krishna chaitanya

Krishna chaitanya Krishna chaitanya


Krishna chaitanya Krishna chaitanya
Krishna chaitanya Krishna chaitanya
Krishna chaitanya Krishna chaitanya
Krishna chaitanya Krishna chaitanya
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTUR

Krishna chaitanya Krishna chaitanya


OBJECT ORIENTED PROGRAMMING USING JAVA

Krishna chaitanya Krishna chaitanya


By
phani

Krishna chaitanya Krishna chaitanya


Krishna chaitanya Krishna chaitanya
Krishna chaitanya Krishna chaitanya
Krishna chaitanya Krishna chaitanya
Krishna chaitanya Krishna chaitanya
Krishna chaitanya Krishna chaitanya
22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

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.

Why the name 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

The following are some important features of Java Programming Language:

1. Simple
2. Object Oriented
3. Distributed

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
4. Robust
5. Secure
6. System Independence
7. Portability
8. Interpreted
9. High Performance
10. Multi Threaded
11. Scalability
12. Dynamic

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.

3. Distributed: Information is distributed on various computers on a network. Using Java,


we can write programs, which capture information and distribute it to the clients.
4. Robust: Robust means Strong. Java Programs are strong and they don’t crash easily like
C or C++ Programs. There are two reasons for java is Strong. First one is, java has got
excellent inbuilt exception handling features. Another one is, java Supports Memory
Management Feature.
5. Secure: Security problems like eavesdropping, tampering, impersonation, and virus
threats can be eliminated or minimized by using java or internet.
6. System Independence: Java byte code (.class file) is not a machine dependent. It can be
run on any machine with any processor and any operating system.
7. Portability: If the program can give same result on every machine, then that program is
called portable. Java programs are portable. This is the result of Java System
independence nature.
8. Interpreted: Java programs are compiling to generate the byte code This byte code can
be downloaded and interpreted by the interpreter in JVM (Java virtual machine). If we
take any other language, only an interpreter or a compiler are used to execute the program
9. High Performance: The problem with interpreter inside the JVM is that it is slow. Java
programs used to run slow. To overcome this problem along with the interpreter, Java
Soft people have introduced JIT (Just In Time) Compiler. Which enhance the speed of
execution.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
10. Multi Threaded: A Thread represents an individual process to execute a group of
statements. JVM uses several threads to executed different blocks of code. Creating
multiple threads is called Multi Threaded.
11. Scalability: Java platform can be implemented on a wide range of computers with
varying levels of resources-from embedded devices to mainframe computers. This is
possible because Java is compact and platform independent.
12. Dynamic: Before development of Java, static Text used to be displayed in the browser.
But when James Gosling demonstrated an animated atomic molecule where the rays are
moving the stretching, viewers were dumb struck.
Java Virtual Machine (JVM)

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.

1. First of all, it loads the .class file into memory.

2. Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

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

Sun Micro system Inc. Has divided java into 3 parts,

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.

FIRST STEP TOWARDS JAVA PROGRAMMING

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

If a program is understandable, then only can it be usable in software. If other


members of software development team cannot understand our program, then they may not
be able to use it in the project and will reject it. So writing comments is compulsory in any
program.

There are three types of comments in java,


1. Single line comments
2. Multi line comments
3. Java Documentation comments

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,

/* This is a multi line comment. This is line one.


This is line two of the comment.
This is line three of the comment. */
3. Java Documentation Comments: These comments start with /** and end with */. These
comments are used to provide description for every feature in a java program. This
description proves helpful in the creation of an .html file called API document.
/** description about a class */
Class Code

/** description about a method */


Method code

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.

To create an API Document, we should use a special compiler called javadoc


compiler.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

STARTING A JAVA PROGRAM

Before we start writing our first java program, let us see how a java program looks like,

/* this is my first java program


To display a message.
*/

import java.lang.System;
import java.lang.String;

import java.lang.*;
class First
{

Public static void main (String args [ ]) //

{
System.out.println(“Welcome to Java”);
}
}

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
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, 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.

public static void main(String args[])

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,

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
1. Create an object to the class to which the method belongs. The syntax of creating an
object is,
ClassName objectName=new ClassName();
2. Then the method should be called using the objectname.methodname().

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.

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 does not make itself
available to JVM and JVM cannot execute it.

So, main() method should always be written as ,

public static void main(String args[])

If at all we want to make any changes, we can interchange public and static as,

static public void main(String args[ ] )

We can use a different name for the string type array and write as,

static public void main(String x[ ] )

/* this is my first java program


To display a message.
*/

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

To display a String “Welcome To Java” , In Java, print() is used to display something on


the monitor.
print(“Welcome To Java”);
A method should be called by using objectname.methodname() So call print() method as
follows,
PrintStream obj.print(“Welcome To Java”);

But it is not possible to create object to PrintStream class directly an alternative is


System.out

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

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
Program 2:

//To find Sum of Two Numbers

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:

C:\> javac Sum.java

C:\> java Sum

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.

system.out.print (“the sum of two numbers =” + z);

NAMING CONVENTIONS AND DATA TYPES

Naming Conventions in Java:

Naming conventions specify the rules to be followed by a Java programmer while


writing the names of packages, classes, methods, etc. Some of the major naming conventions
to be followed in Java,

 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 Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
String
DataInputStream
ActionListener

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

 All Keywords should be written by using small letters.


public
void
static

DATA TYPES IN JAVA

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

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

PRIMITIVE DATA TYPES REFERENCE DATA TYPES

ARRAY CLASS INTERFACE

NUMARIC DATA TYPES NON NUMARIC DATA TYUPES

INTEGER FLOAT CHAR BOOLEAN

1. Primitive data types :

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

Data Type Memory Size Minimum and Maximum Values


Byte 1 bytes -27 to 27 -1
(-128 to 127)
Short 2 bytes -215 to 215 -1
(-32768 to 32767)
Int 4 bytes -231 to 231 -1
(-2147483648 to 2147483647)
Long 8 bytes -263 to 263 -1

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

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

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
(Sing precision floating point number) and double (Double precision floating point
number).

Data Type Memory Size Minimum and Maximum Values


float 4 bytes -3.4e38 to -1.4e-45 for negative values
And 1.4e-45 to 3.4e38 for positive values

double 8 bytes -1.8e308 to -4.9e-324 for negative values


And 4.9e-324 to 1.8e308 for positive values

Character Data Type :-

Character data type is used to represent single character like a, P, &, *,.. , etc.

Data Type Memory Size Minimum and Maximum Values

char 2 bytes 0 to 65535

String Data Type :-


A String represents a group of characters, like New Delhi, AP123, Krishna
Chaitanya,. Etc. The simplest way to create a String is by storing group of characters into a
String type variable as,

String str= “Krishna Chaitanya”;

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

Boolean data type represents any of the two values- true or false. JVM uses 1 bit to
represents a Boolean value internally,

For Example,

boolean response= true;

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.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
 Unicode characters like \u0042
 Escape sequence (backslash codes) like \n, \b, etc.
Character literal should be enclosed in single quotation marks. The preceding Unicode
characters and escape sequence can also be represented as Strings.

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:

int num=ob1101; //this is a binary value


short num=(short) ob1101; //binary value is converted into short

OPERATORS IN JAVA

Operators:

An Operator is a symbol that performs an Operation. An Operator acts on some


variables, called Operands to get the desired results.

If an Operator acts on a single variable, called unary operator, if it acts on two


variables called binary Orator; and if it acts on three variables, then it is called ternary
operator.

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

Operator Meaning Example Result

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
+ Addition Operator a+b 18
- Subtraction Operator a-b 8
* Multiplication Operator a*b 65
/ Division Operator a/b 2
% Modulo Division Operator a%b 3

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

Increment Operator :- This Operator increases the value of a variable by1,


Ex:
int x=1;
++x will make x=2
x++ now x=3

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.

Pre Increment Post Increment


int x=1; int x=1;
System.out.println(x); System.out.println(x);
System.out.println(++x); System.out.println(x++);
System.out.println(x); System.out.println(x);

Output: Output:
1 1
2 1
2 2

Decrement Operator :- This Operator decreases the value of a variable by1,


Ex:
int x=1;
--x will make x=0
x-- Now x=-1

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

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

 It is used to store the value of an expression into a variable, for example


int x=y+z-4;
Here the expression y+z-4 is evaluated and its results is
stored into x

Relational Operator :-
Relational Operators are used to compare two variables. Relational operators are of
six types,

 > greater than operator


 >= greater than or equal to operator
 < Less than operator
 <= Less than or equal to operator
 == equal to Operator
 != not equal to Operator

The main use of relational operators is in the construction of conditions in statements,


like
if(condition_is_true) statement to be executed.
For Example,
if(a>b) System.out.println(a);
if(a ==100) System.out.println(“a value is equal to 100”);
In the above two examples, a>b and a==100 are conditions. If they are true, then the
corresponding statements will be executed.

Logical Operators :-

Logical Operators are used to construct compound conditions. A compound condition


is a combination of several simple conditions. Logical operators are of three types,

 && Logical AND operator


 || Logical OR Operator
 ! Logical NOT Operator

Ex:
if ( a==1 || b==1 || c==1) System.out.println(“Yes”);

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

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.

if( x>y && y<z) System.out.println(“Hello”);

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.

if (!(str1.equals(str2)) ) System.out.println(“Not equal”);

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)

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
So, ~x=-11
 Bitwise AND Operator (&):-
This operator performs AND operation on individual bits of numbers. The symbol for
this operator is &, which is called ampersand.

 Bitwise OR Operator :-
This operator performs OR operation on the bits of the numbers. The symbol is |,
which is called pipe symbol.

 Bitwise XOR Operator (^) :-


This operator performs exclusive OR (XOR) operation on the bits of the numbers.
The symbol is ^, which is called cap, carat, circumflex symbol.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

 Bitwise Left Shift Operator (<<) :-


This operator shifts the bits of the number towards left a specified number of
positions. The symbol for this operator is <<, read as Double Less than. If x << n, it
means shifts the bits of x towards left n positions.
Ex:
If int x=10, x<<2
Shifting the value of x towards left 2 positions will make the leftmost 2
bits to be lost.
The value of x= 0000 1010
Now, x <<2 will be 0010 1000=40 (in decimal)

 Bitwise Right Shift Operator (>>) :-


This Operator shifts the bits of the number towards right a specified number of
positions. The symbol for this operator is >>, read as double greater than. If x>>n, it
means To shift the bits of x towards right n positions.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

 Bitwise Zero Fill Right Shift Operator (>>>) :-


This operator also shifts the bits of number towards right a specified number of
positions. But it stores 0 in the sign bit. The symbol for this operator is >>>, read as
triple greater than. Since it always fills 0 in the sign bit, it is called Zero Fill Right
Shift Operator. If we apply >>> on a positive number, it gives same output as that of
>>. But in case of negative numbers , the output will be positive. Since the sign
bit is replaced by 0.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

Ternary Operator (or) Conditional Operator (? :) :-

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;

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

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.

Member Operator (.) :-


Member operator is also called as dot Operator. This operator tells about member of
package or a class. It is used in three ways,
 We know package contains classes. We can use . operator to refer the class of a
package.
Syntax:
packagename.classname;
Ex:
java.io.BufferReader;
Here, BufferReader is a class in java.io package.

 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;

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
Here, we are testing if emp is an object of Employee class or not. if emp is an object of
Employee class, then true will be returned into x, otherwise x will contain false.

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.

CONTROL STATEMENTS IN JAVA

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.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
The following control statements are available in Java,

 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;

In the above syntax, if condition is true then statement 1 is executed otherwise


statements 2 is executed.

// To test if a number is Positive or Negative


class Demo
{
Public static void main (String args[])
{
int num= -5;
if (num == 0)
System.out.println(“It is Zero”);
else if(num >0)
System.out.println(num +”is Positive”);
else
System.out.println(num +”is Negative”);
}
}

Output:
C: \> javac Demo.java
C: \> java Demo
-5 is Negative

if ....else statement can be written in the following different variations as,

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

if( condition)
statements 1;
else if( condition)
statements 2;
else if( condition)
statements 3;
else
statements 4;

In the above syntax, if condition1 is true, then statements 1 is executed. If condition1 is


false then condition 2 is tested, if condition 2 is true, then statements 2 is executed,
otherwise condition 3 is tested, if it is true then statements 3 is executed, if it is false then
statements 4 is executed.

if(condition1)
{
if(condition2)
{
if(condition3)
{
statements 1;
}
else
statements 2;
}
else
Statements 3;
}
else
statements 4;

Here, if condition1 is true, then condition2 is tested. If Condition2 is true, then


condition3 is tested. If Condition3 is true, then statements 1 is executed, If Condition3 is
false, then statements 2 is executed, If Condition2 is false, then statements 3 is executed, If
Condition1 is false, then statements 4 is executed.

do....while Loop:-

do....while Loop is used when there is a need to repeatedly execute a group of


statements as long as condition is true. If condition is false, the repetition will be stopped and
flow of execution comes out of do..while loop.
Syntax:
do {
statements;
}while(condition);

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
In the above syntax, First loop will execute once, and condition is tested, if loop will execute
until condition is false.
//To display numbers from 1 to 10
class Demo
{
public static void main(String args[])
{
int x;
x=1;

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;

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
while(x<=10)
{
System.out.println(x);
x++;
}
}
}

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

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
4
5
6
7
8
9
10

We can write for loop without expression1 or expression2 or expression3 or any two
expressions and still we get same results.

for loop without expression1,

int x=1;
for( ; x<=10; x++)
{
System.out.println(x);
}

for loop without,

int x=1;
for( ; x<=10; )
{
System.out.println(x);
x++;
}

for loop without expression1, expression2 and expression3

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 ,

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1

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

Nested for Loop:


We can write a for loop with in another for loop , such loops are called Nested for
loops.

//To display stars in right angled triangle form

class Stars
{
public static void main(String args[])
{
int r=5;

for( int i=1; i <=r ; i++ )


{
for( int st=1 ; st <=i ; st++ )

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
{
System.out.print(“*”);
}
System.out.println( );
}
}
}

Output:
C: \> javac Stars.java
C: \> java Stars
*
* *
* * *
* * * *
* * * * *

for - each loop :-


This loop is specially designed to handle the elements of collection. Collection
represents group of elements. For Example, we can take an array as a collection.

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

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
-56
44
99

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)

case value1 : statements1;

case value2 : statements2;

case value3 : statements3;

....

....

case valuen : statementsn;

[default : default statements;]

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

Consider the example :

class Demo

public static void main (String args[ ] )

char color = ‘g’; // color is set to g

switch (color)

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
{

case ‘r’ : System.out.println ( “red”);

case ‘g’ : System.out.println ( “green”);

case ‘b’ : System.out.println ( “blue”);

case ‘y’ : System.out.println ( “yellow”);

default : System.out.println ( “no color”);

Output :

C:\> javac Demo.java

C:\> java Demo

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

The break statement can be used in three ways.

 Break is used inside a loop to come out of it.


 Break is used inside the switch block to come out of the switch block
 Break can be used in nested clocks to go to the end of a block. nested block is
nothing but the block in side the block

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
class Demo

public static void main (String args[ ] )

char color = ‘g’; // color is set to g

switch (color)

case ‘r’ : System.out.println ( “red”);

break ;

case ‘g’ : System.out.println ( “green”);

break ;

case ‘b’ : System.out.println ( “blue”);

break ;

case ‘y’ : System.out.println ( “yellow”);

break ;

default : System.out.println ( “no color”);

Output :

C:\> javac Demo.java

C:\> java Demo

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;

Ex : for (int i=10; i>=1;i++)

{ if (I >5) continue ;

System.out.print(i+” “);

Return Statement :- Naturally a method is useful to perform certain calculation or


processing of data in the program to yield expected results. methods can accept the data from
outside for their processing and generate the result.

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

{ public static void main(String orgs[ ])

{ int x=1;

System.out.println(“before return”

If (x==1) return;

System.out.println(“after return”);

C:\> javac demo.java

C:\> java demo

Out put is……….before return.

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
INPUT AND OUTPUT

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.

To accept data from the keyboard i.e., System.in we need to connect it to an


input stream is needed to read the data. So, we have to connect to the keyboard to an input
stream object. Here, we canuse InputStreamReader that can read data from the keyboard.

Syntax:- InputStreamReader obj=new InputStreamReader(System.in);

Then connect InputStreamReader to BufferedReader which is an another input type stream

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
because there are so many methods available in BufferedReader to read the data properly.

Syntax:-BufferedReader br=new BufferedReader(obj);


when we merge above two syntax's and rewritten in a single statement is
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

ACCEPTING A SINGLE CHARACTER FROM THE KEYBOARD

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 dispay character fom the keyboard.


import java.lang.*;
class Accept
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
char ch=(char) br.read();
System.out.println("entered value is ="+ch);
}
}

write a program to accept a name from the keyboard


import java.lang.*;
class Name
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
String str=br.read();
System.out.println("entered value is ="+str);
}
}

ACCEPTING AN INTEGER VALUE FROM KEYBOARD:-


First we should accept the integer number from the keyboard as a string using readLine()
i.e.,

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
String str=br.readLine();
now the number is in 'str' in the form of string. This should be converted in to integer by
using parseInt() of integer class i.e.,
int N=Integer.parseInt(str);
if we want to write the above two statements in a single line is as follows
int n=Integer.parseInt(br.readLine());

write a program to accept the integer from the keyboard


import java.lang.*;
class Number
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
int n=Integer.parseInt(br.readLine());
System.out.println("entered number is ="+n);
}
}

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);
}
}

write a program to print fabinocci series


import java.io.*;
class EmpData
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));

A Unit Of Krishna Chaitanya Group Of Institutions phani


22 R-AC-MCA1EF-E3 ---OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT -- 1
System.out.println("enter how many fabinocci's =");
int n=Integer.parseInt(br.readLine());
long f1=0,f2=1;
System.out.println(f1);
System.out.println(f2);
long f=f1+f2;
System.out.println(f);
int count=3;
while(count<n)
{
f1=f2;
f2=f;
f=f1+f2;
System.out.println(f);
count++;
}
}
}

A Unit Of Krishna Chaitanya Group Of Institutions phani

You might also like