Programming Java Unit-1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

1.

Creation of Java (History of Java)


Java is an Object-Oriented programming Language developed by James
Gosling and his colleagues at Sun Microsystems in 1991. It took 18 months to
develop the first working version. This language was initially called “Oak”, but
was renamed “Java” 1995. Java is intended to be compiled to a bytecode,
which is then run by a Java Virtual Machine (JVM). The original motto for
java was not the Internet. The primary motivation was the need for a platform-
independent language that could be used to create software to be embedded in
various consumer electronic devices.

Sun Microsystems released the first version 1.0 of java in 1995. It was
followed by java 1.02 two months later. In this version database connectivity
and distributed object features are added. Version 1.1 released in 1997, added a
robust event model, awt enhancements, jar files, RMI (Remote Method
Invocation) and Beans. Version 1.2 released at the end of 1998, has the feature
of Swing, Java 2D, Accessibility Drag and Drop, JAVA IDL (Java Interface
Definition Language), JNI (Java Native Interface) enhancements and JVMDI
(Java Virtual Machine Debug Interface). JDK 1.2 is called Java 2 platform.
Present version of java is JAVA SE 10.

2. Why Java is Important to the Internet?


The reason for this is quite simple. Java expands the universe of objects that
can move freely in cyberspace. In a network, two very broad categories of
objects are transmitted between the server and your personal computer: First
type of object can be transmitted to your computer: Passive information and
dynamic, active programs. For example, when you read your e-mail, you are
viewing passive data. Even when you download a program, the program’s code
is still only passive data until you execute it. Second type of object can be
transmitted to your computer: a dynamic, self –executing program. Such a
program is an active agent on the client computer, yet is initiated by the server.
For example, a program might be provided by the server to display to display
properly the data that the server is sending.
Java Applets: An applet is a special kind of Java program that is designed to be
transmitted over the Internet and automatically executed by a Java-compatible
web browser.

Security: Users are worried about their systems with viral infection and
malicious programs. Java answers these issues by providing a “firewall”
between a networked application and your computer.
Portability: Many types of computers and operating systems are in use
throughout the world - and many are connected to the Internet. For programs to
be dynamically downloaded to all platforms connected to the Internet, some
means of generating portable executable code is needed. Java provides
portability.

3. Features of Java (Java Buzzwords)


i. Simple: Java is a simple language that can be learned easily, even if you
have just stared programming.
ii. Secure: Java program can be executed in an environment that disallows
the viruses and malicious programs.
iii. Portable: Java programs can run on multiple platforms by a special
program called the Java Virtual Machine. Hence only one version of the
application need to be developed and maintained for all platforms.
iv. Object-oriented: Java is purely Object-Oriented and provides Abstraction,
Encapsulation, Inheritance and Polymorphism. An object is an instance of
class consists of variables and related methods.
v. Robust: Java is a reliable language. It does not have permission to access
all of your computer memory and also provide exceptions and error
handling, so java program can’t cause a crash. Java programs are less
prone to error.
vi. Multithreaded: Multithreading is the ability of an application to perform
multiple tasks at the same time. A simple program does many tasks
simultaneously.
vii. Architecture neutral: Programmer can write programs in java without
knowing the systems architecture. Java compiler produces the byte code
that can be executed on a variety of computers running on different
operating systems.
viii. Interpreted: Java is both compile and interpreted. Compiler translates a
java program into java byte codes (.class file). Each byte code instruction
is interpreted by interpreter and run on the computer.
ix. High Performance: Java is faster than other compiled or interpreter based
languages. Since it is compiled and interpreted. Multithreading provides
the ovral execution speed of java programs.
x. Distributed: Java is designed for the distributed environment of the
Internet, because it handles TCP/IP protocols. Java also supports RMI
(Remote Method Invocation). This feature enables a program to invoke
methods across a network.
xi. Dynamic: java is a dynamic language. Java is capable of dynamically
linking in new class libraries, methods, and objects.
4. What is a Bytecode?
Bytecode is a highly optimized set of instructions designed to be executed
by the Java run-time system, which is called the Java Virtual Machine (JVM).
JVM is an interpreter for bytecode. Translating a java program into byte code
makes it much easier to run a program in a wide variety of environments. The
reason is straightforward: only the JVM needs to be implemented for each
platform.

5. The three OOP Principles


All object-oriented programming languages provide mechanisms that help
you implement the object-oriented model. They are Encapsulation, Inheritance
and Polymorphism.
Encapsulation: The Wrapping up of data and methods into a single unit is
known as encapsulation. The data is not accessible to the outside world and
only those methods, which are wrapped in the class, can access it. Abstraction
refers to the act of representing essential features without including the
background details or explanations.
Inheritance: Inheritance is the process by which objects of one class acquire
the properties of objects of another class. Inheritance supports the concept of
hierarchical classification. This is possible by deriving a new class called
derived class from an existing class called base class. The new class will have
the combined features of both the classes.
Polymorphism: Polymorphism is another important OOP concept.
Polymorphism means the ability of giving the same name to different methods.
The individual methods may implement different tasks but can be
differentiated by the type of arguments passed to them.

6. How java differs from C++


Java is a true Object Oriented Language while c++ is basically c with Object
Oriented extension. The following C++ features are intentionally omitted from
Java or significantly modified.
i. Java does not support operator overloading.
ii. Java does not include structure and union.
iii. Java does not have template classes as in c++.
iv. Java does not support multiple inheritances of classes. This is
accomplished using a new feature called “interface”.
v. Java does not use pointers
vi. There are no header files and delete operator in Java.
vii. Java is platform independent.
viii. Java does not allow default arguments.

7. Java Environment
Java environment includes a large number of development tools and hundreds
of classes and methods. The development tools are part of the system known as
Java Development Kit (JDK) and classes and methods are part of the Java
Standard Library (JSL), also known as the Application Programming Interface
(API).

JDK: The JDK comes with a collection of tools that are used for developing
and running java programs. JDK includes:
 appletviewer – Enable us to run java applets with actually using java
compatible browser.
 javac – The java compiler, which translates java source code to
bytecode file that the interpreter can understand.
 java – java interpreter interpret the bytecode and run the instruction.
 javap – Java disassemble, which enables us to convert bytecode file
into a program description.
 Rmic – create skeletons and stubs for remote method invocation.
 javah – Produces header files for use with native methods.
 javadoc – creates HTML format documentation from java source code
files.
 jdb – Java debugger, which helps us to find errors in our programs.

JSL or API: Java Standard Library (JSL) or Application Programming


Interface (API) includes hundreds of classes and methods grouped into several
functional packages. JDK 1.2 has 58 packages. The most commonly used
packages are:
 java.lang – It contains the main language support class deals with
Object wrappers, Strings, Multithreading and basic features of java.
 java.util – It provides classes that support collections, date, time and
calendar operations, parsing and basic event processing.
 java.io – This package provides reading and writing data in the form
of streams and device independent file services.
 java.awt – This package provides classes for creating GUI programs.
It contains, java’s Abstract Windowing Toolkit (AWT) etc.
 java.applet – This package includes a set of classes with support for
HTML embedded java applets.
 java.net – It combines the classes supporting low-level internet
programming and www.
 javax.swing – It offers classes for components, higher level controls
and pluggable look and feel.
8. Process of building and running Java application programs.
Text Editor

Java Source Code


javadoc HTML Files

javac

Java class file javah Header files

java jdb

Java
progam
output

9. 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 are operate on
the data members of the class. A java program may contain one or more
sections as shown below:

Documentation Section

Package Statement

Import Statements

Interface Statements

Class Definitions

Main Method class {Main Method Definition}

Documentation Section: The documentation section contains a set of lines


giving the name of the program, the author and other details, which the
programmer would like to refer to at a later stage. Comments must explain
why and what of classes and how of algorithms. The comment lines must be in
between /** and */.

Package statement: The first statement allowed in a java is a package


statement. This statement declares a package name and informs the compiler
that the classes defined here belong to this package. For example:

package colleges;

Import Statements: This section contains all import packages. These statements
instruct the interpreter to load the respected classes from the packages.
Example:
import java.util.*;
Interface statements: An interface is like a class but includes a group of method
declarations. This is an optional section and is used only when we wish to
implement inheritance feature in the program.
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 standard-alone program requires a main
method as its starting point, this class is the essential part of a java program.
The main method creates objects of various classes and establishes
communications between them. On reaching the end of main, the program
terminates and the control passes back to the operating system.
10. Java tokens
The smallest individual units in a program are known as tokens. A token is
consists of java character set. The compiler recognizes them for building up
expressions and statements. The java language includes 5 types of tokens.
They are:
i) Keywords ii) Identifiers iii) Literals iv) Operators v) Separators.
Keywords: keywords are essential part of a language definition. They
implement specific feature of the language. Java has reserved 50 words as
keywords. Understanding of all these words is important for java programs.
Examples: class, import, double, for etc.
Identifiers: Identifiers are programmer designed tokens. They are used for
naming classes, methods, variables, objects etc. Java identifiers follow the
following rules.
a) They can have alphabets, digits and the underscore and dollar sign
characters.
b) They must not begin with a digit.
c) Uppercase and lowercase letters are distinct.
d) They can be of any length.
Literals: Literals in java are a sequence of characters that represent constant
values to be stored in variables. Java specifies 5 types of literals. They are:
Inters literals, float point literals, character literals, string literals and Boolean
literals.
Operators and separators: An operator is a symbol that takes one or more
arguments and operates on them to produce a result. Operators are of many
types: Arithmetic, Relational, Logical, Assignment, Increment etc. Separators
are symbols used to indicate groups. For example, ( ), {},[ ] etc.

11. Data types


Java defines eight primitive types of data: byte, short, int, long, char, float,
double and boolean. These can be put in four groups.
i. Integers type
ii. Floating-points type.
iii. Characters type.
iv. Boolean type.
Integers: Java defines four integer types: byte, short, int and long. All these are
signed values. Java does not support the concept of unsigned integers. The
width and ranges of these integers vary widely, as shown in this table.
Data Type Width in Bits Range
byte 8 -128 to 127
short 16 -32,768 to 32,767
int 32 -2,147,483,648 to 2,147,483,647
long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
byte: The smallest integer type is byte. This is a signed 8-bit type data.
Variables of type byte are especially useful when you’re working with stream
of data from a network or file. Example:
byte b, c; // variables b and c are of type byte.
short: short is a signed 16-bit type. It has a range from -32,768 to 32,767. This
type is mostly applicable to 16-bit computers, which are becoming increasingly
scarce. Example: short s;
short t;
int: The most commonly used integer type is int. it is a signed 32-bit type. In
addition to other uses, variables of type int are commonly employed to control
loops and to index arrays. Any time you have an integer expression involving
byte, short, int and literal numbers, the entire expression is promoted to int
before the calculation is done. Example: int i, j; // i and j are of type integers.
long: long is a signed 64-bits type and is useful for those occasions where an
int type is not large enough to hold the desired value. The range of a long is
quite large. This makes it useful when big ,whole numbers are needed.
Example: long t; // t is a variable of type long.
Floating-point Type: Floating-point numbers, also known as real numbers, are
used when evaluating expressions that require fractional precision. For
example: calculations such as square root, roots of the quadratic equation, sine
and cosine. There are two kinds of floating-point types: float and double. Their
width and ranges are shown here:
Data Type Width in bits Approximate range
Float 32 1.4e-045 to 3.4e+038
Double 64 4.9e-324 to 1.8e+308
Example: float avg, cgp;
double root1,root2;

Characters: In java, the data type used to store characters is char. Java uses
Unicode to represent characters. Unicode defines a fully international character
set that can represent all of the characters found in all human languages. For
this purpose, it requires 16 bits. Thus, in java char is a 16 bit type. The range of
a char is 0 to 65,536. There are no –ve chars.

Boolean: For logical values, java has a primitive type called boolean. It can
have only one of two possible values, true or false. This is the type returned by
all conditional expressions that govern the control statements. For example the
declaration of variable b of type Boolean is: boolean b;

12. Variables, declaring variables, Dynamic initialization, scope and life time.
Variables are identifiers used to assign names to memory locations. A
memory location holds a value with which we are working. A variable can be
used to store a value of any data type.
The declaration statement defines the type of variable. The general form of
declaration of a variable is:
type identifier [= value] [, identifier [= value] . . . ];
Example: int a=7, b=56;
float ave;
int i;
Java allows variables to be initialized dynamically, using any valid expression
at time the variable is declared. For example, double c = Math.sqrt(a*a + b*b);
Java allows variables to be declared within any block. A block defines a
scope. A scope determines what objects are visible to other parts of your
program. It also determines the life time of those objects. Variables are created
when their scope is entered and destroyed when their scope is left. This means
that a variable will not hold its value once it has gone out of scope. Thus the
life time of a variable is confined to its scope.

13. Type conversion and casting.


The conversion of data from one data type to another is called type conversion
or type casting. This is classified in two types: Implicit and explicit.
i. Implicit type casting/automatic type casting: Implicitly java provides
type casting. Java automatically promotes values to a higher data type to
prevent any loss of information.
For example: byte b=100;
int a = b;
Here the byte value of b is automatically promoted to higher data type
int and then stored in variable a. This is done by java automatically. So,
it is called automatic type conversion or implicit type conversion. Here
there is no data loss. This is also called widening conversion.

ii. Explicit type casting: To create a conversion between two incompatible


types, you must use a cast. A cast is simply an explicit type conversion.
For example, what if you want to assign an int value to byte variable?
This conversion will not be performed automatically, because a byte is
smaller than an int. This kind of conversion is called a narrowing
conversion. Example: int a=5;
byte b = (byte) a;
Here the value of a is explicitly converted into byte type before storing
into the variable b.
Type casting Rules
a. A Boolean variable cannot be type cast.
b. If the range is narrowed, an explicit type cast is required.
c. If the conversion increases the range of data that can be store, it is
some time known as promotion or widening.
d. If any of the operand type is double, the other one will be converted
to double. This works similarly long, float, int, short, and byte.
e. Java automatically promotes byte or short operand to int.
14. Arrays
An array stores ordered sequence of homogeneous values that share a
common name. Homogeneous means that all the values are of the same data
type. It is fundamental data structure. There are several forms of an array used
in java: one dimensional array, two dimensional array and etc.
One dimensional array: A list of values can be given to one variable name
using only one subscript and such a variable is called single-subscripted
variable or a one-dimensional array. Creation of one dimensional array
involves three steps:
i. Declaring the array
ii. Creating memory location
iii. Putting values into the array locations
For example, if we want to represent a set of 5 roll numbers, say {35, 40, 23,
57, 13}, by an array variable rollnos, then we may create the variable rollnos
as follows.
int rollnos[ ]; // or int [ ] rollnos; //declaring array.
rollnos = new int[5]; // creating memory location for 5 values.
rollnos[0] = 35; // putting values into the array at 0th location .
rollnos[1] = 40; // putting values into the array at 1st location .
rollnos[2] = 23; // putting values into the array at 2nd location .
rollnos[3] = 57; // putting values into the array at 3rd location .
rollnos[4] = 13; // putting values into the array at 4th location .
We can declare and initialize the one dimensional array in single line.
int rollnos [ ] = {35, 40, 23, 57, 13}; //Declaring, Creation and Initialization.
int rollnos[] = new int[5];
//Declaration , Creation and Initialization with zeros by default.
int roll []; //Declaring an array varibale
roll = rollnos; // copying into another i.e., rollnos are copying into roll.

Note: In java, all arrays store the allocated size in a variable named length. We
can obtain the length of the array rollnos using rollnos.length.
Example, int n = rollnos.length;
Two Dimensional Array (or) Multidimensional Array: In java,
multidimensional arrays are actually arrays of arrays. Java allows us to define
tables of values by using two dimensional arrays. For example, the following
declares a two dimensional array variable called twod with 4 rows and 5
columns.
int twod[ ][ ] = new int[4][5];
(or)
int twod[ ][ ] = new int [4] [ ];
twod[0] = new int [5];
twod[1] = new int [5];
twod[2] = new int [5];
twod[3] = new int [5];

Two dimensional arrays can be initialized during declarations. By default all


memory locations are initialized with zeros. We can do it in one of two ways.
For example, twod is a 2 by 3 two dimensional array initialized in two ways as
follow:
int twod[2 ] [3 ] = {12, 23, 9, 45, 22, -9}; // Initializing with specific values.
int twod[2 ] [3 ] ={{12, 23, 9},{ 45, 22, -9}}; // Initializing with same values.
Two Dimensional array with variable sizes
int twod[ ][ ] = new int [4] [ ];
twod[0] = new int [1];
twod[1] = new int [2];
twod[2] = new int [3];
twod[3] = new int [4];

15. Operators in Java


Java provides a rich operator environment. These can be divided into the
following four groups:
i. Arithmetic Operators.
ii. Bitwise Operators.
iii. Relational Operators.
iv. Logical Operators.
Arithmetic Operators: Arithmetic operators are used in mathematical
expressions in the same way as used in algebra. The operands of the arithmetic
operators must be of a numeric type. The following table lists the arithmetic
operators. Lets a, b and c are integer type operands.
Operator Description Example
+ Addition c=a+b
- Subtraction c=a-b
* Multiplication c = a* b
/ Division c=a/b
% Modulus c=a%b
++ Increment a++ (or) a = a+1
+= Addition assignment a += b (or) a = a+b
-= Subtraction assignment a -= b (or) a = a-b
*= Multiplication assignment a *= b (or) a = a*b
/= Division assignment a /= b (or) a = a/b
%= Modulus assignment a %= b (or) a = a%b
-- Decrement a-- (or) a = a-1

Bitwise Operators: Java defines several bitwise operators which can be


applied to the integer types: long, int, short, char and byte. These operators act
upon the individual bits of their operands. They are summarized in the
following table.
Operator Description Example
~ Bitwise Unary NOT c=~a
& Bitwise AND c=a&b
| Bitwise OR c = a| b
^ Bitwise exclusive OR c=a^b
>> Shift right c = a >> 2
<< Shift left c = a << 2
&= Bitwise AND assignment a&=b (or) a = a & b
|= Bitwise OR assignment a |=b (or) a = a | b
Bitwise exclusive OR
^= A^=b (or) a = a ^ b
assignment
>>= Shift right assignment a>>=b (or) a =a>>b
<<= Shift left assignment A<<=b (or) a =a<<b

Relational Operators: The relational operators determine the relationship that


one operand has to the other. Specifically, they determine equality and
ordering. The outcome of these operations is a Boolean value. The relational
operators are shown here: Let suppose a and b are two variables of type
integer.
Operator Description Example
== Equal to (c == a)
!= Not Equal to (a != b)
> Greater than (a > b)
< Less than (a < b)
>= Greater than or equal to (a >= 10)
<= Less than or equal to (a <= 29)

Boolean Logical Operators: The Boolean operators operate on Boolean


operands. All of the binary logical operators combine two Boolean values to
form a resultant Boolean value. Let’s suppose a and b are two Boolean
variables. x=5 and y=9 are two integers.
Operator Description Example
& Logical AND (c &a)
| Logical OR (a | b)
^ Logical XOR (a ^ b)
|| Short-circuit OR ((x<=6)||(y<10))
&& Short-circuit AND ((x<=6)&&(y<10))
! Logical Unary NOT (!a)
!= Not equal to (x != 6)
== Equal to (x==5)
?: Ternary if-then-else (x<10)?1:2

Assignment Operator (=) : The assignment operator is the single equal sign,
=. The general form of using assignment operator is: variable = expression or
value; Example, x = 9; y = x+9; z=x=y=99;

16. Control Statements


Programming languages use control statements to cause the flow of execution
of statements. In Java, the control statements can be divided into three
categories: Selection, Iteration and Jump.
17. Explain about Selection or Decision control statements with an example.
Selection: Selection statements allow your program to choose different paths
of execution based upon the outcome of an expression or the state of a
variable. Java support two selection statements: if and switch.
i. If – The if statement is java’s conditional branch statement. It can be
used to route the program execution through two different paths. It is
also called two-way selection statement. The general form are:
a) If (condition) {statement1;
statement2;
. . . . . . . .. ;}
else
{statement1;
statement2;
.. . . . . . .. ;}
b)Nested ifs – A nested if is an if statement within another if or else.
Nested ifs are very common in programming. Example,
if (i==10) {
if (j < 20) a=b;
if (K>100) c= d;
else a=c;
}
else a = d;

c) The if–else–if Ladder: A sequence of nested ifs is the if-else-if ladder.


It looks like this:
if (condition) statement1;
else if (condition) statement2;
else if (condition) statement3;
.........
else { statement n;}

ii. Switch – The switch statement is a multi-way selection statement. It


provides an easy way to dispatch execution to different parts of your
code based on the value of an expression. The general form of a switch
statement:
Switch ( expression)
{
case value1: sequence of statements separated by semicolon
break;
case value2: sequence of statements separated by semicolon
break;
. . . .. . . . . . . . . . . . .
Case value n: sequence of statements separated by semicolon
break;
default: sequence of statements separated by semicolon if any
}
Exmple:
switch (i)
{ case 1: System.out.print(“January”);
break;
case 2: System.out.print(“February”);
break;
case 3: System.out.print(“March”);
break;
case 4: System.out.print(“April”);
break;
case 5: System.out.print(“May”);
break;
case 6: System.out.print(“June”);
break;
case 7: System.out.print(“July”);
break;
case 8: System.out.print(“August”);
break
case 9: System.out.print(“September”);
break;
case 10: System.out.print(“October”);
break;
case 11: System.out.print(“November”);
break;
case 12: System.out.print(“December”);
break
default: System.out.print(“Unknown value”);
}

18. Explain about Iteration control statements with an example.


Java provides three iteration statements: for, while and do-while. These
statements allow you to execute one or more statements repetitively.
for – The for loop executes a set of statements a fixed number of times. The
general form of for is:
for(initialization; test condition; iteration)
{
//Body
}
The initialization of the control variable is done first. The value of the control
variable is tested using test condition. If the condition is true, the body of the
loop is executed; otherwise the loop is terminated and the execution continues
with the statement that immediately follows the loop. The control variable is
updated using the iteration when the control is transferred back to for statement
after executing the last statement in the body.
Example:
for (i=0;i<5;i++)
{
// Body can contain more than one statement
System.out.print(“ For statement”);
}
while – The while is an entry-controlled loop statement. The test is evaluated
and if it is true then the body of the loop is executed. After execution of the
body, the test condition is once again evaluated and if it true, the body is
executed once again. This process is repeated until the test condition value is
false. On exit, the program continues with the statement immediately after the
body of the loop.
Example:
Whiel (i < 10)
{
i++;
System.out.print(“While statement”);
}

do .. while – The do while is an exit-controlled loop statement. The control


executes the body of the loop and tests the condition at the bottom of the loop,
if it is true then the body of the loop is executed another time. This process is
repeated until the test condition value is false. On exit, the program continues
with the statement immediately after the body of the loop. The body of the
loop is always executed at least once.
Example:
do
{
i++;
System.out.print(“While statement”);
} Whiel (i < 10)

19. Explain about Jump control statements with an example.


Java supports three jump statements: break, continue and return. These
statements transfer control to another part of your program.
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 will only exit from
the loop containing it. That is, the break will exit only a single loop.
continue – java support another jump statement called continue statement.
Unlike the break which causes the loop to be terminated, the continue causes
the loop to be continued with the next iteration after skipping any statements in
between. The format of the continue statement is simply continue;.
return – The return statement is used to explicitly return from a method. It
causes program control to transfer back to the caller of the method. The general
form of return statement is: return;.

20. Operator precedence: Operator precedence defines the order in which various
operators are evaluated. The table below shows the order of precedence for
java operators, from highest to lowest.

Highest Precedence
() [] .
++ -- ~ !
* / %
+ -
>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest Precedence
21. Definitions of Class, Object and Instance variable.
Class: A class is a group of objects of similar type. It is a template or blueprint
from which objects are created.
Syntax:
class <class_name>
{Data-members;
Member-methods;
}

Example:
Class Cube
{ int length;
int breadth;
int height;
Cube(int x, int y, int z) { length = x; width=y; height=z;}
int getVol( )
{ int vol;
vol = length*breadth*height;
return vol;
}
}
Object: Object is an instance of a class created using a new operator. The new
operator returns a reference to a new instance of a class. This reference can be
assigned to a reference variable of the class. The process of creating objects
from a class is called instantiation. An object encapsulates data and methods.
For example, the creation of object of the class Cube is:
Cube cubeObj; // Creating a Cube Reference
cubeObj = new Cube; // Creates an object of Cube.
Instance Variable: A variable that is created inside the class but outside the
method is known as instance variable. Instance variable doesn't get memory at
compile time. It gets memory at runtime when object (instance) is created.
That’s why, it is known as instance variable.
Note: Anonymous simply means nameless. An object that has no reference is
known as anonymous object. If you have to use an object only once,
anonymous object is a good approach.
Example from the above class definition.
System.out.println(“Volume = “+new Cube().getVol());
22. What is a constructor? Explain different forms of constructors with examples?
Constructor in java is a special type of method that is used to initialize the
objects. Java constructor is invoked at the time of object creation. It constructs
the values. There are two rules defined for the constructor.
i. Constructor name must be same as its class name.
ii. Constructor must have no explicit return type.
Types of Constructors
a. Default constructor (Constructor without parameters): A
constructor that has no parameters is called as Default constructor.
The default constructor provides the default values to the object.
Example:
class Cube
{ int length;
int breadth;
int height;
void display( )
{ System.out.println("length = "+length);
System.out.println("breadth = "+breadth);
System.out.println("height = "+height);
}
public static void main(String args[ ])
{ Cube objcube = new Cube( );
objcube.display( );
}
}

Output: length = 0
breadth = 0
height = 0
Explanation: In the above class, you are not creating any
constructor so compiler provides you a default constructor. Here 0
values are provided by default constructor. Once you define your
own constructor, the default constructor is no long used.
b. Parameterized constructor: A constructor that has parameters is
known as parameterized constructor. It is used to provide different
values to the distinct objects.
Example:
class Cube
{ int length;
int breadth;
int height;
Cube(int x, int y, int z)
{
length =x;
breadth = y;
height = z;
}
void display( )
{ System.out.println("length = "+length);
System.out.println("breadth = "+breadth);
System.out.println("height = "+height);
}
public static void main(String args[ ])
{Cube objcube = new Cube(5, 6, 7);
objcube.display( );
}
}
Output: length = 5
breadth = 6
height = 7
23. Explain in brief about Constructor Overloading in Java with an example.
Constructor overloading is a technique in Java in which a class can have any
number of constructors that differ in parameter lists. The compiler
differentiates these constructors by taking into account the number of
parameters in the list and their type. For example,
Class Cube
{ int length;
int breadth;
int height;
Cube(int x, int y, int z)
{ length =x;
breadth = y;
height = z;
}
Cube(int x, int y)
{ length =x;
breadth = y;
}
}
24. Define the following: a) this b) Garbage Collection c) finalize( )
a) this is a keyword used to refer an object that invokes the method. this can
be used inside any method to refer to the current object.
Cube(int x, int y)
{ this.length =x;
this.breadth = y;
}
b) Garbage Collection: In java, garbage means unreferenced objects. Garbage
collection is a process of reclaiming the runtime unused memory
automatically. It is a way to destroy the unused objects. It makes java memory
efficient.
c) Finalize: Sometimes an object will need to perform some action when it is
destroyed. For example, if an object is holding some non-java resource such as
a file handler or window character font, then you might want to make sure
these resources are freed before an object is destroyed. To handle such
situation, java provides a mechanism called finalization. The general form of
finalize is:
protected void finalize( )
{
// finalization code
}

25. What is static? Explain Static variable, static method and static class.
Static: The static keyword in java is used mainly for memory management.

We can apply this keyword to variables, methods, blocks and nested classes.

Static variables (or) class variables: if declare any variable as static is


called staic variable or class variable. The static variables gets
memory only once in class area at the time of class loading. So, it is
the common property of all objects. For Example,
class Students
{
int rollno;
String name;
static String college ="GIT";
Students(int r,String n)
{
rollno = r;
name = n;
}
}

Static Method (or) class Method: if you apply static keyword with
any method, it is known as static method. It has
 A static method belongs to the class rather than object of a class.

 A static method can be invoked without object of the class.

 Static method can access static data member and can change the
value of it.

For example:
class StuStatic
{ int rollno;
String name;
static String college = "GIT";
static void change()
{ college = "GITAM GIT";
}
StuStatic(int r, String n)
{rollno = r;
name = n;
}
void display ()
{System.out.println(rollno+" "+name+"\t"+college);
}
public static void main(String args[])
{ StuStatic s1 = new StuStatic (101,"Sai");
StuStatic s2 = new StuStatic (102,"Teja");
StuStatic s3 = new StuStatic (103,"Srinivas");
s1.display();
s2.display();
s3.display();
StuStatic.change();
System.out.println("After changing college");
s1.display();
s2.display(); s3.display();
}
}
Static Class or static nested class: Java allows us to define a new
class within another class. Such a new class is called a nested class.
The class which enclosed nested class is known as Outer class. In
java, we can’t make Top level (outer) class as static. Only nested
classes can be making as static. Static class cannot access non-static
data members and methods. Static class can access static members of
outer class including private.

For example:
class Outer
{static int data=30;
static class Inner
{ void msg( )
{System.out.println("data is "+data);
}
}
public static void main(String args[ ])
{TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg( );
}
}
26. Explain java’s access specifiers.
Encapsulation provides important attribute: Access Control. Through
encapsulation you can control what part of a program can access the members
of a class. By controlling access, you can prevent misuse. Java’s access
specifiers/modifiers are public, protected and private.
Public – It is accessible from all other classes. A class within another
class is called inner class. Inner class cannot have the public access
Friendly/Default Access – when no access modifier is specified, the
member default to a limited version of public accessibility known as
friendly level of access. The difference between the public and the
friendly access is that the public modifier makes fields visible in all
classes, regardless of their packages while the friendly access makes
fields visible only in the same package, but not in other packages.
Protected – The visibility level of a protected field lies in between the
public access and friendly access. The protected modifier makes the
field visible not only to all classes and subclasses in the same package
but also to subclasses in other packages. Non-subclasses in other
packages cannot access the protected members.
Private – They are accessible only with their own class. They cannot
be inherited by subclasses and therefore not accessible in subclasses.
Private Protected Access - A field can be declared with two
keywords private and protected together like:
prevate protected int codeNumber;
This gives a visibility level in between the protected access and
private access. This modifier makes the field visible in all subclasses
regardless of what package they are in. Remember, these fields are not
accessible by other classes in the same package.
Outside
Access Within Within package by Outside
modifier Class Package subclass Package
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
27. Defining the following: a) Recursion b) final
Recursion: Recursion is the process of defining something in terms of itself. A
method that calls by itself is said to be recursion. For example,
int fact(int n)
{ int result;
if (n == 1) return 1;
else result = fact(n-1)*n;
return result;
}

final: The final keyword in java is used to restrict the user. It can be used in
many contexts. Final can be: 1.variable 2.method 3.class.
i. Final variable: Final variables are nothing but constants. We cannot
change the value of a final variable once it is initialized. For example,
final int maxvalue = 25;
Note: A final variable that is not initialized at the time of declaration is
known as blank final variable. We must initialize the blank final variable
in constructor of the class otherwise it will throw a compiler error.
ii. Final method: A final method cannot be overridden.
For example:
class XYZ
{ final void demo( )
{ System.out.println(“XYZ Class Method”);}
}
class ABC extends XYZ
{ void demo( ) // Compiler Error
{ System.out.println(“ABC Class method”); }
public static void main(String args[ ])
{ ABC obj =new ABC();
obj.demo();
}
}

iii. Final class: we cannot extend a final class.

You might also like