Mailam Engineering College Oop-Cs8392 - Unit - I
Mailam Engineering College Oop-Cs8392 - Unit - I
Object Oriented Programming - Abstraction – objects and classes - Encapsulation- Inheritance - Polymorphism-
OOP in Java – Characteristics of Java – The Java Environment - Java Source File -Structure – Compilation.
Fundamental Programming Structures in Java – Defining classes in Java – constructors, methods -access
specifiers - static members -Comments, Data Types, Variables, Operators, Control Flow, Arrays , Packages -
JavaDoc comments.
Basic Concepts of OOP Definition
Objects
Objects are basic run- time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to handle. Each object has the data and
code to manipulate the data and theses objects interact with each other.
Class
The entire set of data and code of an object can be made a user-defined data type with the help of a
class. Once a class has been defined, we can create any number of objects belonging to the classes. Classes are
user-defined data types and behave like built- in types of the programming language.
Data Abstraction
Abstraction refers to the act of representing essential features without including the background details
or explanations.
Encapsulation
Wrapping up of data and function within the structure is called as encapsulation.
Inheritance
Inheritance is the process by which objects of one class acquire the properties of another class. It
supports the concept of hierarchical classification. It provides the idea of reusability. We can add additional
features to an existing class without modifying it by deriving a new class from it.
Polymorphism
Polymorphism a Greek term, means the ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of data used in the operation.
Dynamic binding or late binding
Binding refers to the linking of a procedure to the code to be executed in response to the call. Dynamic
binding means that the code associated with a given procedure call is not known until the time of the call at the
run-time.
Information Hiding (or Data Hiding)
The insulation of the data from direct access by the program is called data hiding or information hiding.
Abstract class:
Abstract class is one that is not used to create objects. An abstract class is designed only to act as a base
class. It is a design concept in program development and provides a base upon which other classes may be built.
PART – A
1) What is meant by Object Oriented Programming?
Object-oriented programming (OOP) is a programming language model organized around "objects"
rather than "actions" and data rather than logic. A program has been viewed as a logical procedure that takes
input data, processes it, and produces output data.
2) What is a Class?(Nov/Dec-18)
A class is a collection of objects that have common properties, operations and behaviours. A class is a
combination of state (data) and behaviour (methods).
A class definition starts with the keyword class followed by the class name; and the class body, enclosed
by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.
5) What is an Instance?
An instance has state, behaviour and identity. The structure and behaviour of similar classes are
defined in their common class. An instance is also called as an object.
15) What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain byte codes. These byte codes can be run
in any platform and hence java is said to be platform independent.
43. Can a java source file be saved using a name other than the class name?(April/May-2019)
Yes, you can save your java source code file with any other name, not same as your main class name but
when you compile it than byte code file name will be same as your main class name. ... And you have compile
and run a class with different name other than the filename, If you don't have any public methods in this class.
The keyword inline can be used to hint to the compiler to perform inline expansion of the body of a member or
nonmember function. To replace a function call with a copy of the function's code during compilation.
PART – B
1.Explain the basic concepts of object oriented programming in detail. (or) . Explain the
characteristics (or) Principles of OOPs.(Nov/Dec-18)(April/May-19)
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
Objects
Classes
Data abstraction and encapsulation
Inheritance
Polymorphism
Dynamic binding
Abstract Class
Objects:
Objects are the basic run-time entities in an object oriented programming. They may represent a
person, a place, a bank account or any item that the program has to handle. They may represent user-defined
data such as vectors, time and lists.
Programming problem is analyzed in terms of objects and the nature of communication between them.
Program objects should be chosen such that they match closely with the real world objects.
When a program is executed, the objects interact by sending messages to another. Each object contains
data and code to manipulate the data. Objects can interact without having to know the details of each others
data or code. It is sufficient to know the type of messageaccepted, and the type of message accepted and the
type of response returned by the objects.
Classes:
The entire set of data and code of an object can made a user defined data type with the help of a class. In
fact the objects are variable of the type class. Once class has been defined we can create any number of objects
belonging to that class.
A Class is thus a collection of objects of similar type. For example, mango, apple and orange are
members of the class fruit. Classes are user defined data type and behave like the built-in types of a
programming language.
In short, a class serves as a blueprint or a plan or a template. It specifies what data and what functions
will be included in objects of that class. Defining the class doesn’t create any objects, just as the mere existence
of a type int doesn’t create any variables.
Abstraction represents the act of representing the essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight and cost and functions to operate on these attributes. The attributes are called data
members and functions are called member functions or methods. Since the classes use the concept of
dataabstraction, they are known as Abstract Data Types (ADT).
Inheritance:
Inheritance is the process by which new classes called derived classes are created from existing classes
called base classes. The derived classes have all the features of the base class and the programmer can choose to
add new features specific to the newly created derived class. For example, a programmer can create a base class
named fruit and define derived classes as mango, orange, banana, etc. Each of these derived classes has all the
features of the base class with additional attributes or features specific to these newly created derived classes.
Mango would have its own defined features, orange would have its own defined features, banana would have its
own defined features, etc.
It is the process by which objects of one class acquire the properties of objects of another class. It
supports the concept of hierarchical classification. For example, the bird ‘robin’ is a part of the class ‘flying
bird’ which is again a part of the class ‘bird’.
This concept provides the idea of reusability. This means that we can add additional features to an
existing class without modifying it. This is possible by a deriving a new class from an existing one. The new
class will have the combined features of both the classes.
Polymorphism:
It means the ability to take more than one form. An operation may exhibit different behavior in different
instances. The behavior depends upon the types of data used in the operation. For example the operation
addition will generate sum if the operands are numbers whereas if the operands are strings then the operation
would produce a third string by concatenation.
There are two types of polymorphism, they are
1.Compile time polymorphism
2.Runtime polymorphism
i) Compile time polymorphism – The compiler selects the appropriate function for a particular call at the
compile time itself. It can be achieved by function overloading and operator overloading.
ii) Run time Polymorphism - The compiler selects the appropriate function for a particular call at the run
time only. It can be achieved using virtual functions.
The process of making an operator to exhibit different behaviors in different instances is known as
operator overloading.
A single function name can be used to handle different types of tasks based on the number and types of
arguments. This is known as function overloading.
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Linking a function call to a function code during compile time is known as static binding. Normal
functions are statically bound.
Linking a function call to a function code during runtime is known as dynamic binding. Virtual
functions are dynamically bound.
Dynamic Binding (also known as late binding) means the code associated with the given procedure call
is not known until the time of the call at run-time. It is associated with the polymorphism and inheritance. A
function call associated with a polymorphic reference depends on the dynamic type of that reference.
Abstract class:
Abstract class is one that is not used to create objects. An abstract class is designed only to act as a base
class. It is a design concept in program development and provides a base upon which other classes may be
built.
2)Describe in detail of java Buzzwords? (or) Explain the features and characteristics of
JAVA.(Nov/Dec-18) (Nov/Dec-19)
CHARACTERISTICS OF JAVA:
Java is guaranteed to be Write Once, Run Anywhere.
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.
Platform independent: Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever
platform it is being run.
Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be
easy to master.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
Architectural-neutral : Java compiler generates an architecture-neutral object file format which makes
the compiled code to be executable on many processors, with the presence of Java runtime system.
OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming. They are an
abstraction, encapsulation, inheritance, and polymorphism. Basically, Java OOP concepts let us create
working methods and variables, then re-use all or part of them without compromising security.
• Abstraction. Abstraction means using simple things to represent complexity. In Java, abstraction means
simple things like objects, classes, and variables represent more complex underlying code and data. This is
important because it lets avoid repeating the same work multiple times.
• Encapsulation. This is the practice of keeping fields within a class private, then providing access to
them via public methods. It’s a protective barrier that keeps the data and code safe within the class itself.
This way, we can re-use objects like code components or variables without allowing open access to the data
system-wide.
• Inheritance. This is a special feature of Object Oriented Programming in Java. It lets programmers
create new classes that share some of the attributes of existing classes.
• Polymorphism. This Java OOP concept lets programmers use the same word to mean different things in
different contexts. One form of polymorphism in Java is method overloading. That’s when different
meanings are implied by the code itself. The other form is method overriding. That’s when the different
meanings are implied by the values of the supplied variables.
The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java Development
Kit (JDK), a set of programming tools for developing Java applications. The Java Runtime Environment
provides the minimum requirements for executing a Java application; it consists of the Java Virtual
Machine (JVM), core classes, and supporting files.
A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Sun and other
companies.
An implementation is a computer program that meets the requirements of the JVM specification
Runtime Instance Whenever you write java command on the command prompt to run the java class,
an instance of JVM is created.
JDK – Java Development Kit (in short JDK) is Kit which provides the environment to develop and
execute(run) the Java program. JDK is a kit(or package) which includes two things
1. Development Tools(to provide an environment to develop your java programs)
2. JRE (to execute your java program).
JRE – Java Runtime Environment (to say JRE) is an installation package which provides environment
to only run(not develop) the java program(or application)onto your machine. JRE is only used by them who
only wants to run the Java Programs i.e. end users of your system.
JVM – Java Virtual machine(JVM) is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is
responsible for executing the java program line by line hence it is also known as interpreter.
Class Loader
The Class Loader loads all necessary classes needed for the execution of a program. It provides security
by separating the namespaces of the local file system from that imported through the network. These files are
loaded either from a hard disk, a network or from other sources.
The JVM puts the code through the Byte Code Verifier that checks the format and checks for an illegal
code. Illegal code, for example, is code that violates access rights on objects or violates the implementation of
pointers.
The Byte Code verifier ensures that the code adheres to the JVM specification and does not violate system
integrity.
Interpreter
o At runtime the Byte Code is loaded, checked and run by the interpreter. The interpreter has the
following two functions:
Execute the Byte Code
Make appropriate calls to the underlying hardware
JVM becomes an instance of JRE at runtime of a Java program. It is widely known as a runtime
interpreter.JVM largely helps in the abstraction of inner implementation from the programmers who make use
of libraries for their programmes from JDK.
In Java, all code must reside inside a class. By convention, the name of the main class should match the
name of the file that holds the program.
To compile the Example program, execute the compiler, javac, specifying the name of the source file
on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of the
program. The Java bytecode is the intermediate representation of your program that contains instructions the
Java Virtual Machine will execute.
To actually run the program, you must use the Java application launcher called java. To
do so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:
When Java source code is compiled, each individual class is put into its own output file named after the
class and using the .class extension. This is why it is a good idea to give your Java source files the same name
as the class they contain—the name of the source file will match the name of the .class file.
When you execute java as just shown, you are actually specifying the name of the class that you want to
execute. It will automatically search for a file by that name that has the .class extension. If it finds the file, it
will execute the code contained in the specified class.
class Example {
This line uses the keyword class to declare that a new class is being defined. Exampleis an identifier that is the
name of the class. The entire class definition, including all of itsmembers, will be between the opening curly
brace ({) and the closing curly brace (}).
The next line in the program is the single-line comment, shown here:
// Your program begins with a call to main().
The next line of code is shown here:
public static void main(String args[ ]) {
This line begins the main( ) method. All Java applications begin execution by calling main( ).
The public keyword is an access modifier, which allows the programmer to control the visibility
of class members.
When a class member is preceded by public, then that member may be accessed by code outside
the class in which it is declared.
In this case, main( ) must be declared as public, since it must be called by code outside of its
class when the program is started.
The keyword static allows main( ) to be called without having to instantiate a particular instance
of the class.
The keyword void simply tells the compiler that main( ) does not return a value.
In main( ), there is only one parameter, String args[ ] declares a parameter named args, which
is an array of instances of the classString. Objects of type String store characterstrings. In this
case, args receives any command-line arguments present when the programis executed.
The last character on the line is the {. This signals the start of main( )’s body. All of thecode that
comprises a method will occur between the method’s opening curly brace and itsclosing curly
brace.
The next line of code is shown here. Notice that it occurs inside main( ).
This line outputs the string "This is a simple Java program." followed by a new line on the screen.
Output is actually accomplished by the built-in println( ) method. In this case, println( )displays the
string which is passed to it.
As you will see, println( ) can be used to display other types of information, too. The line begins with
System.out., System is a predefined class that provides access to the system,and out is the output
stream that is connected to the console.
The first } in the program ends main( ), and the last } ends the Example class definition.
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.
The primitive types represent single values—not complex objects. Because of Java’s portability requirement,
all data types have a strictly defined range. For example, an int is always 32 bits, regardless of the particular
platform.
Integers:
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values.
Java does not support unsigned, positive-only integers.
byte:
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of
type byte are especially useful when you’re working with a stream of data from a network or file.
Byte variables are declared by use of the byte keyword.
short:
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least used Java type.
int:
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to
2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to
index arrays.
long:
long is a signed 64-bit 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.
Floating-Point Types:
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require
fractional precision.
double: Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is
actually faster than single precision on some modern processors that have been optimized for high-speed
mathematical calculations.
For example, double pi, r, a;
Characters:
In Java, the data type used to store characters is char. Java uses Unicode to represent characters. Thus, in Java
char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of
characters known as ASCII still ranges from 0 to 127.
For example, char ch1, ch2;
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true
or false.
This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required
by the conditional expressions that govern the control statements such as if and for.
For example,boolean b;
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be stored
in the reserved memory. Therefore, by assigning different data types to variables, you can store integers,
decimals, or characters in these variables.
Declaring a Variable:
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is
shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the name of the
variable. You can initialize the variable by specifying an equal sign and a value.
Dynamic Initialization:
Variables to be initialized dynamically, using any expression valid at the time the variable is declared.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}}
Types of Variable:
Local variables:
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor or block.
Instance variables:
• Instance variables are declared in a class, but outside a method, constructor or any block.
• Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object's state that must be present throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• Instance variables have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or
within the constructor.
• Instance variables can be accessed directly by calling the variable name inside the class.
Class / static variables:
• Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.
• Static variables are rarely used other than being declared as constants. Constants are variables
that are declared as public/private, final and static. Constant variables never change from
their initial value.
• Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program stops.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators:
The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean
types, but you can use them on char types, since the char type in Java is, essentially, a subset of int.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
Arithmetic Compound Assignment Operators:
Java provides special operators that can be used to combine an arithmetic operation with an assignment.
a = a + 4;
In Java, you can rewrite this statement as shown here:
a += 4;
These operators are unique in that they can appear both in postfix form, where theyfollow the operand as just
shown, and prefix form, where they precede the operand.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Java defines several bitwise operators that can be applied to the integer types, long, int, short,char, and byte.
These operators act upon the individual bits of their operands. They aresummarized in the following table:
All of the integer types are represented by binary numbers of varying bit widths. Forexample, the byte value for
42 in binary is 00101010.
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome ofeach operation. In the
discussion that follows, keep in mind that the bitwise operators are applied to each individual bit within each
operand.
Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its operand.
For example, the number 42, which has the following bit pattern:
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, thenthe resultant bit is a 1,
as shown here:
00101010 42
| 00001111 15
00101111 47
00100101 37
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:
The outcome of these operations is a boolean value. The relational operators are most frequently used in the
expressions that control the if statement and the various loop statements.
The Boolean logical operators shown here operate only on boolean operands. All of thebinary logical operators
combine two boolean values to form a resultant boolean value.
The assignment operator is the single equal sign, =. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression.
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then else statements.
This operator is the ?.
Operator Precedence:
A programming language uses control statements to cause the flow of execution to advance and branch based
on changes to the state of a program. Java’s program control statements can be put into the following
categories:
selection
iteration
jump.
Selection statements allow your program to choose different paths of execution based upon the outcome of an
expression or the state of a variable. Iteration statements enable program execution to repeat one or more
statements. Jump statements allow your program to execute in a nonlinear fashion.
The if Statement
Syntax:
if(condition) statement;
Here, condition is a Boolean expression. If condition is true, then the statement is executed.
Syntax:
if (condition) statement1;
else statement2;
The condition is any expression that returns a boolean value. The else clause is optional. If the condition is
true, then statement1 is executed. Otherwise,statement2 is executed. In no case will both statements be
executed.
Here is an example:
if(a < b)
a = 0;
else
b = 0;
Here is an example:
if(i == 10)
{
if(j < 20)
a = b;
if(k > 100)
c = d; // this if is
else a = c; // associated with this else
}
else
a = d; // this else refers to if(i == 10)
Syntax:
if(condition)
statement;
else if(condition)
.
.
.
else
statement;
Here is an example:
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
Switch:
The switch statement is Java’s multiway branch statement. The switch statement works like this: The value of
the expression is compared with each of the values in the case statements.
If a match is found, the code sequence following that case statement is executed. If none of the constants
matches the value of the expression, then the default statement is executed. However, the default statement is
optional.
Syntax:
switch (expression) {
case value1:
// statement sequence
break;
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
Here is an example:
Iteration Statements
Java’s iteration statements are for, while, and do-while. A loop repeatedly executes the same set ofinstructions
until a termination condition is met.
Syntax:
for(initialization; condition; iteration) statement;
In its most common form, the initialization portion of the loop sets a loop control variable to an initial value.
The condition is a Boolean expression that tests the loop control variable. If the outcome of that test is true, the
for loop continues to iterate. If it is false, the loop terminates. The iteration expression determines how the loop
control variable is changed each time the loop iterates.
Here is an example:
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
While Loop:
The while loop repeats a statement or block while its controlling expression is true.
Syntax:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as longas the conditional
expression is true. When condition becomes false, control passes to thenext line of code immediately following
the loop.
Here is an example:
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
Do-While Loop:
If the conditional expression controlling a while loop is initially false, then the body of the loop will not be
executed at all. However, sometimes it is desirable to execute the body of a loop at least once, even if the
conditional expression is false to begin with.
Syntax:
do {
// body of loop
} while (condition);
Here is an example:
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
Syntax:
for(type itr-var : collection) statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the
elements from a collection, one at a time, from beginning to end. The collection being cycled through is
specified by collection.
Here is an example:
class Foreach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;
}}
Jump Statements:
Java supports three jump statements: break, continue, and return. These statements transfer control to another
part of your program.
Break:
In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a
switch statement. Second, it can be used to exit a loop. Third, it can be used as a “civilized” form of goto.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Continue:
Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the
loop but stop processing the remainder of the code in its body for this particular iteration.
return
The return statement is used to explicitly return from a method. That is, it causes program control to transfer
back to the caller of the method.
At any time in a method the return statement can be used to cause execution to branch back to the caller of the
method. Thus, the return statement immediately terminates the method in which it is executed.
Classes in Java
Class - A class can be defined as a template/blue print that describes the behaviors/states that object of
its type support.
Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
The first line contains the two Java keywords "public" and "class":
The public keyword is known as an access modifier. It controls what parts of your Java program can
access your class.
The class keyword is used to declare that everything within the curly brackets is part of our class
definition. It's also followed directly by the name of the class.
Local variables: Variables defined inside methods, constructors or blocks are called local variables.
The variable will be declared and initialized within the method and the variable will be destroyed when
the method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These
variables are instantiated when the class is loaded. Instance variables can be accessed from inside any
method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method, with the
static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the above
example, barking(), hungry() and sleeping() are methods.
Creating an Object:
A class provides the blueprints for objects. So basically an object is created from a class. In Java, the
new key word is used to create new objects.
An object reference provides a handle to an object that is created and stored in memory.
The new operator returns the location of the object which you assign to a reference type.
Java Objects:
The Object Class is the super class for all classes in Java.
Example:
{
int length = 10;
int breadth = 10;
int height = 10;
public int getVolume()
{
return (length * breadth * height);
}
public static void main(String[] args)
{
Cube cubeObj; // Creates a Cube Reference
cubeObj = new Cube(); // Creates an Object of Cube
System.out.println("Volume of Cube is : " + cubeObj.getVolume());
}
}
Arrays:
The array, which stores a fixed-size sequential collection of variables (or) elements of the same type. Instead of
declaring individual variables, such as
number0, number1, ..., and number99
you declare one array variable such as
numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables.
you must declare a array variable and type of array the variable can reference.
Note:
The style dataType[] arrayRefVar is preferred.
The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to
accommodate C/C++ programmers.
Syntax:
dataType[] arrayRefVar; // Declaring
arrayRefVar = new dataType[arraySize]; // initializing size
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below:
Syntax:
dataType[] arrayRefVar =new dataType[arraySize];
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to
arrayRefVar.length-1.
One-Dimensional Arrays:
To create an array, you firstmust create an array variable of the desired type. The general form of a one-
dimensional array declaration is
Following statement declares an array variable, myList, creates an array of 10 elements of double type, and
assigns its reference to myList.:
Following picture represents array myList. Here myList holds ten double values and the indices are from 0 to 9.
Multidimensional Arrays:
In Java, multidimensional arrays are actually arrays of arrays.To declare a multidimensional array variable,
specify each additional index using another set of square brackets. For example, the following declares a
twodimensional array variable called twoD.
Processing Arrays:
When processing array elements often use either for loop or for each loop because all of the elements in an
array are of the same type and the size of the array is known.
Example:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 0; i < myList.length; i++)
{
System.out.println(myList[i] + " "); // Print all the array elements
}
double total = 0;
For example, the following method displays the elements in an int array:
can invoke it by passing an array. For example, the following statement invokes the printArray method to
display 3, 1, 2, 6, 4, and 2:
printArray(newint[]{3,1,2,6,4,2});
A method may also return an array. For example, the method shown below returns an array that is the reversal
of another array:
JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to
traverse the complete array sequentially without using an index variable.
The following code displays all the elements in the array myList:
A java constructor has the same name as the name of the class to which it belongs.
Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types.
When the constructor is invoked using the new operator, the types must match those that are specified in
the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or
initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the super class constructor using the
super () call.
Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized
constructor).
Overloaded Constructors:
Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as
the class, their signatures are differentiated by their parameter lists.
The above example shows that the Cube1 constructor is overloaded one being the default constructor
and the other being a parameterized constructor.
It is possible to use this() construct, to implement local chaining of constructors in a class.
The this() call in a constructor invokes the another constructor with the corresponding parameter list
within the same class.
Calling the default constructor to create a Cube object results in the second and third parameterized
constructors being called as well.
Java requires that any this() call must occur as the first statement in a constructor.
Below is an example of a cube class containing 3 constructors which demostrates the this() method in
Constructors context.
Example:
public class Cube2
{
int length;
int breadth;
int height;
public int getVolume()
{
return (length * breadth * height);
}
Cube2()
{
this(10, 10);
System.out.println("Finished with Default Constructor");
}
Cube2(int l, int b)
{
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having 2 params");
}
Cube2(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having 3 params");
}
Methods
Methods are similar to functions or procedures that are available in other programming languages.
Example:
public class Invoice
{
public static void main(String[] args)
{
printHeader();
System.out.println("You owe us $47.00");
}
public static void printHeader()
{
System.out.println("Mailam");
System.out.println("Engineering College");
System.out.println("Tindivanam");
}
}
Types of methods
Static methods:
Static variable is a class variable which value remains constant for the entire class.
Static method is the one which can be called with the class itself and can hold only the static variable.
←
← Example:
← class MyUtils
← {
← public static double mean(int[] p)
{ int sum = 0; // sum of all the elements
← for (int i=0; i<p.length; i++)
← {
← sum += p[i];
0 }
return ((double)sum) / p.length;
}//endmethod mean
}
1
Static Methods:
Why declare a method as static
The above mean() method would work just as well if it wasn't declared static, as long as it was called
from within the same class.
If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly)
with an object.
Even when used within the class, there are good reasons to define a method as static
Similarly, any programmer looking at the code will know that a static method can't interact with instance
variables, which makes reading and debugging easier.
Calling methods :
There are two cases.
If a method (static or instance) is called from another class, something must be given before the method
name to specify the class where the method is defined.
For instance methods, this is the object that the method will access.
For static methods,
The class name should be specified.
Eg,
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the class of the object will be used.
Method overloading:
Methods having same name but different arguments is called method overloading.
Example:
public class Overload2
{
void add(int m, int n)
{
int sum = m + n;
System.out.println( "Sum of a+b is " +sum);
}
void add(int a, int b, int c)
{
int sum = a + b + c;
System.out.println("Sum of a+b+c is " +sum);
}
}
class overloadfunc
{
public static void main(String args[])
{
Overload2 obj = new Overload2();
obj.add(4,19);
obj.add(4,17,11);
}
}
Access Specifiers:
Public
It can be accessed from anywhere in the class or packages.
Friendly
It is also known as default, the difference between public and friendly is public can be accessed from any
package whereas friendly is accessed with the packages only.
Protected
It lies between public and friendly, this makes visible all classes and sub classes with in the same package
and also to subclasses in other packages.
Private
It is the highest degree of protection, which is accessible within own class alone.
Default
Java provides a default specifier which is used when no access modifier is present. Any class, field,
method or constructor that has no declared access modifier is accessible only by classes in the same package.
The default modifier is not used for fields and methods within an interface.
Example:
Class Baseclass
{
Public int x=10;
Private int y=10;
Protected int z=10;
int a=10; //Implicit Default Access Modifier
}
Protected int getZ()
{
return z;
}
Static Variables:
We use class variables also know as Static fields when we want to share characteristics across all objects
within a class.
When you declare a field to be static, only a single instance of the associated variable is created common
to all the objects of that class. Hence when one object changes the value of a class variable, it affects all
objects of the class.
We can access a class variable by using the name of the class, and not necessarily using a reference to an
individual object within the class. Static variables can be accessed even though no objects of that class
exist. It is declared using static keyword.
Static Methods:
Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods
are often used to provide global functions for Java programs.
For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods
from inside a static method.
Ex:
Class Cube
{
int length=10;
int breadth=10;
int height=10;
public static int numOfCubes=0;//static variable
Public Cube()
{
numOfCubes++;
}
}
Public class CubeStaticTest
{
Public static void main(String args[])
{
System.out.println(“number of cube objects=”+Cube.numOfCubes);
Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating
and usage of classes, interfaces, enumerations and annotations easier etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations )
providing access protection and name space management.
Some of the existing packages in Java are:
We may like to use many of the classes contained in a package. It can be achieved by
Access a package :
The import statement can be used to search a list of packages for a particular class.
package package1 ;
public class classA
{
public void displayA()
{
System.out.println(“class A”);
}
}
Example:
An example that creates a package called animals. It is common practice to use lowercased names of packages
to avoid any conflicts with the names of classes, interfaces.
interface Animal
{
public void eat();
public void travel();
}
Now put an implementation in the same package animals:
package animals;
Then there are Javadoc comments that are unique to the Java language.
Comments in Java
Single Line Comments
Single line comments are used to add a very brief comment within some code, often a long or
complex method.
They begin with a double forward slash (//) and end with the end of line or carriage return.
EX:
private static String name = "Guys"; //The name to print
Javadoc Comments:
Javadoc Comments are specific to the Java language and provide a means for a programmer to fully
document his / her source code as well as providing a means to generate an Application Programmer
Interface (API) for the code using the javadoc tool that is bundled with the JDK.
These comments have a special format which we will discuss in this section and then in the following
section we will look at how to use the javadoc tool to generate an API.
A Javadoc comment precedes any class, interface, method or field declaration and is similar to a multi-
line comment except that it starts with a forward slash followed by two atserisks (/**).
The basic format is a description followed by any number of predefined tags.
The entrie comment is indented to align with the source code directly beneath it and it may contain any
valid HTML.
Generally paragraphs should be separated or designated with the <p> tag.
EXample:
/**
* A Container is an object that contains other objects.
* @author Trevor Miller
* @version 1.2
* @since 0.3
*/
public abstract class Container
{
/**
* Create an empty container.
*/
protected Container() { }
/**
* Return the number of elements contained in this container.
* @return The number of objects contained
*/
public abstract int count();
/**
* Clear all elements from this container.
* This removes all contained objects.
*/
public abstract void clear();
/**
* Accept the given visitor to visit all objects contained.
* @param visitor The visitor to accept
*/
public abstract void accept(final Visitor visitor);
/**
* Return an iterator over all objects conatined.
* @return An iterator over all objects
*/
public abstract Iterator iterator();
/**
* Determine whether this container is empty or not.
* @return <CODE>true</CODE> if the container is empty:
* <CODE>count == 0</CODE>, <CODE>false</CODE>
* otherwise
*/
public boolean isEmpty()
{
return (this.count() == 0);
}
/**
* Determine whether this container is full.
* @return <CODE>true</CODE> if conatiner is full,
* <CODE>false</CODE> otherwise
*/
public boolean isFull() {
return false;
}
}
The description should give a concise summary of the item being commented.
It should be written in simple and clear English using correct spelling and grammar.
Punctuation is required.
The first sentence of the description is the most important part of the entire description.
It should be a short and concise summary of the item being commented.
This is due to the fact that the Javadoc tool copies the first sentence to the appropriate class or package
summary page, which implies that the first sentence should be compact and can stand on its own.
Take a look at the example above again and you'll see that the first sentence is a brief descriptive summary of
each item.
The use of the <code> tag
The use of the <code> tag is greatly encouraged and should be used for all Java keywords, names and
code samples.
Omission of parenthesis
When referring to a method that has no parameters or a method which has multiple forms (method
overloading) it is acceptable and even encouraged to simply omit the parenthesis. Consider the following
example:
The <code>add</code> method inserts items into the vector.
This is the correct way of doing it as opposed to the incorrect way in the next example:
A method usually defines a certain behavior or operation; because of this it usually signals an action that
is best described by a verb.
Avoid abbreviation
One final word on style guidelines is to avoid the use of abbreviation at all costs as this renders
comments unclear.
Instead of using an abbreviation one should use its expanded form.
17)State the purpose of finalize() method In java? With an example explain how finalize()
method can be used in Java program.(Nov/Dec-18)
Finalize() is the method of Object class. This method is called just before an object is garbage collected.
finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory
leaks.
Syntax
protected void finalize() throws Throwable
Throw
Example
public class JavafinalizeExample1 {
public static void main(String[] args)
{
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");
}
@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}
Output:
2018699554
end of garbage collection
finalize method called
18) What are literals? Explain the types of literals supported by java. (April/May-19)
Java Literals: A literal in java refers to a fixed value that appears directly in a program. Java define five
primary types of literals. By literal we mean any number, text, or other information that represents a value.
Types of Literals:
19) Write a Java code using do while loop that counts down to 1 from 10 printing exactly ten lines of
“hello”.( April/May-2019)
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(“hello”);
i--;
}while(i>1);
}
}
ADDITIONAL PROGRAMS:
HELLOWORLD
import java.io.*;
class hello
{
public static void main(String arg[])
{
System.out.println("Hello World.");
}
}
INPUT
import java.util.*;
class Scanner_Ex
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
}
}
}
CHECK WHETHER A NUMBER IS EVEN OR ODD USING IF...ELSE STATEMENT
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = reader.nextInt();
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}
if(leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
default:
System.out.printf("Error! operator is not correct");
return;
}
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
i++;
}
status = 1;
num++;
}
}
}
import java.util.Scanner;
class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}
}
class JavaExample
{
void calculateArea(float x)
{
System.out.println("Area of the square: "+x*x+" sq units");
}
void calculateArea(float x, float y)
{
System.out.println("Area of the rectangle: "+x*y+" sq units");
}
void calculateArea(double r)
{
double area = 3.14*r*r;
System.out.println("Area of the circle: "+area+" sq units");
}
public static void main(String args[]){
JavaExample obj = new JavaExample();
obj.calculateArea(6.1f);
obj.calculateArea(10,22);
obj.calculateArea(6.1);
}
}
CLASS PROGRAM 1
class student
{
int regno;
String name;
}
public class J2aSimpleClass
{
public static void main(String args[])
{
student s=new student();
s.regno = 100;
s.name = "John Marshal";
System.out.println("Reg No " + s.regno);
System.out.println("Name " + s.name);
}
}
CLASS PROGRAM 2
import java.util.Scanner;
class students
{
private int regno;
private String name;
void getdata()
{
Scanner in = new Scanner(System.in);
System.out.println ("Enter the Register Number");
regno = in.nextInt();
System.out.println ("Enter the Name");
name = in.next();
}
void showdata()
{
System.out.println("Reg No " + regno);
System.out.println("Name " + name);
}
}
public class J2bSimpleClass
{
public static void main(String args[])
{
students s=new students();
s.getdata();
s.showdata();
//s.regno = 10; //ERROR: regno is private
}
}
CLASS PROGRAM 3
import java.util.Scanner;
class stud
{
private String name,result;
private int regno,m1,m2,m3,total;
private float percentage;
void getdata()
{
Scanner in = new Scanner(System.in);
System.out.println ("Enter the Register Number");
regno = in.nextInt();
System.out.println ("Enter the Name");
name = in.next();
class J2cSimpleClass
{ public static void main(String[] args)
{ stud s=new stud();
System.out.println ("\t\t\tStudent Information System");
s.getdata();
s.calculation();
s.show();
}
}
NOV/DEC 2018
PART-A
PART-B
April/May 2019
PART-A
1.Can a java source file be saved using a name other than the class name? ( Q.NO: 43 )
2. What are inline functions? Give examples. ( Q.NO:44 )
PART-B
(Nov/Dec-19)
PART-A