Professional Documents
Culture Documents
Programming Java Unit-1
Programming Java Unit-1
Programming Java Unit-1
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.
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.
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.
javac
java jdb
Java
progam
output
Documentation Section
Package Statement
Import Statements
Interface Statements
Class Definitions
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.
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.
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];
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;
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 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.
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();
}
}