Java
Java
JAVA
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
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
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.
Components of JVM
Class loader
Execution Byte code
Engine verifier
Security Garbage
Manager Collector
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
Execution Engine
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.
int i;
void me()
{
System.out.println(i);
}
public static void main(String[ ] args) {
a.me();
System.out.println(a.i);
}
}
Class: - A class is a model to creating an object. Class will not exit physically.
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.
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.
C++ Java
C++ is not a purely object,-oriented Java is purely object oriented
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: -
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.
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
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
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.
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);
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);
}
}
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.
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
InputStreamReader
System.in
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
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.
Output:
weeping...
barking...
eating...
Ex1:
Interface A
{
Int x=20;//public static final
Void method();//public abstract
}
Interface B
{
Int x=30;
Void method();
}
//Other functionality
//Call the Asynctask
ce.doAsynctask();
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);
n=sc.nextInt();
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;
Output:
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;
}
Output
Enter first number
25
Enter second number
3
Hcf of two numbers is=1
class Lcm
}
}
Output:
enter number 1
125
enter number 2
4
LCM of 125 and 4 is =500
{
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
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
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");
}
}
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 {
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;
}
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)