Sunteți pe pagina 1din 56

INTRODUCTION TO JAVA

JAVA

 Object Oriented Program is a programming approach in which a problem domain is characterized as


a set of objects that have a specific attributes and behavior. The objects are manipulated with a collection of
functions called methods or services. The objects are classified into classes and subclasses. (or)
 An Object Oriented Programming organizes a program around its data, i.e., objects and a set of well-
defined interfaces to that data. An object-oriented program can be characterized as data controlling access to
code.

 Java is an Object Oriented Programming (OOP) language used to design an application, which will
run securely over the network and work on wide range of platforms.
J2SE: - J2SE stands for Java 2 Standard Edition, it is a specification used to develop fundamental java
application they may be standard or network.
J2SE = Core Java + Advanced Java
J2SE: - Java 2 Standard Edition
J2EE: - Java 2 Enterprise Edition

J2EE: - J2EE stands for Java 2 Enterprise Edition, it is a specification used to develop business solutions for
network (or) J2EE is a specification that provides an environment to run the web components and the enterprise
components.
J2ME: - Java 2 Micro Edition

J2ME: - J2ME stands for Java 2 Micro Edition, it is a specification used for developing wireless and Embedded
System. Embedded System is software, which directly installed into hardware.
Core Java – Desktop Java
NIC – Network Interface Card
Novel Network: - Net based softwaress
Ex: - Windows NT, UNIX.
Protocol: - This is also a program; it is a specification of set of rules to be followed by a computer in network.
When to send/receive data
How to send/receive data
Hand Shaking: - This means two Computers establishing a connection communicating with each other and
finally disconnecting is called Hand shaking.
Frame
A Packet represents a group of bytes. IP means Internet Protocol address
this is unique address this is given to Computers.
TCP/IP: - Transmission Control Protocol/Internet Protocol. Packet
Client: - A Client is a machine that sends a request for some services to other Computer.
Server: - Server is a machine that receives requests from the Clients and provides services to the Client
requests.
The main advantage of a network is resources sharing.

Web application: - A web application is a collection of Servlets, HTML pages, Classes and other resources that
can bundle and run on the multiple Containers from multiple Vendors.
Resources Sharing: -
 Sharing memory
 Sharing data
 Sharing software
 Sharing hardware
 Sharing Processor

Advantages: -
 High Security for data
 Lightening Speed (i.e. high speed)
Disadvantages: -
 Highly expensive.
The web browser software is installed on Internet Client.
Ex: - Internet Explorer, Mozilla, Fire fox, Netscape Navigator etc…
The software that should be installed on Internet Server is Web Server.

Web Server: - A web server is a server that provides the implementation of HTTP protocol.
Ex: - Internet information Server (IIS), Apache Web Server, etc…

Application Server: - An Application Server is a product that provides the facilities like taking care of
transactions, taking care of security and simplifies the development of business logic (or) Application servers
provides you with common middleware services, such as resource pooling, networking and more. Application
server allows you to focus on your application and not worry about the middleware you need for a robust server
side deployment.
Ex: - Microsoft Transactions Server (MT Server) from Microsoft, EJB containers like WebLogic, WebSphere,
JBoss etc…
 Hypertext Transfer Protocol (HTTP) is widely used protocol on internet.
 File Transfer Protocol (FTP), when we download a file from Internet.
 Simple Mail Transfer Protocol (SMTP) is used to send mails on the internet.
 Post Office Protocol (POP) is used to receive mails.
Programmer has: -
1. To develop a web browser
2. To increase the capabilities of web browser
3. To develop a web server
4. To increase the capabilities of the web server
5. To develop protocol

Translator is a program that converts a computer program into machine language (Electric Pulses).
There are 3 types of translators -
1. Interpreter Interpreter translates line by line of computer program
2. Compiler Compiler translates all lines of program at a single time
3. Assembler Assembler translates assembly language into machine language


x.c x.obj x.exe

Machine code Full pledged


machine code
Convert the language
Header file instructions

PIV


x.java x.class JVM

Celeron


It consists byte
code format JVM

Cyrix
JVM

 The size of each instruction is 1 byte or 8 bits.
 There are around 210 byte code instructions are available
 Byte code instruction is understand by JVM (Java Virtual Machine)

Applications

 Google docs
 Banking
 Desktop app
 Mobile app
 Web servers

How java program is executed

Source code(.java file) is compiled by javac compiler,after compiling the source code is converted to
bytecode(.class file),bytecode is again converted in to object code by using java virtual machine.

Bytecode is highly optimized set of instructions

Inorder to provide security most of the bytecode is executed with JVM

Components of JVM

Class loader
Execution Byte code
Engine verifier

Security Garbage
Manager Collector

 Sun Microsystems is developed the JVM program.


 JVM convert byte code instruction into machine code.
 JVM understand every byte code instructions.
 JVM will understand the byte code instruction & it will convert the byte code instructions into PIV
processor understandable machine language instructions.
 JVM will convert the byte code instructions into any type of processor understandable machine
language instructions.
 Java programs system independent.
 JVM is system dependent.
 Depending on operating system we have to download the operating system related JVM program.
 .class file is system independent.
 JVM is making as Java system independent.
 Portability means giving same results on any type of system or machine.

Security Problems on Internet: -


1. Eves dropping: - Reading others data illegally on Internet, is called Eves dropping.
2. Tampering: - Not only reading others data but also modifying it on Internet, is called Tampering.
3. Impersonation: - A person acting as another person on Internet is called impersonation.
4. Virus: - Virus is a harmful program that can damage data, software & hardware of a system.
 Virus was first developed by Pakistani’s. Virus will spread to *.exe, *.sys, *.doc. but *.txt files cannot
carry virus.
 Solution for eves dropping & tampering encryption/decryption. Encryption means converting data into
understandable data. Decryption means converting data back to readable form.
 For impersonation, solution is digital signature file, containing personal information for identify the
person in encrypted form. Digital signatures are developed in java.
 Solution for virus is .class file. Security manager is program that identifies illegal code and
information security polices. A .class is a text file virus can’t be affected.
Why Java is suitable for Internet: -
 Security problems on Internet are eliminated through java.
 Java is a system independent; Java is executable on any platform.
In 1990, Sun Microsystems inc., USA is developed software for remotes. (James Gosling).
In 1993, Oak language is developed, by that time some company is registered Oak name, for this
reason they named as “Java”.
In 1995, Sun world conference has given entire details of Java.
JAVA VIRTUAL MACHINE(JVM)
JVM is the heart of the execution process
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 instruction that can be
executed by the microprocessor.
In JVM, there is a module (or program) called class loader sub system, which performs the following functions:
.
 First of all, it loads the. class file into memory.
 Then it verifies whether all byte code instructions are proper or not. If it finds any instruction
suspicious, the execution is rejected immediately.
 If the byte instructions are proper, then it allocates necessary memory.to execute the program.
This memory is divided into 5 parts, called run time data areas, which contain the data and results while
running the program. These areas are as follows:
Method area: Method area is the memory block,.which stores the class code,. code of the variables, and code of
the methods in the Java program. (Method means functions written in a class)
Heap: This is the area where objects are created. Whenever JVM loads a class, a method and a heap area are
immediately created in it.
Java Stacks: Method code is stored on Method area.. But while running a method, it needs some more memory
to store the data and results. This memory is allotted on Java stacks..So, Java stacks 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. JVM uses a separate thread (or process) to execute each method. .
PC (Program Counter) registers: These are the registers (memory areas), which contain memory address of
the instructions of the methods.
Native method stacks: Java methods are executed on Java stacks. Similarly, native methods
(for exampleC/C++ functions) are executed on Native method stacks. To execute the nativemethods, generally
native method libraries (for example C/C++ header files) are required. These header files are located and
connected to JVM by a program, called Native method interface.

adaptive optimizer.
Execution engine contains interpreter and JIT (Just In Time) compiler, which are responsible for converting the
byte code instructions into machine code so that the processor will execute them. Interpreter will execute the
simple instructions whereas JIT executes blocks of code called hotspots
Most of the JVM implementations use both the interpreter and JIT compiler simultaneously to convert the byte
code.
Class
Class files
Loader

Method Java PC Native


method stacks

area Heap Stacks registers

runtime data areas

Native method interface Native method libraries

Execution Engine

What is OOPS? *****

Ans: - An Object Oriented Programming organizes a program around its data, i.e., objects and a set
of well defined interfaces to that data. An object-oriented program can be characterized as data
controlling access to code.

Features of oops
1. Object: - An object is any thing that exists in the world. An object will have properties and actions.
Variables and methods are available in object.

Objects are two types

1. Mutable Objects: - Whose contents of objects can be modified.


2. Immutable Objects: - Whose contents of objects can not be modified.
An object is super class for all the classes. The methods in the object class are as follows:

Ex: - class TestAcc

int i;

void me()

{
System.out.println(i);

}
public static void main(String[ ] args) {

TestAcc a=new TestAcc();

a.me();
System.out.println(a.i);

}
}

Class: - A class is a model to creating an object. Class will not exit physically.

 Without a class we cannot create objects.


 But a class can exist without objects.
 Class also will have variables (data) and methods (code).
 There are three class access modifiers: public, protected, private.
 There are four access levels: public, protected, default, private.
 Classes can also be modified with final, abstract or strictfp.
 A class cannot be both final and abstract.
 A final class prevents inheritance i.e a final class cannot extends the other class.
2. Encapsulation: - Bundling up of data & methods as a single unit is called Encapsulation.

Class is an example for encapsulation. The main advantage of encapsulation is programmers


can use same names in the two different classes, still there will not be any problem.

3. Abstraction: - Showing necessary data and hiding unnecessary data from the user is called
abstraction.

4. Inheritance: - Producing new classes from an existing class is called inheritance. The newly
produced class will have all the qualities of the existing class plus it can have its own qualities. The
reusability is the main advantage of Inheritance.

5. Polymorphism: - This word is comes out from the two words of Greek Words. Poly means many
and morphism means forms. Polymorphism means many forms. If something exists in different form it
is called Polymorphism. If same method performs various tasks it is called as polymorphism.

6. Message passing: - Calling a method is called as message passing

Features Of Java
Simple: Java is a simple programming language. Java is developed, they wanted it to be simple because it has to
work on electronic devices, where less memory is available.

Object-oriented: Java is an object, oriented programming language. This means Java programs use objects and
classes. Since Java is a purely object-oriented programming language, in order to write a program in Java, we
need atleast a Class or an object. This is the reason why in every Java program we write at least one class. C++
is not a purely object-oriented language, since it is possible to write programs in C++ without using a class or an
object

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. This is possible because Java can handle the protocols
like TCP/IP and UDP.

Robust: Robust means -strong. Java programs are strong and they don't crash easily like a C or C++ program.
There are two reasons -for this. Firstly, Java has got excellent inbuilt exception handling features. An exception
is an error that occurs at run time. If an exception occurs, the program terminates abruptly giving rise to
problems like loss of data. Overcoming such problems is called exception handling. This means that even
though an exception occurs in a Java program, no harm will happen.

Memory management: JVM is also capable of deallocating the memory when it is not used. Garbage collector
is a form of memory management that checks the memory from time to time and marks the variables or objects
not used by the program, automatically.
Secure.: Security problems like eavesdropping, tampering, impersonation, and virus threats can be eliminated or
minimized by using Java on Internet.
System independence: Java's byte code is not machine dependent. It can be run on any machine with any
processor and any operating system.
Portability: If a program yields the same result on every machine, then that program is called portable. Java
programs are portable. This is the result of Java's System independence nature.
Interpreted: Java programs are compiled to generate the byte code. This byte code can be downloaded and
interpreted by the interpreter in JVM. we use both compiler and interpreter for the execution.
High Performance: The-problem with interpreter inside the JVM is that it is slow. Because of this, Java
programs used to run slow. To overcome this problem, along with the interpreter,
JavaSoft people have introduced JIT (Just In Time) compiler, which enhances the speed of'
execution. So now in JVM, both interpreter and JIT compiler work together to run the program.
Multithreaded: A thread represents an individual process to execute a group of statements. JVM uses several
threads to execute different blocks of code. Creating multiple threads is called 'multithreaded'.
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.
Dynamic: Before the development of Java, only static text used to be displayed-in the browser. animation was
done using an applet program, which are the dynamically interacting programs on Internet.

Difference between c++ and java

C++ Java
 C++ is not a purely object,-oriented  Java is purely object oriented

 Pointers are available in c++  Pointers are not available in java


 Allocation and deallocation of the memory is  Allocation and deallocation is done by JVM
done by the programmer

 C++ has goto statement  Java doesn’t have goto statement

 Supports Multiple inheritance  Doesn’t support multiple inheritance

 Supports operator overloading  Doesn’t support operator overloading

 Supports automatic casting  Supports implicit casting


 Constructors and destructors are supported in c++  Doesn’t support destructors

Simple java program


Import java.lang.*;//header file
Class classname
{
Public static void main(string args[])//main function
{
System.out.println(“hello world”);//output statements
}
}

 Import:JVM goes to the library execute the code and returns the value to the program
 Public:it is the access specifier that allows programmer to control the visibility of the class members.
 Main():main function is declared since it is called outside the class
 Static:it allows main() to be called without having a particular instance of the class
 Void: return type indicates that it doesnot return any value
 String :datatype
 Args[]-it receives the command line arguments which is the parameter of the main function
 System:it is a predefined class that contains input and output functions
 Out:output stream that is connected to a console
Data types and literals: - A data type represents the type of data stores in memory (variable).
Integer data type: - It represents integer numbers i.e. the numbers without decimal points.
Subtype: -

S. No. Data type Memory size Min & Max value


1. Byte 1 byte -128 to 127
2. Short 2 bytes -32768 to +32767
3. Int 4 bytes -2147483648 to +2147483647
-9223372036854775808 to
4. Long 8 bytes +9223372036854775807 (or) -9.2 x
10-18 to 9.2 x 1018

Ex: - byte r.no = 10 (0 - literal)


 Literal means the constant value being directly storing into variable.
long x = 150L;
L means take that number forcibly as long integer to allot the memory as user defined.
float data types: - They can handle numbers with decimal points. Such number’s called floating data type.
Sub type: -

S. No. Data type Memory size Min & Max value


1. (Single precision ) float 4 bytes -3.4e38 to + 3.4e38
2. Double precision 8 bytes -1.7e308 to + 1.7e308

Q.) What is the difference between float and double? *****


Ans: - float can represents up to 7 digits after decimal point accurately.
Double can represents up to 15 digits after decimal point accurately.

Ex: - float PI = 3.142F;


 F represents forcing the JVM to take the value as float because JVM defaultly takes any decimal values
as double.

Character data type: - It represents a single characters.

S. No. Data type Memory Size Min & Max value


1. Char 2 bytes 0 to 65535

Ex: - char ch = ‘x’;

ASCII – American standard code for information interchange.

S. No. Data type Memory Size Min & Max value


1. Char 2 bytes 0 to 65535
2. Byte 1 byte -128 to 127
3. Short 2 bytes -32768 to +32767
4. Int 4 bytes -2147483648 to +2147483647
-9223372036854775808 to
5. Long 8 bytes +9223372036854775807 (or) -9.2 x
10-18 to 9.2 x 1018
6. Float 4 bytes -3.4e38 to + 3.4e38
7. Double 8 bytes -1.7e308 to + 1.7e308
8. Boolean 1 bit 0 or 1

Keyboard consists 114keys. Keyboard consists up to 200 characters only.

Q) What is Unicode? *****


Ans: - Unicode is specification that includes the alphabetic of all international languages into java character
set. Unicode uses 2 bytes to represent single character.

4. String data types: - String represents a group of characters. Strings are objects of string class in java.
Ex: - String name “Inet solv”;
String str = new String (“A String”);
Boolean data type: - They store either true or false. It can handle only two values.
Ex: - boolean response = true;
Casting: - Converting one data type into another (data) type is called casting.
Data type: - It represents the type of data stored into a variable is called Data type. There are two types of data
types.
1. Primitive data types: - These data types represent a single value methods are not available to directly handle
Primitive data types.
Ex: - char, byte, int, long, float, double, boolean.
 Primitive data types will store only single value.
2. Advanced data types (or) Referenced data types: - These data types represent groups of values. Methods
are available to handle them.
Ex: - Any array, String any class.

Q) What is the difference between primitive data types and reference types? *****
Ans: - Primitive data types represent single value methods are not available to directly handle Primitive data
types. Primitive data types will store only single value.
Referenced data types represent groups of values. Methods are available to handle them.

Note: -
1. Using casting we can covert a primitive data type into another primitive data type.
2. Using casting we can convert a referenced data type into another referenced data type.
3. We cannot use casting to covert a primitive type into a referenced type and vice versa. For this purpose
wrapper classes are available.
Casting Primitive data type: -
1. Widening: - Converting a lower data type into a higher type is called widening.
Lower data type means occupies lower memory and contains less numbers of data and higher data type
means occupies higher memory and consists higher numbers of data.
char, byte, short, int, long, float, double
Lower --------------------------------------------------- higher
Ex: - char ch = ‘B’;
int n = (int) ch; //Here (int) is cast operator.
Note: - We can convert char into int type only.
Ex: - float f = (float)n;
Here it is temporary conversion of n only.
2. Narrowing: - Converting a higher data type a lower data type is called narrowing. In narrowing we may
loose some digits or precessions.
Ex: - int n = 65;
char ch = (char)n;
Ex: - double d = 12.123;
int n = (int)d;
Casting referenced data types: - If the classes don’t have any relationship then we cannot convert from one
class to another class.
There must be some relationship between classes to casting.
We can cast one class type into another class type only if there is a relation between those classes by
the way of inheritance.
Ex: - //Casting referenced data types.
class One
{
void show1()
{
System.out.println(“One”);
}
}
class Two extends One
{
void show2() //overriding – void show1()
{
System.out.println(“Two”);
}
}
class Cast
{
public static void main(String args[ ])
{
//Super class reference to refer super class object
One o;
o = new One();
o.show1();
o.show2();
}
}
Reference variable always use to refer to an object One o. Here o is reference variable.
generalization
Generalization is a phenomenon where a sub class is promoted to a super class, and hence becomes more
general. Generalization needs widening or up-casting.
Ex:
Class one
{
Void show1()
{
S.o.p(“super class method”);
}
}
Class two extends one
{
Void show1()//override the super class method
{
S.o.p(“sub class method”);
}
}
Class cast
{
PSVM(string args[])
{
One o;
O=(one)new two;// o is referring to the sub class object
O.show1();
}
}
Specialization
Specialization is phenomencn where a super class is narrowed down to a sub class. Specialization needs
narrowing or down-casting
Ex:
Class one
{
Void show1()
{
S.o.p(“super class method”);
}
}
Class two extends one
{
Void show1()
{
S.o.p(“sub class method”);
}
}
Class cast
{
PSVM(string args[])
{
Two t;
t=(two)new one;// t is referring to the super class object
t.show1();
}
}

Class
 Class is a collection of objects of similar type
 Class is a user defined type that contains the data and code to manipulate the data
 With help of the class we can create no of objects of type class
Syntax:
Class classname
{
Type instance variable 1;
.
.
Type instance variable n;
Type method name()
{
}
}
Instance variables:
Variables defined within the class are said to be instance variables, because it contains the own copy of the
variables.
Each and every instance variables is accessed with an object
Space for instance variable is allocated during object creation
Objects
 Objects are instances of a class
 Objects are defined as an entity that contains data and its related function
 Objects may be either logical or physical
 Objects can take space in memory and communicates with each other by sending and receiving
messages
 Object is a variable that contains the memory address of the instance variables
Creating objects:
 Once when the object is created the memory allocation is made in “heap”
 Hash code is a unique identification number allocated to the objects by the JVM
Syntax:
Classname objectname =new default constructor();

Declaring objects:
 Create a variable of class type
 This variable does not define an object
 It is a variable that refers to the object
 Acquire an actual copy, physical copy of the object
 Assign the object to the variable that’s done by the new operator.
 It dynamically allocates the memory for an object and returns the reference to it.
 Reference is stored in the variable.

ex1:
class person
{
String name;//instance variables
Int age;
Void talk()//method
{
s.o.p(“hello”);
}
}
Class demo
{
PSVM(string args[])
{
Person raju=new person();//object creation
}
}
Raju-object that holds the memory address of the instance variables name and age as 100101.

Object reference variable:


ex: Box mybox;//declare reference to object
mybox=new Box();//allocate a box object
Box b1=new box();
Box b2=b1;
Box-class name
height,width,depth-instances variables of class Box
mybox-object that contains the memory address of the instance variables
b1,b2-objects
 b1 &b2 refers to the same instance variables
 Any changes made to b2 will affect b1
 Assigning the reference will not create duplicate copies of the object
To remove the reference
Box b1=new Box();
Box b2=b1; b1=null;
Operators
An operator is a symbol that performs an operation. An operator acts on some variables, called operands to get
the desired result
Classification of operators based on operands:
 Unary operators
 Binary operators
 Ternary operators
Unary operators
unary operators act on only one operand. There are 3 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, for example:
Ex: int x=5;
s.o.p(-x);//-5
s.o.p(x);//5
 Increment Operator (++)
This operator increases the value of a variable by 1,
Pre increment:
It increments the value of the variable and then stores the value
ex :
a=1,b=2
a=++b
after the execution of the statement a=3,b=3
Post increment :
It stores the value of the variable initially and then increments the value
ex : a=1
b=2
a=b++
after the execution of the statement a=2,b=3
 Decrement Operator (++)
This operator decreases the value of a variable by 1,
Pre decrement:
It increments the value of the variable and then stores the value
ex :
a=1,b=2
a=--b
after the execution of the statement a=2,b=2
Post decrement :
It stores the value of the variable initially and then increments the value
ex : a=1
b=2
a=b--
after the execution of the statement a=2,b=1
 Assignment Operator (-)
 This operator is used to store some value into a variable. It is used in 3 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;//the value of y is
stored in x
 It is used to store the value of an expression into a variable ,ex z=x+y-w;

Binary operator
Binary operators acts on 2 operands .Types
 Relational operators
 Arithmetic operators
 Logical operators
 Bitwise complement operator
 Bitwise and operator
 Bitwise or operator
 Bitwise xor operator

 Relational operators:
These operators are used for the purpose of comparing.ex:a=2,b=3
 greater than operator ,ex:a>b
 >= greater than or equal to ,ex:a>=b
 < less than operator,ex:a<b
 <= less than or equal to,ex:a<=b
 = =equal to operator,ex:a==b
 ! = not equal to operator,ex:a!=b
 Arithmetic operators:
Arithmetic operators are used to perform arithmetic operations.ex:a=2,b=3
 Addition operator(+),ex:a+b//displays 5
 Subtraction operator(-),ex:a-b//displays -1
 Division operator(/),ex:a/b//displays 0.6
 Multiplication operator(*),ex:a*b//displays 6
 Modulus operator(%),ex:a%b//displays 1
 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:
 && and operator
Ex:x=3,y=2,z=4
if(x>y&&y<z)
s.o.p(“hello”);
 I I or operator
Ex:If(a==1IIb==1IIC==1)
S.o.p(“yes”);
 not operator
ex:str1=”abc”,str2=”def”
if(!(str1.equals(str2))
s.o.p(“not equal”);
 Boolean Operators
These operators act on boolean variables and produce boolean type result. The following 3 are boolean
operators:
 &boolean and operator
 Iboolean or operator
 ! boolean not operator
Boolean & operator returns true if both the variables are true. Boolean I operator returns true if any one of the
variables is true. Boolean ! operator converts true to false and vice versa.
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//returns false&gives true only if both are true
aIb//returns true when anyone of the value is true
!b//returns true

 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 a positive number can be obtained by changing O's as 1's and vice versa

Int x=10.~x?
X=10=0000 1010
By changing O's as l's and vice versa, we get 1111 0101. This is nothing but -ll(in decimal). SO,-x = -11.
 Bitwise and Operator ( & )
This operator performs and operation on the individual bits of the numbers. The symbol for this operator is &,
which is called ampersand.
Truth table is a table that gives relationship between the inputs and the output. From the table, we can conclude
that by multiplying the input bits, we can get the output bit. The AND gate circuit present in the computer chip
will perform the and operation.
X Y X&Y
0 0 0
0 1 0
1 0 0
1 1 1

Int x=10,y=11.find the value of x& y?


X=10=0000 1010
Y=11=0000 1011
From the truth table, by multiplying the bits, we can get x&y=0000 1010=(10)
 Bitwise or Operator ( I )
This operator performs or operation on the bits of the numbers. The symbol is I, which is called pipe symbol.
Adding the input bits, we can get the output bit. The OR gate circuit, which is present in the computer chip will
perform the or operation:
X Y XIY
0 0 0
0 1 1
1 0 1
1 1 1

Int x=10,y=11.find the value of x& y?


X=10=0000 1010
Y=11=0000 1011
From the truth table, by multiplying the bits, we can get xIy=0000 1011=(11)
 Bitwise xor Operator ( ^)
This operator performs exclusive or (xor) operation on the bits of the numbers. The symbol is A, which is called
cap, carat, or circumflex symbol.
X Y X^Y
0 0 0
0 1 1
1 0 1
1 1 0
From the table, we can conclude that when we have odd number of l's the input bits, we can get the output bit as
1. The XOR gate circuit of the computer chip will perform this operation.
Int x=10,y=11.find the value of x& y?
X=10=0000 1010
Y=11=0000 1011
From the truth table, by multiplying the bits, we can get x&y=0000 0001=(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 we write x«n, the meaning is to shift the bits of x towards left n
positions.
Shifting the value of x towards left 2 positions will make the leftmost 2 bits to be lost. The value of x is 10 =
0000 10lD. 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. Ifwe write x»n, the meaning is to shift the bits of x towards right n
positions.
» shifts the bits towards right and also preserves the sign bit, which is the leftmost bit. Sign bit represents the
sign of the number. Sign bit 0 represents a positive number and 1 represents a negative number. So, after
performing » operation on a positive number, we get a positive value in the result also. If right shifting is done
on a negative number, again we get a negative value only.
Shifting the value of x towards right 2 positions will make the rightmost 2 bits to be lost. x value is 10 = 0000
1010. Now x»2 will be: 0000 0010 = 2 (in decimal)

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


This operator also shifts the bits of the 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 a 0.

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 a conditional statement. Two symbols are used for this operator? and:
syntax
variable = expressionl? expression2 expression3;

This means that first of all, expressionl is evaluated. If it is true, then expression2 value is stored into the
variable. If expressionl is false, then expression3 value is stored into the variable.
ex: max=(a>b)?a:b;
Here, (a>b) is evaluated fIrst. If it is true; then the value of a is stored into the variable max, else the value of b
is stored into max

 Member operator(.)
Member operator is also called dot operator since its s~bol is a. (dot or period). This operator tells about
member of a package or a class. It is used in three ways:
1.package contains the classes . operator can be used to refer the class of a package
Syntax:
Packagename.classname
Ex: java.io.bufferedReader
2. inorder to access the variables of the class we use (.) operator
Syntax:
Classname.variablename;
Ex :emp.id//emp-class name,id-variable name
3. . inorder to access the methods of the class we use (.) operator
Syntax:
Classname.methodname;
Ex :math.sqrt();//math-classname,sqrt()-method name

 instanceofOperator
This operator is used to test if an object belongs to a class or not. Note that the word instance means object. This
operator can also be used to check if object belongs to an interface or not.
Syntax:
Boolean variablename=object instanceof class;
Ex: Boolean x=emp instanceof employee
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 runtime).
Syntax:
Classname obj=new classname();
Ex:employee emp=new employee();??emp is object of class employee

 cast Operator
Cast operator is used to convert one datatype into another datatype. This operator can be used by writing
datatype inside simple braces
Double x=10.54;
Int y=x;//error because x and y are different
To store x value into y, we have to first convert the datatype of x into the datatype of y. It means double
datatype should be converted into int type by writing int inside the simple braces as: (int). This is called cast
operator.
Int y=(int)x;//x datatype is converted in t pint type and then stored into y

Control statements:
Control statements are the statements which alter the flow of execution and to provide better control to the
programmer on the flow of execution. They are useful to write better and complex programs.

Types of control statements:


 Selective statements
 Iterative statements
Selective statements
This group of statements allows the user to select from the multiple options
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 a group of statements.it is used to compare between two variables.
Syntax:
If(condition)
Statements1;
Else
Statements;

Ex:program to find whether the given number is positive or negative


Class demo
{
PSVM(string args[])
{
Int num=-5;
If(num>0)
s.o.p(“it is positive”);
else
s.o.p(“it is negative”);
}}
Output
It is negative
if...else if statement
This statement is used to compare more three variables.
Syntax:
If(condition1)
Statements1;
Elseif (condition2)
Statements;
Else Statements;
Ex:program to find the largest of three numbers
Class demo
{
PSVM(string args[])
{
Int a=2,b=3,c=4;
If(a>b&&a>c)
S.o.p(“a is greater”);
Elseif(b>a&&b>c)
S.o.p(“b is greater”);
Else
s.o.p(“c is greater”);
}
}
Output
C is greater
Switch statement(multi branching 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

Syntax:
Switch(variable)
{
Case value1:statements1;
Case value2:statements2;
.
.
Default:
Default statements;
}
Ex:program to find the color
Class demo
{
PSVM(string args[])
{
Char color=’g’;
Switch(color)
{
Case ‘r’:s.o.p(“red”);
Case ‘g’:s.o.p(“green”);
Case ‘y’:s.o.p(“yellow”);
Default:s.o.p(“no color”);
}
}}

Output
Green// g is passed as a input to the switch

Iterative statements
The group of statements gets repeatedly executed until the condition becomes true..

Do while loop
This loop is used when there is a need to repeatedly execute a group of statements as long condition is true. If
the condition is false, the repetition will be stopped and the flow of execution comes out of do...while loop.
It is also called as pretested loop,since the condition is checked at the end of the loop
Syntax:
Do{
Statements;
}while (condition);

Ex:program to display the numbers from 1 to 10


Class demo
{
PSVM(string args[])
{
Int x;
X=1;
Do
{
s.o.p(x);
x++;
}while(x<=10);
}
}
Output
1
2
3
4
5
6
7
8
9
10
While loop
The functioning of this loop is also similar to do while loop. This loop repeats a group of statements as long as a
condition is true Once the condition is false, the loop is terminated.
It is also known as pretested loop,since the condition is checked in the beginning of the loop
Syntax:
While(conditions){
Statements;
}

While Do while
 Pre tested loop  Post tested loop
 Loop will be executed at least once  Loop will not be executed if the condition is
false

Ex:class demo
{
PSVM(string args[])
{
Int x;
X=1;
While(x<=10)
{
s.o.p(x);
x++;
}}
Output
1
2
3
4
5
6
7
8
9
10
for Loop
The for loop is also same as do...while or while loop, but it is more compact syntactically. The for loop executes
a group of statements as long as a condition is true.it is also known as fixed execution because the no of times
the loop iterates is already known.
Syntax:
For(initialization;condition;incrementation)
{
//statements
}
Ex:class demo
{
PSVM(string args[])
{
for(int i=0;i<=10;i++)
{
s.o.p(x);
}
}

Nested for loops


For loop defined inside a for loop is nested for loop.
Syntax:
For(initialization;condition;incrementation)
{
For(initialization;condition;incrementation)
{
}
}
Ex :program for printing stars
Class stars
{
PSVM(string args[])
{
Int r=5;
For(int i=1;i<=r;i++)
{
For(st=1;st<=I;st++)
{
s.o.p(“*”);
}
S,o.println();
}
}
}
Output
*
**
***
****
*****
Foreach loop

For each loop repeatedly executes group of statements for each element of the collection.
It executes as many times as there are no of elements in the collection.
For(variable:collection)
{
Statements
}
Ex:
Class demo
{
PSVM(string args[])
{
Int arr[]={200,19,-56,46,99};
For(int i:arr)
{
S.o.p(i);
}
}
}
Ouput
200
19
-56
46
99
For Foreach
 Repeats until the condition becomes false  Used to modify the collection dynamically
 Rapid modification doesnot affect the code  Rapid modification affects the code
 It supports increment and decrement operator  It does not support increment and decrement
operator
break Statement
The break statement can be used in 3 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 blocks to go to the end of a block./Nested blocks represent a block written
within another block
syntax:
break labelname;
ex:
class demo
{
PSVM(string args[])
{
Boolean x=true;
b1;{
s.o.p(“inside b1 block”);
b2:{
s.o.p(“inside b2 block”);
break b1;
}
s.o.p(“out of all blocks”);
}
}
Output
Out of all blocks
Continue statement
Continue is used inside a loop to repeat the next iteration of the loop. When continue is executed, subsequent
statements in the loop are not executed and control of execution goes back to the next repetition of the loop.
Syntax:
Continue;
Ex:
Class continue
{
PSVM(string args[])
{
For(int j=0;j<=6;j++)
{
If(j==4)
{
Continue;
}
s.o.p(j+””);
}
}
}
Output
012356
Return statement
 return statement is used in a method to come out of it to the calling method
 It returns the result of the expression or the value of the variable
Syntax:
Returntype function name(parameters)
{
Return:
}
Ex:
Class demo
{
PSVM(string args[])
{
Demo obj=new demo();//creating objects
Int res=obj.method(10);//calling method function
s.o.p(“result”+res);
}
Int method(int num)//function definition
{
Return num*num;
}
}

Constructor: - A constructor is similar to a method, which is used to initialize the variables or objects. There
are two types of constructors.
 Parameters, which passes the variables from objects to the constructor.
 A constructor will have same name of that of its class.
 A constructor will not return any value, not even void.
 The default return value of constructor is class.
 Constructor is used to initialize the instance variables
 Constructors cannot be overridden, because constructors are not inherited into classes.
 The main purpose of constructor is to set the initial state of an object when the object is creating using
“new” operator.
 A constructor can be directly invoked by another constructor (using a call to super() or this()).
 Constructor can use any access modifier even private also. If a constructor is declared Constructor as
private in a class then it will creates only one object to its class, Types of Constructors: -
1. Default constructor: - It is a constructor without parameters.
2. Parameterized Constructor: - This will have one or more parameters.
Note: - A constructor is called and executed only once at the time of creating an object to the class.
Difference between Constructor and Method:
Constructor Method
1. Constructor is a special kind of method used to 1. A method is a function, it represents group of
instance of a class. statements to perform tasks.
2. Constructor doesn’t return any type, not even void 2. Method can return void or valid return type.
also.
3. Constructor will have the same name of that its 3. As a name except the class method name, begin
class. with lower case.
4. Constructor prevents the inheritance. 4. Method can be inherited.
5. We can over load but we cannot overridden. 5. We can over load and overridden.
6. “This” refers to another constructor in the
6. “This” refers to instance of class.
present/same class.
7. “Super” refers to invoke the super class 7. Execute an overridden method in the super class.
constructor.
8. Constructor will automatically invoke when an
8. Method has called explicitly.
instance of class is created.
Ex: - //default constructor
person()
{
name = “Vishnu”;
age = 30;
}
//action-methods
//parameterized constructor
person(String s, int a)
{
name = s; (or) this.name = name;
age = a; (or) this.age = age;
}
//action-methods
public void talk();
System.out.println(“Hello I am” +name);
 Where String s & int a are local variables to receive data from outside.
Default Constructor Parametrized Constructor
1. A constructor without any parameters is called as 1. A Constructor with one or more parameters is
default constructor. called parametrized constructor.
2. Default constructor is used to initialize every 2. Parameterized constructor is used to initialize each
object with same data. object with different data.
3. Super Class default constructor is available to its 3. Super Class parametrized constructor is not
subclass. available to its subclass.
4. Java compiler creates a default constructor, when 4. Java compiler did not provide the paramerized
the programmer did not provide any type of constructor to the class. The programmer has to
constructor in a class. provide the parametrized constructor in a class.

Ex1: - //this refers to present class variables, methods and constructors.


//Constructors
class Sample
{
int i
Sample()
{
this(); //calls para constructror)
( this() left & right simple braces will call present class default constructor)
this.display();
}
Sample(int i)
{
this.i = i; //refers to instance variable
}
void this.display(int i) ( (int i) local variable)
{
System.out.println(“i = ”+i); ( i it is a local variable)
}
}
class Demo
{
public static void main(String args[ ])
{
//Create an object to Sample class
Sample s = new Sample(); //Here default constructor is called & executed.
s.display();
}
}
To get instance variable use this.i
 This always refers to present class object.
Constructor overloading
 Constructors can be overloaded, writing two or more constructors with same name but with difference
in the parameters is called as constructor overloading.
Ex:
Class person
{
Private string name,areaname,qualification;
Private int age,mobno;
Person(string s,int i)
{
Name=s;
Age=I;}
Person(string a,int m,string q)
{
Areaname=a;
Mobno=m;
Qualification=q;
}
Void display()
{
S.o.p(name+””+age+””+areaname+””+qualification”);
}
Class demo
{
PSVM(string args[])
{
Person ex=new person(“raju”,20);
Person ex1=new person(“bagalur”,9876543210,”B.E”);
ex1.display();
ex2.display();
}}
Array: -
An Array represents a group of elements of same data type. We can represent several elements in a single
array. There are 3 types of arrays
1. One dimensional array (1D)
2. Two dimensional array (2D)
3) Multidimensional array (3D, 4D, 5D,….)
One dimensional array: - A One dimensional array represents a single row or a single column of elements.
Ex: - Marks obtained by a student in 5 subjects are: 55 64 66 74 24
Creating One dimensional array: - There are 2 ways
1. We can create 1D array by declaring & initializing it directly.
Ex: - int marks[ ] = {55,23,87,34,56};
Memory allocated by JVM is
55 57 68 70 69
[0] [1] [2] [3] [4]
Marks 55 = marks[0]
or Marks[ i ] where i is an integer number that indicates position of the element in the array. i is also called as
index. Index represents the position of an element in the array. One dimensional array consists only one index.
float x[ ] = {1.5f, 2.of,3f};
char ch[ ] = {‘a’, ‘b’, ‘c’} ;
String name[ ] = {“raj”, “kamal”, “sita”};
2) WeScan create a 1D array by using “new” operator and later we can store the elements in that array.
Ex: - int marks[ ] = new int[10];
marks[0] = 50;
marks[1] = 60;
marks[2] = 80;
Double sal[ ] = new Double[100];
String s[ ] = new String[50];
NOTE: - arrayname.length gives size of array;
Ex: - // Find total & percentage of marks
import java.io.*;
class Arr1
{
public static void main(String args[ ]) throws IOException
{
//To accept data from keyboard
BufferedReader br = new BufferedReader(InputStreamReader(System.in));
System.out.println(“How many subjects? ”);
int n = Integer.parseInt(br.readLine());
//Create array with size n
int marks[ ] = new int[n];
//Store marks into array
for(int i=0; i<n; i++);
{
System.out.print(Enter marks: ”);
marks[ i ] = Integer,parseInt[br.readLine();
}
//Find Total
int tot = 0;
System.out.println(“The array elements are: ”);
for(int i = 0; i<n; i++)
{
System.out.println(marks[ i ]);
tot = tot + marks[ i
}
//Display the total marks
System.out.println(“Total marks = ”+ tot);
//Calculate percentage
float percent = (float) tot/n; //(float) is a cast operator
System.out.println(“Percentage = ”+ percent);
}
}
 By default arrays are created in C,C++ on static memory, but in java every thing is created on dynamic
memory
 Only one for is enough to handle One dimensional array.
Two Dimensional Array (2D Array): - 2D array represents several rows & columns of elements.
Ex: - A class students are obtained marks in 5 subjects.
Student1 – 50, 51, 52, 53, 54
Student2 – 60, 61, 62, 63, 64
Student3 – 70, 71, 72, 73, 74
Creating 2D array: -
1. We can declare and initialize directly.
Ex: - int marks[ ] [ ] = {{ 50, 51, 52, 53, 54}, {60, 61, 62, 63, 64}, {70, 71, 72, 73, 74}};
JVM allot memory for the above array like below.
r1
r2
r3
C0 C1 C2 C4
1D array is a combinations of several 1D array marks[ i ] [ j ]
In this i and j are indexes. i represents as row position and j represents as column position. 2D array
consists 2 indexes.
Ex: - float marks[ ] [ ] = {{ 1.1f, 1.2f, 1.3f, 1.4f, 1.5f},
{2.1f, 2.2f, 2.3f, 2.4f, 2.5f},
{3.1f, 3.2f, 3.3f, 3.4f, 3.5f}};
2. We create 2D array using new operator and we can store elements in to it.
int marks [ ] = new int[3] [5];
char ch[ ] = new char[100] [100];
Ex: - // To display a 2D array in a matrix
Class Arr1
{
public static void main(String args[ ])
{
float marks[ ] [ ] = {{ 1.1f, 1.2f, 1.3f, 1.4f, 1.5f},
{2.1f, 2.2f, 2.3f, 2.4f, 2.5f},
{3.1f, 3.2f, 3.3f, 3.4f, 3.5f}};
System.out.printl(“In matrix form: ”);
for(int i = 0; i<3; i++)
{
for(int j = 0; j<4; j++)
{
System.out.println(x[ i ] [ j ] + “\t”);
}
System.out.println();
}
}
}
 The outer most for loop represents row of matrix and inner most for loop represents column of matrix.
for this matrix to find total of matrix same as above and then add below program
float tot = 0;
for(int i = 0; i<3; i++)
{
for(int j = 0; j<4; j++)
{
tot = tot + [ i ] + [ j ];
}

Command line arguments


Input by passing command line argument.it is an argument passed at the time of running the java program
Argument to java program can be passed by appending them to the command line when the java program is
executed
the argument Can be grouped by using double quotes that are removed before the argument are passed to the
program
inside the main() method the argument can be handled by iterating over the array of the argument that is stored
as a string

( Parameter is useful to receive values from outside to the main method.)


C:\>java prog 10 11 12

Command line
10 - args[0] 10 - Command line argument
11 - args[1]
12 - arg[s2]
Command line arguments are stored in args[0], args[1], args[2].
Command line arguments are the values passed to the main method at the time of running a program.
Ex: - //Program finds args length
class Args
{
public static void main(String args[ ])
{
//find no. of args.
int n = args.length;
System.out.println(“No. of args = “ +n);
//Displays args
for(int i = 0; i<n; i++)
System.out.println([args[ i ]);
}
}
Call the main method of a class from another class using classname.main().
Ex:
Class class1{
PSVM(string args[])
{
For(string s:args)
S.o.p(s);
}}
Class class2{
PSVM(string args[])
{
String names[]={“gopi”,”kamal”,”vinay”,”neeta jain”};
Class1.main(names);
}
}
Jagged arrays
A jagged array is a array that contains group of arrays with in it.
Jagged array can store single dimensional array or multidimensional array(2D,3D)
Ex:creating jagged array
Int x[][]=new int [2][];
X is a jagged array with size 2.so it elements will be X[0] and x[1].where these elements store two 1D arrays
X[0]=new int[2];
X[1]=new int[3];
The first array is represented by x[0] and can have 2 elements ,x[0][0]and x[0][1]
The second array is represented by x[1] can have 3 elements,x[1][0],x[1][1],x[1][2]
Methods: - A method consists of a set of statements to perform a task. A method will have two parts.
1. Method header (or) Method Prototype: - This part contains method name, parameters and method return
type.
returntype methodname(parameter1, parameter2, ……)
method parameters are local variables to receive the data from outside for the method.
Ex: - void sum(double d1, double d2)
double sqrt(double x)
long fact(int n)
double power(double x, int n)
2. Method body: - It contains statements representing the logic to solve the problem. It starts with begin “{”
and ends with “}”. In between these curlew braces we have to write statements.
Ex: - {
statements;
}
Note: - A method can return some value only if return statement is used in the method body. Method can return
only variable/objects/value.
Ex: - return 1;
return x;
return obj;
return x+y;
return x,y;  It is not possible.
 Java compiler will construct default constructor when there is not any constructor.
Instance method: - It is a method that acts upon instance variables.
To call instance methods we have to use objname.methodname();
Static method: - A static method is a method that does not act upon instance variables of a class. Static methods
are declared with static keyword.
A static method is called using objectname.methodname();
Ex: - static double(double d1, double d2)
{
return d1+d2;
}
Sample s = new Sample();
double x = s.sum(10, 15.5);
System.out.println(“Result = ”+x);
A static method is also called directly using classname.methodname();
double x = Sample.sum(10, 15.5);
1. A static method is a method it cannot act on instance variables.
2. A static method is called class.methodname();
3. Static methods are loaded on the Method area of the Class loader sub system in the JVM architecture.
4. Static method cannot access instance variable but they can access static variables.
5. A static method should be declared as static.
6. A static method is a method that can be called and executed without creating an object.
7. Static methods can’t be overridden. But it can be redefined in a subclass.
8. Static methods are overloaded.
Static Variable Instance Variable
1. A static variable is a variable whose single copy in 1. An instance variable will have a separate copy
memory is shared by all the objects of class. available in each object.
2. If any modification of one object will affect other 2. If any modification of one object will not affect
objects. other objects.
3. Static variables are executed at compilation time. 3. Instance variables are executed at runtime.
4. Instance means objects. Objects are dynamically
created by JVM on the heap area of class loader sub
4. Static variables are loaded on the method area of system in the JVM architecture. Instance variables are
class loader sub system in the JVM architecture. loaded in the objects, so ultimately instance variables
are loaded on the heap area of class loader sub
system.
5. Only static variables and methods can be accessed 5. Only instance variables and methods can be
of the call to super() or this(). accessed after super constructor runs.

 Instance variables are created in objects. Objects are in the memory of heap. So instance variable are
stored in heap.
 Static variables, Static blocks and static methods are stored on method area of JVM.
 Static variable must be declared with static keyword.
 Instance variable can be declared any where in the class and no need of initializing it. It will takes
default values.
Types of methods in Java: -
1. Static methods.
2. Instance methods
a) Accessor method
b) Mutator methods.
3. Factory methods.
 A static method does not act on instance variables.
 block is a group of statements with ()
Ex: - //A Static block
class Sample
{
static{
System.out.println(“This is inside static”);
}
public static void main(String args[ ])
{
System.out.println(“Inside main”);
}
}
Static blocks: - Static blocks are group of statements written inside a block declared as static.
 Static blocks are executed before any method is executed.
 It means static blocks are executed at the time of compilation only.
 Static blocks are stored on the method area of Class loader sub system.
Ex: - //A Static block
class Sample
{
static{
System.out.println(“This is inside static block”);
System.exit(0);
}
}
 In general without main method we can not run the java program.
2. Instance method: - Instance means objects. An object contains instance variables. Instance methods these are
methods, which act upon instance variables of a class. Instance variables are created in object in the heap
memory. This means instance methods acts upon class objects.
 An instance method is called using objectname.methodname.
 Only instance variables and methods can acess after super constructor runs.
 An instance method can access instance variables.
 Instance methods can be overloaded or overridden.
a) Accessor method: - These methods access or read instance variables.
b) Mutator method: - These methods not only read the instance variables but also modify them. Mutator
methods modify the contents of the objects.
Ex: - //Accessor and mutator methods
class Person
{
String name;
int age;
char sex;
Person(String name, int age, char sex);
{
this.name = name;
this.age = age;
this.sex = sex;
void display ()//this is an accessor method
{
System.out.println(“Name = ”+name);
System.out.println(“Age = ”+age);
System.out.println(“Sex = ”+sex);
}
}
class Demo
{
public static void main(String args[ ])
{
Person p1 = new Person(“Srinivas”, 20, ‘M’);
p1.display();
}
}
In a class:
Static blocks
These are executed initially
Static variables
Instance Variables
Instance method Then these are executed secondly
Constructor ---- Constructor will be executed finally
 When instance variable & local variable names are same then only we have to use “this”.
 A class is also called user defined data type.
 Class variables means static variables.
Ex: - //Accessor and mutator methods
class Person
{
String name;
int age;
char sex;
Person(String name, int age, char sex);
{
name = n;
age = a;
sex = s;
void display ()//this is an accessor method
{
System.out.println(“Name = ”+n);
System.out.println(“Age = ”+a);
System.out.println(“Sex = ”+s);
}
Person modify (Person obj) //Mutator method
{
obj.name = “Laxmi”;
--obj.age;
obj.sex = ‘F’;
return obj; ( obj is Person class object)
}
}
class Demo
{
public static void main(String args[ ])
{
Person p1 = new Person(“Srinivas”, 20, ‘M’);
p1.display();
Person p2 = p1.modify(p1); (or)
Person p2 = p1.modify(new Person(“Vankat”, 30, ‘M’));
p2.display();
p1.display(); (Now it will displays Laxmi’s details)
}
}
Object Object
reference variable reference variable
Srinivas Srinivas
p1 p1
20 20
Copy of reference
another
obj Lakxmi Object
We are
Venkat
storing as 19 obj
30
p2 F
Laxmi
p2
30

 Referenced variables are passed to methods by value. M


 Objects are passed to the methods byvalue.
 Any thing passed to method by value.
 There is no concept pass byvalue & pass byreference.
 Pass by reference means passed the address of variable to methods, then pointers receives the address
of variable then we can do modification.
 JVM/JVM compiler is developed in C-Language.
 Pointers are used internally by JVM, but pointers are not used by the programmers.
 The primitive java types (boolean, byte, char, short, int, long, float and double) and the keyword void
are also represented as class objects.
 methods also receives arrays as parameters and returns array as result
local variables:

Ex: - //Understanding methods


class Sample
{
double d1, d2;
sample(double d1, double d2) //parameterized constructor
//double d1, double d2 are local variables.
{
this.d1 = d1;
this.d2 = d2;
}
void sum()
{
System.out.println(“Sum = ”+(d1+d2));
}
}
class Demo1
{
public static void main(String args[ ])
{
Sample s = new Sample(10, 15.5);
s.sum();
}
}
 double d1, double d2 are local variables.
 d1, d2 are instance variables.
(or)
//Understanding methods
class Sample
{
double d1, d2;
sample(double d1, double d2) //parameterized constructor
//double d1, double d2 are local variables.
{
this.d1 = d1;
this.d2 = d2;
}
static void sum(double d1, double d2)
{
return d1+d2; // d1, d2 are local variable
}
}
class Demo1
{
public static void main(String args[ ])
{
Sample s = new Sample(10, 15.5);
double x = s.sum();
System.out.println(“Result = ”+x);
}
}
Passing arrays to methods
Just like objects are passed to methods,it is also possible to pass arrays to methods and return arrays from
methods
Ex:
Class arrays
{
Int max(int[]array)
{
Int max=0;
For(int i=0;i<array.length;i++)
{
If(array[i]>max)
{
Max=array[i];
}
}
Return max;
}
Int min(int[]array)
{
Int min=array[0];
For(int i=0;i<array.length;i++)
{
Min=array[i];
}
}
Return min;
}
Class myarray
{
Scanner sc=new scanner(system.in);
s.o.p(“enter the size of array”);
int size=sc.nextInt();
int[] myarray=new int[size];
s.o.p(“enter the elements of the array”);
for(int i=0;i<size;i++)
{
Myarray[i]=sc.nextInt();
}
Arrays a=new arrays();
s.o.p(“max value”+a.max(myarray));
s.o.p(“min value”+a.min(myarray));
}
}
Recursive functions
Method calling itself is called recursive method.
Factory methods: - A factory method is a method that returns object of the class to which it belongs. All
factory methods are static methods.
Ex: - NumberFormat obj = NumberFormat.getNumberInstance();
NumberFormat obj1= NumberFormat.getCurrencyInstance();
NumberFormat obj1= NumberFormat.getPercentInstance();
getNumberInstance(),getCurrencyInstance(),getPercentInstance() are factory methods.
In some classes we cannot use new operator to create an object. In that situation this factory methods
are used.
Input and output functions
Accepting input from Keyboard: -
Stream: - It represents flow of data from one place to another place. To move data we need stream. There
are two types of streams are available.
1. Input Stream: - It receives or reads data.
2. Output Stream: - It sends or writes data to some other place.
 Streams are represented by classes in java.io.package.
 Keyboard is represented by System.in [ System is a class]
System.in  InputStream obj - Keyboard
System.out  PrintStream obj - Monitor
System.err  PrintStream obj - Monitor

Q) What is the difference between System.out() and System.err()? *****


Ans: - System.out is used to display normal messages and results.
Ex: - System.out.println(“A normal message”);
System.err is used to display error messages.
Ex: - System.err.println(“Error message);

 Streams are represented by input/output devices.


 By using streams we can handle hardware components even though Input/output are channel we need
not to change the stream in java program. Thus we are achieving system independent.
InputStreamReader: - InputStreamReader reads the data from keyboard.
BufferedReader

InputStreamReader
System.in

BufferedReader: - It is one type of InputStreamReader. It is connected to InputStreamReader. It accepts the


data form InputStreamReader.
1. Attach the keyboard to InputStreamReader.
To create an object
Class obj = new Class()
InputStreamReader obj = new InputStreamReader(System.in);
2. Attach the InputStreamReader to BufferedReader
BufferedReader br = new BufferedReader(obj);
3. Read data from BufferedReader using read() or readLine() methods.
Ex: - //Accepting a single char from Keyboard.
import java.io.*;
class Input
{
public static void main(String args[ ])
throws IOException1
{
//Attach the keyboard to InputStreamReader
InputStreamReader obj = new InputStreamReader(System.in);
//Attach the InputStreamReader to the BufferedReader
BufferedReader br = new BufferedReader(object);
//read data from BufferedReader
System.out.println(“Enter a single char: ”);
Char ch = (char)br.read();
System.out.println(“You Entered: ”+ ch);
}
}
 br.read() returns int values so we have to use (char) before the br.read() to give in char value [  Char
ch = (char)br.read();]
 Converting one data type to another data type is called type casting or casting.
( ) is called as casting operator.
 When we are using read() method in rare conditions we will get runtime errors, so to eliminate this
error we have to use throws IOException.
 read() method cannot read more than one character.
Accepting a String: -
String ch = br.readLine();
readLine takes 255 characters.
Ex: - //Accepting int value
import java.io.*;
class Input
{
public static void main(String args[ ])throws IOException
{

1 Exception: - It means runtime error.


//create BufferedReader object to accept data from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter int No. ”);
String str = br.readLine();
int n = Integer.parseInt(str);
//parseInt(str) is a static method in Integer class
System.out.println(“Number =”+n);
}
}
 parseInt(str) is a Static method in a integer class
Accepting a float Number from keyboard: -
Same as above but in the place of int n = Integer.parseInt(str);
We have to write float n = Float.parseFloat(str); (or)
float n = Float.parseFloat(br.readLine());
Accepting a double float Number: -
Same as above
double n= Double.parseDouble(br.readLine());
Ex: - //Accept & display Employee Details
import java.io.*;
class Input
{
public static void main(String args[ ]) throws IOException
{
// To accept data from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//Accept Employee Data
System.out.print(“Employee ID: ”);
int id = Integer.parseInt(br.readLine));
System.out.print(“Employee sex: ”);
Char sex = (char)br.read();
br.skip(2);
System.out.print(“Employee Name: ”);
String Name = br.readLine();
//Display Employee Data
System.out.println(“Employee Data: ”);
System.out.println(“ID :”+id);
System.out.print(“Sex :”+sex);
System.out.print(“Employee Name :”+Name);
}
}
 br.skip(2) is used to eliminate the enter key = \r. Because when we are using br.read () & br.readLine() it will
get.
Disadvantage
There is no possibility in accepting the different types of data in same line
StringTokenizer: - The StringTokenizer class is useful to break a string into small pieces, called tokens. It
accepts different types of input in a single line.
1. To create an object to StringTokenizer
StringTokenizer st = new StringTokenizer(str, “delimiter”); (or)
StringTokenizer st = new StringTokenizer(str, “,”); (or)
StringTokenizer st = new StringTokenizer(str, “, :”);
 Here , : are called as delimiters
2. To find the next piece in the string.
String piece = st.nextToken();
3. To know if more pieces are remaining.
booleab x = st.hasMoreTokens();
4. To know how many number of pieces are there.
int no = st.countTokens();
 Token means piece of string.
Ex: - //Cutting the string into pieces
import java.util.*;
class STDemo
{
public static void main(String args[ ])
{
//Take a string
String str = “It is our capital city called New Delhi”;
//brake the string into species
StringTokenizer st = new StringTokenizer(str, “ ”);
//retrieve the pieces and display
System.out.println(“The token are: ”);
while(st.hasMoreTokens())
{
String s1 = st.nextToken();
System.out.println(s1);
}
}
}
Scanner
We can use Scanner class of java. util package to read input from the keyboard or a text file.
When the Scanner class'receives input, it breaks the input into several pieces, called. tokens. These
tokens can be retrieved from the Scanner object using the following methods:
next () - to read a string
nextByte () - to read byte value
nextlnt () - to read an integer value
nextFloat () - to read float value
nextLong ()- to read long value.
nextDouble () -to read double value
To read input from keyboard, we can use Scanner class -as:
Scanner sc=new scanner(system.in);
Ex:
Class ex
{
PSVM(string args[])
{
s.o.p(“sal”);
scanner sc=new scanner(system.in);
int id=sc.nextInt();
string name=sc.next();
float sal=sc.nextFloat();
s.o.p(“id=”,+id);
s.o.p(“name=”,+name);
s.o.p(“sal=”,+sal);
}}
Buffered reader Scanner
 It is synchronous  It is not synchronous
 It supports multiple thread  It doesnot support multiple threads
 It occupies large memory space  It occupies less memory space
 It reads only string  It can read all the datatypes
displaying Output with System.out.printf()
format and display the output, printf () method is available in PrintStream class. This method
orks similar to printf () function in C. We know that System. out returns PrintStream class
dect, so to_call the printf () method, we can use: System. out. printf () . following format characters can be used
in printf () :
 %s - string
 %c - char
 %d - decimal integer
 %f-float number'
 %0 - octal number
 %b- boolean value
 %x - hexadecimal number
 %e - number in scientific notation
 %n - new line character
Ex:
System.out.printf(“salary=%f”,sal);
Polymorphism: - Polymorphism came from two Greek words. Poly means many and morphs means forms. If
something exists in many forms, it is called Polymorphism. If the same method performs many tasks it is called
Polymorphism. There are two types of Polymorphisms.
1. Static Polymorphism
2. Dynamic Polymorphism
Dynamic Polymorphism: - This is the Polymorphism exhibited at runtime. Dynamic
means runtime. This is also known as runtime polymorphism (or) late binding.
Method consists two parts
1. Method header – It doesn’t change
2. Method body – But body will change/different
In Dynamic Polymorphism a method called is linked with method code at runtime. So it is also called
late binding.
Ex: - //Method Overloading
class Sample
{
void add(int a, int b)
{
System.out.println(“Sum of two = ” +(a+b));
}
void add(int a, int b, int c)
{
int d = a+b+c;
System.out.println(“Sum of three = ” +d);
Class Poly
{
public static void main(String args[ ])
{
Sample s = new Sample();
s.add(10,20);
s.add(10,20,30);
}
}
Ex: - class Shape{
int i;
void m1(){
System.out.println("It is shape");
}
}
class Box extends Shape{
int p;
void m2(){
System.out.println("It is box");
}
}
public class TestSuper {
public static void main(String[] args) {
Shape s=new Shape();
System.out.println(s.i);
s.m1();
//s.m2(); It is invalid
//System.out.println(s.p); It is invalid
/*From above we can say that Superclass cannot access the members of
subclass, but Superclass can access only overridden methods*/
Box b=new Box();
System.out.println(b.p);
System.out.println(b.i);
b.m1();
b.m2();
Shape s1=new Box();
/*From above we can say that Subclass can refer the Superclass reference and
Subclass can access all the members of Superclass.
System.out.println(s1.i);
s1.m1();
//s1.m2(); It is invalid
//System.out.println(s1.p); It is invalid
Box b1=(Box)new Shape(); //If we run the whole code now runtime exception
occurs
System.out.println(b1.i);
System.out.println(b1.p);
b1.m1();
b1.m2();
}
}
Output: -
0
It is shape
0
0
It is shape
It is box
0
It is shape
Exception in thread "main" java.lang.ClassCastException: com.marlabs.vara.Shape
at com.marlabs.vara.TestSuper.main(TestSuper.java:31)
Method Signature: - A method signature represents method name and its parameter. This part is called method
signature. It is useful to uniquely identify method from signature.
JVM identifies a method separately when any one of the following differences is found.
1. There may be different number of parameters in the both methods.
Ex: - void add(int a, int b)
void add(int a, int b, int c)
2. There is a difference in the data types of parameters (or) number of parameters
Ex: - void add(float a, int b)
void add(double a, double b)
3. There is a difference in the sequence of parameters (or) order of parameters
Ex: - int swap(char a, int b)
int add(int a, char b)
4. There must be difference in return type
Ex: - int add(int a, int b)
int add(int a, int b)
Any one of the above differences will make method signature to be different, then JVM can recognized
that method differently.

Overloading method: - Writing two or more methods with the same name but with different method signatures
is called method over loading. Method overloading is an example for Dynamic Polymorphism.
If you write same methods and same parameters in one
class it is called as duplicate method, but compiler doesn’t
execute this type of method. There must be some difference in double calculate(
the method in one class. double x)
 Overlaoded methods can change return type. t
 Methods can be overridden and overloaded.
 Constructors are overloaded but not overridden. double calculate
 Polymorphism is not applied to overloading.
 Reference type determines which overloaded method (double x)
will be used at compile time.
 Methods from a superclass can be overloaded in a
subclass.
 Overloading means reusing the same method name, but
with different arguments.
 Methods can be overloaded in the same class or in a subclass.
Overloaded methods:
 Must have different argument lists.
 May have different return types, as long as the argument lists are also different.
 May have different access modifiers.
 May throw different exceptions.
Ex: - //Example for Overriding
class One
{
double calculate(double x)
{
return x * x;
}
}
class Two extends One
{
double calculate(double x)
{
return Math.sqrt(x);
}
}
class Poly
{
public static void main(String args[ ])
{
Two t = new Two();
double res = t.calculate(16);
System.out.println(“Result = ”+res);
}
}
Method overriding: - Writing two or more methods in super and sub classes with the same name and same
signature is called method overriding.
The sub class method overrides the super class method. This means only sub class method is executed.
In method overriding JVM executes a method depending upon the type of the reference used to call the method.
Method overriding is an example for Dynamic Polymorphism.
 Writing body for method is called implementation.
 The argument list must exactly match that of the overridden method.
 The return type must exactly match that of the overridden method.
 The access level must not be more restrictive than that of the overridden method.
 If a method can’t be inherited we cannot override it.
 The overriding method must not throw new broader checked exceptions than those declared by the
overridden method.
 Polymorphism applies to overriding, not to overloading.
 Object type determines which overridden method is used at runtime.
 The key benefit of overriding is the ability to define behavior that's specific to a particular subclass
type.
 When a method is declared certain exceptions and you want to override that method you can cut of all
your runtime exceptions while overriding and any general level exceptions like the parent exceptions can be
replaced with its subclass exceptions list, this is the rule for overriding a method. (or) you can specify the same
set of the exceptions or you can leave out of all of the exceptions.
 When we are overriding the methods superclass methods must throws superclass exception and in
subclass method should throws subclass exception. If superclass method is throws superclass exception and it
should be hanlded by try & catch block.
 If superclass method is throws superclass exception and the subclass method can be without throwing
an exception (or) subclass method can throws runtime exceptions.
Only overrided methods are accessible by Superclass from the Subclass

What are the functional difference between method overloading and method overriding: -
Method Overloading Method Overriding
1. A programmer uses method overriding when he
1. A programmer uses method overloading when he
wants to provide different implementation for the
wants to extend an already available feature.
same feature.
2. A method overloading is code refinement. 2. Method overriding is code replacement.
3. A method overloading doesn’t depends on return 3. A method overriding depends on return type of a
type of a method and exception. method and exception.
4. Overlaoding lets you define the same operation in 4. Overriding lets you define the same operation in
different ways for different data. different ways for different object types.

Static polymorphism:
The polymorphism exhibited at compilation time is called static polymorphism.the java compiler is responsible
for binding the methods,compiler need not wait until the objects are created
Static method is a method whose single copy in memory is shared by all the objects of the class .methods belong
to the class rather than to the objects. So they are also called class methods. static methods are overloaded or-
overridden, since they ,do not depend on theobjects.
Ex:
Class one
{
Static void calculate(double x)
{
s.o.p(“square value”+(x*x));
}
Class two extends one
{
Static void calculate(double x)
{
s.o.p(“square root=”+math.sqrt(x));
}
}
Class poly
{
PSVM(string args[])
{
One o=new two();//super class method
o.calculate(25);}
}
Polymorphism with private methods
 Method overriding is not possible since the methods that are declared as private cannot be accessed by
the subclass
 Only method overloading is possible
 Overriding is possible only when the private method is called as a private method
Polymorphism with final methods
 Final methods cannot be overridden
 Method overloading is possible
 Final method improves the performance
 It just copies the code like “inline operation”
Ex:
Class a
{
Final void method()
{
s.o.p(“hello”);
}
}
Class b
{
Void method2()
{
a.method1();//call final method
}
}
Final class
It is a class that is declared as final .final keyword before the class prevents the class from inheriting.
Ex:
Final class A
Class B extends class A//run time error ..class A can not be inherited

Inheritance: - Producing new classes from an existing class is called as inheritance.


 The newly produced class is called sub class. The original class is called Super class.
 Extends is the keyword use in inheritance.
Syntax: -
class Subclass extends Super class
 Reusability is the main advantage of inheritance.
 Because of reusability developing of software/program becomes easy.
 Sub class contains a copy of super class object.
 In inheritance, we create object to only sub class. Because in Sub class it contains all the methods &
objects of class are available to sub class.
Case 1: -
//If Super class has a default constructor
class One
{
One()
{
System.out.println(“One”);
}
}
class Two
{
Two()
{
System.out.println(“Two”);
}
}
class Const
{
public static void main(String args[ ])
{
Two t = new Two();
}
}
 When you create an object to sub class to super class constructor is also available to sub class.
 Super class default constructor is also available to sub class.
 Super class parameterized constructor is not available to sub class.
Case 2: -
//If Super class has parameterized constructor
class One
{
int i;
One(int i)
{
this.i = i;
}
void show()
{
System.out.println(“Super class method = ” +i);
}
}
class Two extends One
{
int i;
Two(int x, int y)
{
super(x); //super() means calling super class default constructor
i = y;
}
void show()
{
System.out.println(“Sub class method = ” +i);
System.out.println(super.i);
super.show();
}
}
class Const
{
public static void main(String args[ ])
{
Two t = new Two(100,200);
t.show();
}
}
 Super keyword refers to super class from sub class.
 Using super key word we can refers to super class instance variables constructors, methods also.
 super.show() in sub class. It shows super class method.
 We have to initialize first super class constructor.
super(x);

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.

Single Inheritance Example


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...

Multilevel Inheritance Example


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat(); //c.bark();//C.T.Error
}}
meowing...
eating...
Interface: - An Interface defines a protocol of behavior that can be implemented by any class anywhere in the
class hierarchy. An interface defines a set of methods but doesn’t implement them. An interface is a named
collection of method definitions (without implementations). An interface can also declare constants.
An interface is a specification of method proto types. Prototypes will be in the interface. All the methods of the
interface are abstract.
For polymorphic interface inheritance, where the client wants to only deal with a type and does not
care about the actual implementation use interfaces. If you need to change your design frequently, you should
prefer using interface to abstract. Coding to an interface reduces coupling and interface inheritance can achieve
code reuse with the help of object composition. Another justification for using interfaces is that they solve the
‘diamond problem’ of traditional multiple inheritance as shown in the figure. Java does not support multiple
inheritances. Java only supports multiple interface inheritance. Interface will solve all the ambiguities caused by
this ‘diamond problem’.
 All the methods are incomplete only.
 We can create reference to the interface.
 We can’t create an object to interface.
 In interface we have the abstract methods. Implementation class is a class, where all the methods in a
class.
 We can provide several classes for the same interface.
 In interface here all the abstract methods. So must implement all methods in a class (this can also
contain or within body to that methods) this class is called implemented class.
 We can provide n number of implement to interface.
 Interface contains only names.
 Database is repository of data. To manage and to store the data, database is needed. Data is stored in
the form of tables.

API doc. Implementation Databases

class (I.C.) Oracle


void connect() *
Boy for the
{
method
* Sybase
remove it & --------------------
I. C.
use interface.
--------------------
Mysql
*
I. C.
main method

 void method() this support all or any database in the world.


 The database & to retrieve the data.
 All the methods in interface are abstract.
 Driver is an implementation class, where the methods are implemented.
 Interface is more powerful than class.
 API document is a .html file, that contains description of all the features of a software or a product or a
technology.
 By default all the methods of interface are public & abstract.
Ex: - //Interface example
interface MyInter
{
void connect(); //public abstract
}
class OracleDB implements MyInter
{
c OracleDB
public void connect()
{
System.out.println(“Connecting to Oracle database…”); connect()
} mi
method
}
class SybaseDB implements MyInter c references that object
{
public void connect()
{
System.out.println(“Connecting to Sybase database…”);
}
}
class MysqlDB implements MyInter
{
public void connect()
{
System.out.println(“Connecting to Mysql database…”);
}
}
class Database c OracleDB
{
public static void main(String args[ ])
connect()
throws Exception mi
method
{
//Accept the database name and store it in object c. c references that object
Class c = Class forName(args[0]);
//Create an object to the class whose name is in c.
MyInter mi = (MyInter)c.newInstance();
//Call connect() method using mi
mi.connect();
}
}
Save it Database.java
C:\rnr>javac Database.java
C:\rnr>java Database.java OracleDB
C:\rnr>java Database.java SybaseDB
C:\rnr>java Database.java MysqlDB
Interface: (summary)
1. An interface is a specification of method prototypes.
2. An interface contains o or more abstract methods.
3. All the methods of the interface are public and abstract by default.
4. An interface may have variables, which are public static and final by default. In another words, interfaces can
declare only constants, not instance variables.
5. We cannot create an object to an interface.
6. But we can create a reference of interface type.
7. All the abstract methods of the interface should be implemented in its implementation class.
8. Interface reference can be used to refer to the objects of implementation classes.
9. If any method is not implemented in an implementation class, it should be declared as “abstract”.
10. Once an interface is written, any third party vendor can implement it.
11. An interface cannot implement another interface.
12. An interface can extend another interface.
13. We can write a class inside an interface.
14. A class can implement multiple interfaces.
15. All the methods are incomplete only.
16. Interface methods must not be static. Because interface methods are abstract, they cannot be marked final,
strictfp, or native.
17. Interface dos not have constructors. Interfaces are not part of an object’s inheritance tree.
Multiple :Inheritance using Interfaces
We know that in multiple inheritance, sub classes are derived from multiple super class .super classes have same
names for their members (variables and methods) then which members are inherited into the sub class is the
main confusion in multiple inheritance.This confusion is reduced by using interfaces to achieve multiple
inheritance. Let us take two interfaces as:

Ex1:
Interface A
{
Int x=20;//public static final
Void method();//public abstract
}
Interface B
{
Int x=30;
Void method();
}

Ex2: - //Multiple Interface example


interface Father
{
int PROP1 = 500000; //public static final, final means fixed values
float HT1 = 6.2f;
}
interface Mother
{
int PROP1 = 800000;
float HT1 = 5.0f;
}
class Child implements Father, Mother
{
void property()
{
System.out.println(“Child’s Property = ”+(PROP1 + PROP2));
}
class Multi
{
public static void main(String args[ ])
{
Child ch = new Child();
ch.property();
ch.height();
}
}
O/P: - Child’s property = 13, 00, 000
Child’s height = 5.6

Call back using interfaces


The mechanism of calling from one function to another function by passing its memory address is known as
callback.
Call backs are achieved in java with the help of interface references
Java does not have the concept of function pointer
It implements Callback mechanism through its Interface mechanism
Here instead of a function pointer, we declare an Interface having a method which will be called when the callee
finishes its task

The CallBack Interface


public interface Callback
{
public void notify(Result result);
}
The Caller or the Higher Level Class
public Class Caller implements Callback
{
Callee ce = new Callee(this); //pass self to the callee

//Other functionality
//Call the Asynctask
ce.doAsynctask();

public void notify(Result result){


//Got the result after the callee has finished the task
//Can do whatever i want with the result
}
}

The Callee or the Lower Layer Function


public Class Callee {
Callback cb;
Callee(Callback cb){
this.cb = cb;
}

doAsynctask(){
//do the long running task
//get the result
cb.notify(result);//after the task is completed, notify the caller
}
}
Programs
1.factorial of a number
Class fact
{
public static void main(String arg[])
{
int n=5,fact=1;

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

fact=fact*i;
}
System.out.println("factoral="+fact);
}
}

2. Average of n numbers

class Average

{
public static void main(String arg[])
{
int n;double res=0;
Scanner sc=new Scanner(System.in);

System.out.println("enter how many numbers to cal avg");

n=sc.nextInt();

int a[]=new int[n];

System.out.println("enter "+n+" numbers");

for(int i=0;i<n;i++)
a[i]=sc.nextInt();

for(int i=0;i<n;i++)
res =res+a[i];

System.out.println("average="+res/n);

3. sum of numbers

class sum

{
public static void main(String arg[])
{
int n,sum=0;

Scanner sc=new Scanner(System.in);

System.out.println("enter how many numbers you want sum");


n=sc.nextInt();
int a[]=new int[n];
System.out.println("enter the "+n+" numbers ");
for(int i=0;i<n;i++)
{
System.out.println("enter number "+(i+1)+":");
a[i]=sc.nextInt();
}
for(int i=0;i<n;i++)
{
sum+=a[i];
}
System.out.println("sum of "+n+" numbers is ="+sum);
}
}

Output:

enter how many numbers you want sum


5
enter the 5 numbers
enter number 1:
32
enter number 2:
12
enter number 3:
43
enter number 4:
212
enter number 5:
23
sum of 5 numbers is =322

4.HCF of two numbers

class Hcf
{
int temp;
int highest(int a,int b)
{
if(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
return highest(a,b);
}
return a;
}

public static void main(String arg[])


{
Hcf h=new Hcf( );
int n1,n2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter first number");
n1=sc.nextInt();
System.out.println("Enter second number");
n2=sc.nextInt();
System.out.println("Hcf of two numbers is="+h.highest(n1,n2));
}
}

Output
Enter first number
25
Enter second number
3
Hcf of two numbers is=1

5. LCM of two numbers

class Lcm

public static void main(String arg[])


{
long a,b,lcm;
Scanner sc=new Scanner(System.in);
System.out.println("enter number 1");
a=sc.nextLong();
System.out.println("enter number 2");
b=sc.nextLong();
lcm=lcmCalculation(a,b);
System.out.println("LCM of "+a+" and "+b+" is ="+lcm);
}
static long lcmCalculation(long n1,long n2)
{
long temp,i=2,res;
if(n1>n2)
res=n1;
else
res=n2;
temp=res;
while(res%n1!=0 || res%n2!=0)
{
res=temp*i;
i++;
}
return res;

}
}

Output:

enter number 1
125
enter number 2
4
LCM of 125 and 4 is =500

6.leap year or not


class Leapyear

{
public static void main(String arg[])
{

int year=Integer.parseInt(arg[0]);
if(year!=0)
{
if(year%400==0)
System.out.println(year+" is a leap year");
else if(year%100==0)
System.out.println(year+" is not a leap year");
else if(year%4==0)
System.out.println(year+" is a leap year");
else
System.out.println(year+" is not a leap year");
}
else
System.out.println("Year zero does not exist ");
}
}

Output

Leapyear 2050

2050 is not a leap year

7. reverse a number

class Rev

{
public static void main(String[] arg)
{
int a,res=0,n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
n=sc.nextInt();
while(n!=0)
{
a=n%10;
res=(res*10)+a;
n=n/10;
}
System.out.println("reverse of a number is "+res);
}
}

output

Enter a number
153
reverse of a number is 351

8.reverse a string
class ReverseString{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1 ; i >= 0 ; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of the string: " + reverse);
}
Output
Enter the string to reverse:computer science
Reverse of the string:ecneics retupmoc

9.to check the number is prime or not

class PrimeCheck
{
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter any number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}

Output;Enter any number:

19 is a Prime Number
10.fibonacci series
class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}

Output
0 1 1 2 3 5 8 13 21 34
11.calculator
public class JavaExample {

public static void main(String[] args) {

double num1, num2;


Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = scanner.nextDouble();
System.out.print("Enter second number:");
num2 = scanner.nextDouble();

System.out.print("Enter an operator (+, -, *, /): ");


char operator = scanner.next().charAt(0);

scanner.close();
double output;

switch(operator)
{
case '+':
output = num1 + num2;
break;

case '-':
output = num1 - num2;
break;

case '*':
output = num1 * num2;
break;

case '/':
output = num1 / num2;
break;
default:
System.out.printf("You have entered wrong operator");
return;
}

System.out.println(num1+" "+operator+" "+num2+": "+output);


}
}
Output:

Enter first number:40


Enter second number:4
Enter an operator (+, -, *, /): /
40.0 / 4.0: 10.0

12.floyds triangle
class FloydTriangleExample
{
public static void main(String args[])
{
int rows, number = 1, counter, j;
//To get the user's input
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of rows for floyd's triangle:");
//Copying user input into an integer variable named rows
rows = input.nextInt();
System.out.println("Floyd's triangle");
System.out.println("****************");
for ( counter = 1 ; counter <= rows ; counter++ )
{
for ( j = 1 ; j <= counter ; j++ )
{
System.out.print(number+" ");
//Incrementing the number value
number++;
}
//For new line
System.out.println();
}
}
}
Output
Enter the number of rows for floyd's triangle:
6
Floyd's triangle
****************
1
23
456
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
13.To find the number is Armstrong or not using buffered reader
class ArmstrongBuf
{
public static void main(String[] arg) throws IOException
{
int a,arm=0,n,temp;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number");
n = Integer.parseInt(in.readLine());
temp=n;
while(n!=0)
{
a=n%10;
arm=arm+(a*a*a);
n=n/10;
}
if(arm==temp)
System.out.println(temp+" is a armstrong number ");
else
System.out.println(temp+" is not a armstrong number ");
}
}
output
Enter a number
153
153 is a armstrong number
UNIT I -QUESTION BANK

PART A (2 M ARKS)

1. What are the features of Java Language?


2. Give any 4 differences between C++ and Java.
3. What are the data types supported in Java?
4. What is the use of static keyword?
5. What is the use of final keyword?
6. What is a constructor?
7. What is the use of this keyword?
8. What is Polymorphism?
9. How will you initialize arrays?
10. What are the advantages of Java Language?
11. What is the general form of a class?
12. What are local variables
13. What are instance variables?
14. What is the importance of static variable?
15. Define Interface.
16. What is type casting?
17. List the Control statements in Java
18. What are the different types of Operators in java?
19. How to declare the objects in java program?
20. Give the syntax for command line arguments.
21. What is Class and Objects?
22. What is an object reference variable.
23. Difference between up casting and down casting

PART – B (16 MARKS)


1. Explain OOP Principles.
2. Give suitable example for Class and methods.
3. Explain about the features in java
4. Explain Constructors with examples
5. Explain the concept of inheritance with program
6. Describe an interface with example.
7. With suitable examples explain about arrays in java.
8. Explain briefly about control statements in java with syntax.
9. Write a java program for type conversion and casting.
10. Explain polymorphism in detail with example
11. Explain passing primitive datatypes to the methods and passing objects to the methods explain

S-ar putea să vă placă și