Java Unit 1
Java Unit 1
Java Unit 1
OOPS stands for Object Oriented Programming System. It is the most popular
approach followed by programming languages. Java is one such language which
follows OOPS.
Objects: Objects are the basic runtime entities in an object-oriented system. They
may represent a person, a place, a bank account or any thing that the program can
handle.
Classes: A class is a collection of objects of similar type. The entire set of data and
code of an object can be made a user-defined data type using the concept of a class.
A class may be thought of as a data type and an object as a variable of that type.
Once a class has been defined, we can create any number of objects belonging to
that class.
Benefits of OOP:
Object-Oriented Programming contributes to the solution of many problems
associated with the development and quality of software products.
The advantages of OOP are:
Through inheritance we can eliminate redundant code and extend the use of
existing classes.
We can build programs from the standard working modules that communicate
with one another, rather than having to start writing the code from scratch.
Data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.
It is possible to have multiple objects to coexist without any interference.
It is easy to map objects in the problem domain to those objects in the
program.
It is easy to partition the work in a project based on objects.
The data-centered design approach enables us to capture details of a model
in implementable form.
Object-oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects make the
interface descriptions with external systems much simpler.
Software complexity can be easily managed.
Java has many advanced features when compared to other programming languages.
Compiled and Interpreted: First, Java compiler translates source code into
bytecode instructions. Bytecodes are not machine instructions and therefore, in the
Java systems not only verify all memory access but also ensure that no viruses are
communicated with an applet. The absence of pointers in Java ensures that
programs cannot gain access to memory locations without proper authorization.
Simple, Small and Familiar: Java is a small and simple language. Familiarity is
another important feature of Java. To make the language look familiar to the existing
programmers, it was modeled on C and C++ languages. Java uses many constructs
of C and C++ and therefore, Java code "looks like a C++" code. In fact, Java is a
simplified version of C++.
class SampleOne
{
public static void main (String args[ ])
{
System.out.println ("Java is better than C++.");
}
}
Class Declaration
class SampleOne
Opening Brace
Every class definition in Java begins with an opening brace "{" and ends with a
matching closing brace "}", appearing in the last line in the example. This is similar
to C++ class construct. (Note that a class definition in C++ ends with a semicolon.)
defines a method named main. Conceptually, this is similar to the main( ) function
in C/C++. Every Java application program must include the main( ) method. This is
the starting point for the interpreter to begin the execution of the program. A Java
application can have any number of classes but only one of them must include a
main method to initiate the execution.
The keyword public is an access specifier that declares the main method
Public: as unprotected and therefore making it accessible to all other classes. This
is similar to the C++ public modifier.
Next appears the keyword static, which declares this method as one that
belongs to the entire class and not a part of any objects of the class. The
Static:
main must always be declared as static since the interpreter uses this
method before any objects are created.
The tyep modifier void states that the main method does not return any
Void:
value (but simply prints some text to the scree.)
This is similar to the printf( ) statement of C or cout << construct of C++. Since
Java is a true object oriented language, every method must be part of an object. The
println method is a member of the out object, which is a static data member of
System class.
Java Program Structure: A Java program may contain many classes of which only
one class defines a main method. Classes contain data members and methods that
operate on the data members of the class. Methods may contain data type
declarations and executable statements. To write a Java program, we first define
classes and then put them together. A Java program may contain one or more
sections as shown below:
{ Essential
package student;
The package statement is optional. That is, our classes do not have to be part of
package.
Import Statements: The next thing after a package statement (but before any
class definitions) may be a number of import statements. This is similar to the
include statement in C. Example:
import student.test;
This statement instructs the interpreter to load the test class contained in the
package student. Using import statements, we can have access to classes that are
part of other named packages.
Class Definitions: A Java program may contain multiple class definitions. Classes
are the primary and essential elements of a Java program. These classes are used to
map the objects of real-world problems. The number of classes used depends on the
complexity of the problem.
Main Method Class: Since every Java stand-alone program requires a main
method as its starting point, this class is the essential part of a Java program. A
simple Java program may contain only this part. The main method creates objects of
various classes and establishes communications between them. On reaching the end of
main, the program gets terminated.
Creating the Program: We can create a program using any text editor like
notepad. But, we need to make sure that the program name should be saved with
the extension “.java”. Advisably, the name of the program should match with the
name of the public class or a class that has main() method.
class Test
{
IIMC Prashanth Kumar K(Head-Dept of Computers)
7
public static void main(String as[])
{
System.out.println(“Java Program”);
}
}
Compiling the program: Java program involves two steps for its execution: one
compilation and the other execution. We use “javac” tool to compile java program.
This yields byte code file whose extension is “.class”. This is an intermediate file and
not directly executable.
Running the Program: Now, java program is interpreted by the tool “java” which
as an interpreter. This is different for different machines. This tool generates
executable code for the machine in use. Thus one can view the output of the java
program.
1. Type the program in the DOS editor or notepad. Save the file with a .java
extension.
2. The file name should be the same (advisably) as the class, which has the main
method.
3. To compile the program, using javac compiler, type the following on the command
line: Example: javac Test.java
4. After compilation, run the program using the Java interpreter.
Example: java Test
5. The program output will be displayed on the command line.
All language compilers translate source code into machine code for a specific
computer. But, Java compiler produces an intermedia code known as bytecode for a
machine that does not exist. This machine is called the Java Virtual Machine and it
exists only inside the computer memory. It is a simulated computer within the
computer and does all major functions of a real computer
The virtual machine code is not machine specific. The machine specific code is
generated by the Java Interpreter by acting as an intermediary between the virtual
machine and the real machine. The Java API acts as the intermediary between the
operating system and the Java Framework. The virtual machine code is not machine
specific. The machine specific code (known as machine code) is generated by the Java
interpreter by acting as an intermediary
Command line arguments are the parameters passed to the executable java program in
the form of strings. Command line arguments are collected in main function itself. The
argument is an array of strings and can collect the list of strings. File name is not
included in the list of arguments as in C language. This is very useful to receive quick
inputs.
class Test
{
public static void main(String args[])
{
System.out.println(“Number of arguments=”+as.length);
for(int i=0;i<as.length;i++)</as.length;i++)
System.out.println(as[i]);
}
}
java Test 1 2 3
Number of arguments=3
Data-type: Data-type specifies what type of value a variable can store. It also
specifies its size. Every variable in Java has a data-type. Java language is rich in its
data types. The categories of different data-types are shown below. The two main
types are Primitive and non-primitive types.
1. Integer type: An integer type of variables can hold integer constants. Java
supports four types of integer data types. They are byte, short, int and long. The
following table shows size in bytes and range of values each data type can represent.
Integer can be converted to long type by typing ‘L’ after them.
2. Floating point type: This data type is used to represent numbers containing
fractional values. They are two types of data-types under this category, namely, float
and double. float type number are single precision numbers while double type
number are double precision numbers. By default float are double precision and can
converted to single precision by adding ‘f’ at the end. Double precision types are
used when greater precision is required in storage of floating point. Floating point
data types have special NaN (Not a Number) value for undefined numbers like 0/0
etc.
3. Character type: Java provides a data type called char to hold character values. It
is of size 2 bytes and assumes single character. The character value must be
enclosed in single quotes.
4. Boolean type: It can have only two values, either ‘true’ or ‘false’. Its keyword is
‘boolean’ and use only 1 bit. All comparison operators return boolean type values.
The words ‘true’ and ‘false’ cannot be used as identifiers.
Type casting is a process to convert one data type to another. It makes the variable
compatible temporarily. We often encounter situations where there is a need to store
a value of one type into a variable of another type. In such situations, we must cast
the value to be stored by preceding it with the type name in parentheses. Casting is
often necessary when a method returns a type different than the one we require.
Four integer types can be cast to any other type except boolean. Casting into a
smaller type may result in a loss of data. Similarly, the float and double can be
cast to any other type except boolean. Again, casting to smaller type can result in a
loss of data. Casting a floating point value to an integer will result in a loss of the
fractional part. If the following order is used for type casting, it guarantees in no loss
of information.
for example
Example:
float x=32;
The value of the x will be ’32.0’, because of implicit conversion of value from int to
float
Explicit type Casting: if a user forcefully changes the data type into other allowable
data type it is said to be explicit type casting.
Example:
int to float:
float x;
x=5/2 /* value of x will be 2.0 */
x=(float)5/2; /* value of x will be 2.5 */
float to int:
int x;
IIMC Prashanth Kumar K(Head-Dept of Computers)
11
x= 3.2 /* causes error */
x=(int)3.2 /* x will be 3 */
The character pair ? : is a ternary operator available in Java. This operator is used to
construct conditional expressions of the form:
Where Exp1, Exp2 and Exp3 are expressions. Exp1 is evaluated first. If it true, then
Exp2 is evaluated otherwise Exp3 is evaluated. Only one expression among Exp2 and
Exp3 is evaluated.
if (condition) {
statements
b) if else: Statements in if block get executed only when the condition is true
and statements in else block get executed only when the condition is false.
if (condition) {
Statements
else {
Statements
if ( x > 0 )
System.out.println( “positive”);
else if ( x < 0)
System.out.println(“negative ”);
else
System.out.println( “zero”);
(d). nested if: Writing if in another if is nested-if. Inner if is processed only when
outer if’s condition is true. Hence, statements in inner-if get executed only when
condition1 and condition2 are true.
13. In what way switch statement differs from if statement? (Mar 2011)
It allows the computer to evaluate the expression first and then depending on
whether the value of the expression is true or false. It transfers the control to a
particular statement. This point of program has two paths to follow, one for the true
condition and the other for the false condition.
Java has a built-in multi way decision statement known as switch. The switch
statement tests the value of a given variable against a list of case values and when a
match is found, a block of statements associated with that case is executed.
14. Write a program to find the number of and sum of all integers greater
than 100 and less than 200 that are divisible by 7.
class div7
{
public static void main(String[] args)
{
int i=0,sum=0;
for(int n=101;n<200;n++)
{
if(n%7==0)
{
sum=sum+n;
i=++i;
System.out.println(n);
}
}
System.out.println("No of integers divisible by 7 which are >100 and <200 are:" + i);
System.out.println("Sum of integers divisible by 7 which are >100 and <200 are:" + sum);
}
}
while(condition)
{
do…while: The while makes a test condition before the loop is executed. Therefore,
the body of the loop may not be executed at all if the condition is not satisfied at the
very first attempt. On some occasions it might be necessary to execute the body of
the loop before the test is performed. Such situations can be handled with the help
of the do…while statement.
do
{
}while(condition);
On reaching the do statement, the program proceeds to evaluate the body of the
loop first. At the end of the loop, the test condition in the while statement is
evaluated. If the condition is true, the program continues to evaluate the body of the
loop once again. This process continues as long as the condition is true. When the
condition becomes false, the loop will be terminated and the control goes to the
statement that appears immediately after the while statement. Since the test
condition is evaluated at the bottom of the loop, the do…while construct provides an
exit-controlled loop and therefore the body of the loop is always executed atleast
once.
The for loop is entry-controlled loop that provides a more concise loop control
structure. The general form of for loop is:
}
The execution of for statement is as follows:
1. Initialization of the control variables is done first, using assignment
statements such as i=1 and count=0. These variables are known as loop-control
variables.
2. The value of the control variable is tested using the test condition. The test
condition is a relational expression such as i<10 that determines when the loop
will exit. If the condition is true, the body of the loop is executed; otherwise the
break: an early exit from a loop can be accomplished by using the break statement.
When the break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the loop.
When the loops are nested, the break would only exit from the loop containing it.
That is, the break will exit only a single loop.
class PrimeNumber
{
public static void main (String args[])
{
int n=10,i;
i=2;
while(i<n)
{
if(n%i= =0)
{
system.out.println(“Number is not prime”);
break;
}
i++;
}
if(n==i)
System.out.println(“Given no is prime”);
}
}
continue: Java supports similar statement called the continue statement. However,
unlike the break which causes the loop to be terminated, the continue as the name
implies causes the loop to be continued with the next iteration after skipping any
statements in between.
class Demo
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
if(i<5)
continue;
System.out.println(i);
}
}
}
In the above program we are redirecting the flow of execution back to the next
iteration of the loop till i<5. When i value changes from 1 to 4(i=1,2,3,4) continue
IIMC Prashanth Kumar K(Head-Dept of Computers)
16
statement will be executed and System.out.println is not executed. Whenever i value
will become 5 i values will be displayed.
18. Write a program using while loop to display reverse the digits of the
given number.
import java.io.*;
class reverse
{
public static void main(String[] args) throws IOException
{
int i,k;
System.out.println("Enter a number to reverse");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
i=Integer.parseInt(s);
System.out.print("Reversed Number:");
while(i>0)
{
k=i%10;
System.out.print(k);
i=i/10;
}
}
}
19. Write a program to compute the sum of the digits of a given number.
import java.io.*;
class sum
{
public static void main(String[] args) throws IOException
{
int i,k,sum=0;
System.out.println("Enter a number");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
i=Integer.parseInt(s);
while(i>0)
{
sum=sum+i%10;
i=i/10;
}
System.out.println("Sum of the digits:" + sum);
}
}
Class: A class is a user-defined data type with a template that serves to define its
properties. Once the class type has been defined, we can create variables of that
type using declarations that are similar to the basic type declaration. These variables
are termed as instance of classes.
The basic form a class definition is:
The keyword extends indicates that the properties of the superclass are extended to
the subclass.
Objects in Java are created using new operator. The new operator creates an
object of the specified class and returns a reference to that object.
Rectangle r;
R=new Rectangle();
The type specifies the type of the value the method would return. This could be a
simple data type such as int, float,char and so on. It could be even void, if the
method doesn’t return any value. The parameter list is always enclosed in
parenthesis. This list contains variable names and types of all values which are
given as input. In case where no input data is required, the declaration must
retain empty parenthesis. The body actually describes the operations to be
performed.
class Rectangle
{
int length;
int width;
class Rectangle
{
int length;
int width;
Rectangle(int x,int y)
{
length=x;
width=y;
}
Special Characters:
Constructors have the same name as the class itself.
They don’t have any return type, not even void. This is because they
return the instance of the class.
Copy Constructor is a constructor that takes the object of same class as argument.
If all the properties of an object which has to be assigned to another object, this is
advisable.
Java classes can be reused in several ways. This is basically done by creating
new classes, reusing the properties of existing ones. The mechanism of deriving a
new class from old one is called inheritance. The old class is known as base class or
super class or parent class and the new one is called the subclass or derived
class or child class.
The inheritance allows subclasses to inherit all the variables and the methods
of their parent classes.
Inheritance may take different forms:
Single inheritance (only one super class)
Multiple inheritance (several super class)
Hierarchical inheritance (one super class, many subclasses)
Multilevel inheritance (derived from a derived class)
Hierarchical inheritance: If two or more classes are derived from a class, it can be
called as hierarchical inheritance.
Multiple inheritance:If a class is derived from two or more classes, it can be called
as multiple inheritance. Java does not support this type of inheritance.
Multilevel inheritance: (Oct 2012) If a class is derived from the class, which is
derived from another class; it can be called as multilevel inheritance.
Method overloading:-
Methods are created with the same name but different parameter list and different
definitions. This is called method overloading.
Method overloading is used when objects are required to perform similar task
but using different. Input parameters.
When we call a method in an object, java matches up the method name first
and then the number of parameters and then type of parameters to decide
which one of the definitions to execute. This process is known as
polymorphism.
class Room
{
float length;
float breadth;
Room(float x,float y)
{
length=x;
breadth=y;
}
Room(float x)
{
length=breadth=x;
}
Int area()
{
Return length*breadth;
}
Method overriding:-
A method defined in a super class can be inherited by its subclass and is used
by the objects created by its subclass. Method inheritance enables us to define and
use methods repeatedly in subclasses without having to define the methods again in
the subclass. However, there may be occasions when an object to respond to the
same method but have different behavior when that method is called. That means,
the super-class method should be override. This is possible by defining a method in
the subclass that has the same name, same arguments and same return type as a
class A
{
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
System.out.println("k: " + k);
}
}
class OverrideMethod {
public static void main(String args[]) {
B b = new B(1, 2, 3);
b.show();
A a=new A(10,20);
a.show();
}
}
final class A
{
Making a method final ensures that the functionality defined in the method will never
be altered in any way. Similarly, the value of a final variable can never be changed.
When a class contains atleast one abstract method, it should be declared as abstract.
When using the abstract classes, we must satisfy the following conditions:
We cannot use abstract classes to instantiate objects directly. For example
Shape s=new Shape() is illegal because Shape is an abstract class.
The abstract methods of an abstract class must be defined in its subclass.
We cannot declare abstract constructors or abstract static methods.
An array represents a group of elements of same data type. It can store a group of
elements.
In java arrays are created on dynamic memory i.e. allocated at runtime by JVM.
Arrays are generally categorized into two parts as follows:
Single dimensional arrays.
Multi dimensional arrays.
Ex:-
int counter[ ];
int[ ] counter;
These lines create necessary memory locations for the array counter. It is
also possible to combine the two steps declaration and creation of memory location
as follows:
Initialization of arrays:-
Putting values into the array is known a “initialization”. This is done as
follows:
arrayname[subscript]=value;
Ex:-
counter[0]=35;
Java creates arrays starting with the subscript of 0 and ends with a value one
less than the size specified.
Arrays can also be initialized automatically when they are declared, as shown
below:
Syntax:- type arrayname[ ]={list of values};
Ex:-
In the above example array size is not given, the compiler allocates enough
space for all elements specified in the list.
Multi-dimensional arrays:-
Multidimensional arrays can represent the data in the form of rows and columns i.e. by
taking two or more indexes.
2-Dimensional Arrays: 2-Dimensional Arrays can represent the data in the form of rows
and columns i.e. by taking two indexes. Generally, these are used to work with matrices.
Advantages of arrays:
Disadvantages:
import java.io.*;
class matrixmult
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int m1[][]=new int[3][3];
int m2[][]=new int[3][3];
int m3[][]=new int[3][3];
int i,j,k;
System.out.println("Enter elements of first matrix ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m1[i][j]=Integer.parseInt(br.readLine());
}
}
/*Matrix multiplication*/
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m3[i][j]=0;
for(k=0;k<3;k++)
{
//m3[i][j]+=m1[i][k]*m2[k][j];
m3[i][j]=m3[i][j]+m1[i][k]*m2[k][j];
}
}
}
class VectorTest
{
public static void main(String as[])
{
Vector v1=new Vector(10);
v1.add(“10”);
v1.add(“20”);
v1.add(“30”);
System.out.println("Number of Elements:"+v.size());
System.out.println("Vector Elements:"+v1);
}
}
interface InterfaceName
{
Variables declaration;
Methods declaration;
An interface variable is public, static and final by default. This means all the variables
of the interface are constants. Methods declaration will contain only a list of methods
without anybody statements.
1. Extending interfaces
Interfaces can also be extended. The sub interface will inherit all the members of the
super interface. This is achieved by using the keyword extends.
Sub interfaces can not define the methods declared in the super interfaces. So class
is
used to implement the derived interface, to define all the methods.
2. Implementing interfaces:-
Class must be defined to implement the code for the method of interface.
Example:
interface Area
{
final static double pi=3.14;
double compute (double x, double y);
}
Class Interface
A class must be declared using the An interface must be declared using the
keyword class keyword interface
A class contains the methods which are An interface consists of methods which
defined. are declared.
A class can implement many interfaces An interface can extend another interface
A class can simultaneously extend a class An interface is that which can simulate
and implement multiple interfaces multiple inheritance.
A class which implements an interface An interface is implicitly abstract. It
must implement all of the methods cannot be directly instantiated except
declared in the interface or be an when instantiated by a class .
abstract class.
Methods of a class can use any access In an interface, all methods are implicitly
specifier. public
Variables of a class can be defined In an interface, all variables are static
according to the requirement and final by default.