0% found this document useful (0 votes)
27 views38 pages

Notes Java

Uploaded by

faizalanother
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
27 views38 pages

Notes Java

Uploaded by

faizalanother
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 38

UNIT-I

Unit I
4 - Marks :
1. Write about Java platform.
Java is a programming language and a computing platform for application development. It was first
released by Sun Microsystem in 1995 and later acquired by Oracle Corporation. Java platform is a collection
of programs that help to develop and run programs written in the Java programming language. Java platform
includes an execution engine, a compiler, and a set of libraries. JAVA is platform-independent language. It is
not specific to any processor or operating system.

2. Write down the structure of Java.


A Java program consists of different sections. Some of them are mandatory but some are optional. The
optional section can be excluded from the program depending upon the requirements of the programmer.

3. Differentiate C++ and Java.

C++ Java

C++ is platform-dependent. Java is platform-independent.

C++ is mainly used for system Java is mainly used for application programming. It
programming. is widely used in window, web-based, enterprise and
mobile applications.

C++ supports the goto statement. Java doesn't support the goto statement.

C++ supports multiple inheritance. Java doesn't support multiple inheritance through
class. It can be achieved by interfaces in java.

C++ supports operator overloading. Java doesn't support operator overloading.

4. Write down the syntax of switch case statement.


Switch case statement is used when we have number of options (or choices) and we may need to perform a
different task for each choice.
The syntax of Switch case statement looks like this –
switch (variable or an integer expression)
{
case constant:
//Java code
;
case constant:
//Java code
;
default:
//Java code
;
}

5. What is an array? Write an example.


An array stores a sequence of values that are all of the same type.
Making an array in a Java program involves three distinct steps:
 Declare the array name.
 Create the array.
 Initialize the array values.
public class Largest {

public static void main(String[] args) {


int[] numArray = { 23, -34, 50, 33, 55, 43, 5, -66 };
int largest = numArray[0];

for (int num: numArray) {


if(largest < num)
largest = num;
}

System.out.println("Largest element " + largest);


}
}

6 - Marks :
6. Write short notes on Lexical issues in Java.
There are many atomic elements of Java. Java programs are a collection of whitespace, identifiers,
comments, literals, operators, separators and keywords.

Whitespace:
Java is a free-form language. It means we do not need to follow any special indentation rules. In java whitespace is
a space, tab, or newline.

Identifiers:
Identifiers are used for class names, method names and variable names.
An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
dollor-sign characters.
Eg: AvgTemp, count, $calculate, s5, value_display
An identifier must not begin with a number because it leads to invalid identifier.
Eg: 5s, yes/no
Literals:
A constant value in Java is created by using a literal representation. A literal is allowed to use anywhere in the
program.
Eg: Integer literal : 100
Floating-point literal : 98.6
Character literal : ‘s’
String literal : “sample”
Comments:
The contents of a comment are ignored by the compiler. In java there are three types of comments. They
are single-line, multi-line and documentation comment.
Single-line comment: Two slashes characters are the single-line comment i.e. //. This type of comment
is called a "slash-slash" comment
// This comment extends to the end of the line.

Multi-line comment: To add a comment of more than one line, we can precede our comment using /* and
end with delimiter */.
/*..............the multi-line comments
are given with in this comment
.....................................................*/
Documentation comment: This is a special type of comment that indicates documentation comment. This
type of comment is readable to both, computer and human. To start the comment, use /** and end with */.
/**....... Documentation comments..........*/

Separators:
Separators are used to terminate statements. In java there are few characters are used as separators . They
are, parentheses(), braces{}, brackets[], semicolon;, period., and comma,.

Keywords:
In java, a keyword has a predefined meaning in the language, because of this, programmers cannot use
keywords as names for variables, methods, classes, or as any other identifier.
Boolean.break,byte,case,catch,for,if,switch,int,etc
7. How will you declare a variable? Explain the types of variable with an example.
The value stored in a variable can be changed during program execution.A variable is only a name
given to a memory location, all the operations done on the variable effects that memory location.In Java,
all the variables must be declared before they can be used.
Basic form of a variable declaration −
data type variable [ = value][, variable [ = value] ...]

There are three kinds of variables in Java −


 Local variables : 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.
 Instance variables : Instance variables are declared in a class, but outside a method, constructor or any
block.
 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.
8. Write the features of Java.
Java is a programming language and a computing platform for application development. It was first
released by Sun Microsystem in 1995 and later acquired by Oracle Corporation. Java platform is a
collection of programs that help to develop and run programs written in the Java programming language.
o Compiled and Interpreted
o Platform Independent and portable
o Object- oriented
o Robust and secure
o Distributed
o Familiar, simple and small
o Multithreaded and Interactive
o High performance
o Dynamic and Extensible
9. List out the data types available in Java and write down their default memory size.
A data type is a scheme for representing values. An example is int which is the Integer, a data
type. Values are not just numbers, but any manner of data that a computer can process. The data type
defines the kind of data that is represented by a variable. As with the keyword class, Java data types are
case sensitive.
There are two types of data types
 primitive data type
 non-pimitive data type
In primitive data types, there are two categories
 numeric means Integer, Floating points
 Non-numeric means Character and Boolean

In non-pimitive types, there are three categories


 classes
 arrays
 interface
Data type Size Range
(byte)
byte 1 -128 to 127
boolean 1 True or false
char 2 A-Z,a-z,0-9,etc.
short 2 -32768 to 32767
Int 4 (about) -2 million to 2 million
long 8 (about) -10E18 to 10E18
float 4 -3.4E38 to 3.4E18
double 8 -1.7E308 to 1.7E308

10. What are the rules to be followed in naming the variable?


Rules:
1. Variable names are case-sensitive.
2. A variable’s name can be any legal identifier.
3. It can contain Unicode letter,Digits and Two Special Characters such as Underscore and dollar Sign.
4. Length of Variable name can be any number.
5. Its necessary to use Alphabet at the start (however we can use underscore , but do not use it )
6. White space is not permitted.
7. Special Characters are not allowed.
8. Digit at start is not allowed.
9. Variable name must not be a keyword or reserved word.

10- Marks :
11. Explain the features of Java in detail.
1. Compiled and Interpreted
Basically a computer language is either compiled or interpreted. Java comes together both these approach thus
making Java a two-stage system.
Stage 1: Java compiler translates Java code to Bytecode instructions
Stage 2: Java Interpreter generate machine code that can be directly executed by machine that
is running the Java program.
2. Platform Independent and portable
Portable: Java programs can be easily moved from one computer system to another and anywhere. Changes
and upgrades in operating systems, processors and system resources will not force any alteration in Java
programs.
Platform Independent: First way is, Java compiler generates the bytecode and that can be executed on any
machine. Second way is, size of primitive data types are machine independent.
3. Object- oriented
Java is truly object-oriented language. All program code and data exist in objects and classes.
Java comes with an extensive set of classes which are organized in packages that can be used in program by
Inheritance.
4. Robust and secure
Java is a most strong language which provides many securities to make certain reliable code.
It is design as garbage –collected language, which helps the programmers virtually from all memory
management problems.
Java also includes the concept of exception handling, which detain serious errors and reduces all kind of threat
of crashing the system.
Security is an important feature of Java and this is the strong reason that programmer use this language for
programming on Internet.
The absence of pointers in Java ensures that programs cannot get right of entry to memory location without
proper approval.
5. Distributed
Java is called as Distributed language for construct applications on networks which can contribute both data
and programs.
Java applications can open and access remote objects on Internet easily. That means multiple programmers at
multiple remote locations to work together on single task.
6. Simple and small
Java is very small and simple language. Java does not use pointer and header files, goto statements, etc. It
eliminates operator overloading and multiple inheritance.
7. Multithreaded and Interactive
Java maintains multithreaded programs.
That means we need not wait for the application to complete one task before starting next task. This feature is
helpful for graphic applications.
8. High performance
Java performance is very extraordinary for an interpreted language, majorly due to the use of intermediate
bytecode.Java architecture is also designed to reduce overheads during runtime.
The incorporation of multithreading improves the execution speed of program.
9. Dynamic and Extensible
Java is also dynamic language.
Java is capable of dynamically linking in new class, libraries, methods and objects.
Java program is support functions written in other language such as C and C++, known as native methods.
12. Briefly write about operators with an example.
An operator is symbols that specify operation to be performed may be certain mathematical and
logical operation. Operators are used in programs to operate data and variables. They frequently form a
part of mathematical or logical expressions.

Categories of operators are as follows:


1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators
Arithmetic operators:
Arithmetic operators are used to make mathematical expressions and the working out as same in algebra. Java
provides the fundamental arithmetic operators. These can operate on built in data type of Java.
Operator Importance/
significance
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo division or
remainder
Logical operators:
When we want to form compound conditions by combining two or more relations, then we can use logical
operators.
Operators Importance/
significance
|| Logical – OR
&& Logical –AND
! Logical –NOT
Relational Operators:
When evaluation of two numbers is performed depending upon their relation, assured decisions are made.
The value of relational expression is either true or false.
If A=7 and A < 10 is true while 10 < A is false.
Operator Importance/ significance
> Greater than
< Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
Assignment Operators:
Assignment Operators is used to assign the value of an expression to a variable and is also called as Shorthand
operators.
Variable_name binary_operator = expression
Simple Assignment Operator Statement with shorthand Operators
A=A+1 A+=1
A=A-1 A-=1
A=A/(B+1) A/=(B+1)
A=A*(B+1) A*=(B+1)
A=A/C A/=C
A=A%C A%=C
Conditional Operators:
The character pair ?: is a ternary operator of Java, which is used to construct conditional expressions of the
following form:
Expression1 ? Expression3 : Expression3
The operator ? : works as follows:
Expression1 is evaluated if it is true then Expression3 is evaluated and becomes the value of the conditional
expression. If Expression1 is false then Expression3 is evaluated and its value becomes the conditional
expression.
Increment and Decrement Operators:
The increment operator ++ adds 1 to a variable. Usually the variable is an integer type, but it can be a floating
point type. The two plus signs must not be split by any character. Usually they are written immediately next to
the variable.

Expression Process Example end result


A++ Add 1 to a variable after use. int A=10,B; A=11
B=A++; B=10
++A Add 1 to a variable before use. int A=10,B; A=11
B=++A; B=11
A-- Subtract 1 from a variable after use. int A=10,B; A=9
B=A--; B=10
--A Subtract 1 from a variable before use. int A=10,B; A=9
B=--A; B=9
Bit Wise Operators:
Bit wise operator execute single bit of their operands
Operator Importance/ significance
| Bitwise OR
& Bitwise AND
&= Bitwise AND assignment
|= Bitwise OR assignment
^ Bitwise Exclusive OR
<< Left shift
>> Right shift
~ One‘s complement

13. Explain the Control Structures with an example.


Introduction:
In Java, program is a set of statements and which are executed sequentially in order in which they appear

Control Structure:
In java program, control structure is can divide in three parts:
 Selection statement
 Iteration statement
 Jumps in statement

Selection Statement:
Selection statement is also called as Decision making statements because it provides the decision making
capabilities to the statements.
In selection statement, there are two types:
 if statement
 switch statement
These two statements are allows you to control the flow of a program with their conditions.

if Statement:
The “if statement” is also called as conditional branch statement.The “if statement” is a commanding decision
making statement and is used to manage the flow of execution of statements. The “if statement” is the simplest
one in decision statements.
Simple if statement:
Syntax:
If (condition)
{
Statement block;
}
Statement-a;
In statement block, there may be single statement or multiple statements. If the condition is true then statement
block will be executed. If the condition is false then statement block will omit and statement-a will be
executed.
The if…else statement:
Syntax:
If (condition)
{
True - Statement block;
}
else
{
False - Statement block;
}
Statement-a;
If the condition is true then True - statement block will be executed. If the condition is false then False -
statement block will be executed. In both cases the statement-a will always executed.
Nesting of if-else statement:
Syntax:
if (condition1)
{
If(condition2)
{
Statement block1;
}
else
{
Statement block2;
}
}
else
{
Statement block3;
}
Statement 4;
If the condition1 is true then it will be goes for condition2. If the condition2 is true then statement block1 will
be executed otherwise statement2 will be executed. If the condition1 is false then statement block3 will be
executed. In both cases the statement4 will always executed.
switch statement:
In Java, switch statement check the value of given variable or statement against a list of case values and when
the match is found a statement-block of that case is executed. Switch statement is also called as multiway
decision statement.
Syntax:
switch(condition)// condition means case value
{
case value-1:statement block1;break;
case value-2:statement block2;break;
case value-3:statement block3;break;

default:statement block-default;break;
}
statement a;
The condition is byte, short, character or an integer. value-1,value-2,value-3,…are constant and is called as
labels. Each of these values be matchless or unique with the statement. Statement block1, Statement block2,
Statement block3,..are list of statements which contain one statement or more than one statements. Case label
is always end with “:” (colon).

Iteration Statement:
The process of repeatedly executing a statements and is called as looping. The statements may be executed
multiple times (from zero to infinite number). If a loop executing continuous then it is called as Infinite loop.
Looping is also called as iterations.
In Iteration statement, there are three types of operation:
 for loop
 while loop
 do-while loop

for loop:
The for loop is entry controlled loop. It means that it provide a more concious loop control structure.
Syntax:
for(initialization;condition;iteration)//iteration means increment/decrement
{
Statement block;
}
When the loop is starts, first part(i.e. initialization) is execute. It is just like a counter and provides the initial
value of loop. But the thing is, I nitialization is executed only once. The next part( i.e. condition) is executed
after the initialization. The important thing is, this part provide the condition for looping. If the condition will
satisfying then loop will execute otherwise it will terminate.
Third part(i.e. iteration) is executed after the condition. The statements that incremented or decremented the
loop control variables.
while loop:
The while loop is entry controlled loop statement. The condition is evaluated, if the condition is true then the
block of statements or statement block is executed otherwise the block of statement is not executed.
Syntax:
While(condition)
{
Statement block;
}
do-while loop:
In do-while loop, first attempt of loop should be execute then it check the condition.
The benefit of do-while loop/statement is that we get entry in loop and then condition will check for very first
time. In while loop, condition will check first and if condition will not satisfied then the loop will not execute.
Syntax:
do
{
Statement block;
}
While(condition);
In program,when we use the do-while loop, then in very first attempt, it allows us to get enter in loop and
execute that loop and then check the condition.
14. Write a program to find the area & circumference of a circle using BufferedReader class.
import java.io.*;
public class Circle
{
final static float pi=22/7F;
public static void main(String args[])throws NumberFormatException,IOException
{
System.out.println("Enter the radius of a circle");
InputStreamReader io=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(io);
float radius=Float.parseFloat(br.readLine());
System.out.println("Area of a cricle is:"+radius*radius*pi);
System.out.println("circumference of a circle is:"+2*radius*pi);
}
}
15.Describe the characteristics of OOPs concept.
1) Class
The class is a group of similar entities. It is only an logical component and not the physical entity. For example, if
you had a class called “Expensive Cars” it could have objects like Mercedes, BMW, Toyota, etc. Its
properties(data) can be price or speed of these cars. While the methods may be performed with these cars are
driving, reverse, braking etc.
2) Object
An object can be defined as an instance of a class, and there can be multiple instances of a class in a program. An
Object contains both the data and the function, which operates on the data. For example - chair, bike, marker, pen,
table, car, etc.
3) Inheritance
Inheritance is an OOPS concept in which one object acquires the properties and behaviors of the parent object. It’s
creating a parent-child relationship between two classes. It offers robust and natural mechanism for organizing and
structure of any software.
4) Polymorphism
Polymorphism refers to the ability of a variable, object or function to take on multiple forms. For example, in
English, the verb “run” has a different meaning if you use it with “a laptop,” “a foot race, and ”business.&rdquo
Here, we understand the meaning of “run” based on the other words used along with it.The same also applied to
Polymorphism.
5) Abstraction
An abstraction is an act of representing essential features without including background details. It is a technique of
creating a new data type that is suited for a specific application. For example, while driving a car, you do not have
to be concerned with its internal working. Here you just need to concern about parts like steering wheel, Gears,
accelerator, etc.
6) Encapsulation
Encapsulation is an OOP technique of wrapping the data and code. In this OOPS concept, the variables of a class
are always hidden from other classes. It can only be accessed using the methods of their current class. For example
- in school, a student cannot exist without a class.
7) Association
Association is a relationship between two objects. It defines the diversity between objects. In this OOP concept, all
object have their separate lifecycle, and there is no owner. For example, many students can associate with one
teacher while one student can also associate with multiple teachers.
8) Aggregation
In this technique, all objects have their separate lifecycle. However, there is ownership such that child object can’t
belong to another parent object. For example consider class/objects department and teacher. Here, a single teacher
can’t belong to multiple departments, but even if we delete the department, the teacher object will never be
destroyed.
9) Composition
A composition is a specialized form of Aggregation. It is also called "death" relationship. Child objects do not have
their lifecycle so when parent object deletes all child object will also delete automatically. For that, let’s take an
example of House and rooms. Any house can have several rooms. One room can’t become part of two different
houses. So, if you delete the house room will also be deleted.
Advantages of OOPS:
 OOP offers easy to understand and a clear modular structure for programs.
 Objects created for Object-Oriented Programs can be reused in other programs. Thus it saves significant
development cost.
 Large programs are difficult to write, but if the development and designing team follow OOPS concept
then they can better design with minimum flaws.
 It also enhances program modularity because every object exists independently.
UNIT-II
4 - Marks :
1. Define class. Write the syntax for class declaration.
Definition: A class is a collection of objects of similar type. Once a class is defined, any number of objects can be
produced which belong to that class. The class is a group of similar entities. It is only an logical component and
not the physical entity. For example, if you had a class called “Expensive Cars” it could have objects like
Mercedes, BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the methods may be
performed with these cars are driving, reverse, braking etc.
Class Declaration
class classname
{

ClassBody

};

2. What are the advantages of inheritance?


 Minimize the amount of duplicate code in an application by sharing common code amongst several
subclasses.
 Inheritance can also make application code more flexible to change because classes that inherit from
a common superclass can be used interchangeably. If the return type of a method is superclass
 Reusability -- facility to use public methods of base class without rewriting the same
 Extensibility -- extending the base class logic as per business logic of the derived class
 Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived
class
 Overriding--With inheritance, we will be able to override the methods of the base class so that
meaningful implementation of the base class method can be designed in the derived class.

3. List out the rules for a Constructor.


 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 Constructors have a parameter list like methods but don’t have a return type, nor even void
 A Java constructor cannot be abstract, static, final, and synchronized

4. Does the Java supports multiple inheritance. How?


No. There is no support for multiple inheritance in java. Java doesn’t allow multiple inheritance
to avoid the ambiguity caused by it. One of the example of such problem is the diamond
problem that occurs in multiple inheritance.
diamond problem:
We will discuss this problem with the help of the diagram below: which shows multiple inheritance as
Class D extends both classes B & C. Now lets assume we have a method in class A and class
B & C overrides that method in their own way. Wait!! here the problem comes – Because D is
extending both B & C so if D wants to use the same method which method would be called (the
overridden method of B or the overridden method of C). Ambiguity. That’s the main reason why Java
doesn’t support multiple inheritance.

5. What do you mean by Abstract Class?


A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A normal
class(non-abstract class) cannot have abstract methodsAn abstract class can not be instantiated, which
means you are not allowed to create an object of it.
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

public void sound(){


System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}
6- Marks :
6. Write the usages of “this” , “super” keywords.
In java, this is a reference variable that refers to the current object.
Usage of java this keyword
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method
The super keyword in java is a reference variable which is used to refer immediate parent class object.
Usage of java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

7. Differentiate Overloading and Overriding.


Overriding methods Overloading methods
Usage context A subclass re-implements Provide multiple versions of a method with
methods inherited from a different signatures.
superclass.
Method name Must be the same.
Arguments list Must be the same. Must change the arguments lists.
Return type Must have the same return type, May have different return types.
throws clause Must not throw new or broader May throw different exceptions.
checked exceptions.
Access modifiers Must not have more restrictive May have different access modifiers.
access modifiers.
Method Which method to invoke is Which method to invoke is decided at compile
invocation decided at runtime. time.
resolution
Constructors Cannot be overridden. Can be overloaded.
Allowed methods Only inherited methods can be No restriction.
overridden.
Disallowed Static and final methods cannot No restriction.
methods be overridden.

8. Write a short note on Access specifiers in Java.


In java we have four Access Specifiers and they are listed below.
1. Public : Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields
declared as public can be accessed from any class in the Java program
2. Private : Private Specifiers achieves the lowest level of accessibility.private methods and fields can
only be accessed within the same class to which the methods and fields belong
3. Protected: Methods and fields declared as protected can only be accessed by the subclasses in other
package or any class within the package of the protected members' class
4. default(no specifier): When you don't set access specifier for the element, it will follow the default
accessibility level. There is no default specifier keyword. Classes, variables, and methods can be
default accessed.

We look at these Access Specifiers in more detail.


9. Briefly explain about static and fixed methods?
Static methods are implicitly final, because overriding is done based on the type of the object, and
static methods are attached to a class, not an object. A static method in a superclass can be shadowed
by another static method in a subclass, as long as the original method was not declared final. However,
you can't override a static method with a non-static method. In other words, you can't change a static
method into an instance method in a subclass.
10. Discuss about constructor and destructor in Java.
Constructor in Java
A constructor is basically a member function of class, which initializes the object and allocates
memory to it. Constructors can be easily identified as they are declared and defined with the same
name as that of the class. A constructor does not have any return type; so, they do not return
anything, not even ‘void’. A Constructor is always defined in the public section of a class.

Example code is:


class example{
example() {
System.out.println(“hello”);}
public static void main(String args[]){
example e=new example();}}
Destructor is not possible because java is garbage collected language.We cannot predict when an object is
destroyed.Finalize is used which is inherited method.
In java ,there is no destructor in Java. But, Java provides an effective way for memory management by
its feature Garbage collection.
Garbage collector which makes sure that the unreferenced objects are taken off the heap memory and
thereby making sure that there is enough of space on heap to store new objects to efficiently run programs.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
10 - Marks :
11. Write a program to implement String manipulation.
import java.io.*;
class Str
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Welcome to java program");
String subStr="saran";
System.out.println("String before removal:"+str);
System.out.println("subString is:"+subStr);
int a,b;
String x=str.toString();
a=x.indexOf(subStr);
b=subStr.length();
if(a!=-1)
{
str=str.delete(a,a+b);
System.out.println("After subString removal:"+str);
}
else
{
System.out.println("subString not found");
}
}
}
12. Illustrate the types of Inheritance with diagram.
1) Single Inheritance
Single inheritance is very easy to understand. When a class extends another one class only then we call it a single
inheritance. The below flow diagram shows that class B extends only one class which is A. Here A is a parent
class of B and B would be a child class of A.

Single Inheritance example program in Java


Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

2) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class. The
inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple inheritance”
is that the derived class will have to manage the dependency on two base classes.
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class,
thereby making this derived class the base class for the new class. C is subclass or child class of B and B is a child
class of A.

Multilevel Inheritance example program in Java


Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits

the same class A. A is parent class (or base class) of B,C & D
5) Hybrid Inheritance
Hybrid inheritance is a combination of Single and Multiple inheritance. A hybrid inheritance can be achieved in
the java in a same way as multiple inheritance can be!! Using interfaces. By using interfaces you can have
multiple as well as hybrid inheritance in Java.

13. Explain any five String functions with example.


The following methods are some of the most commonly used methods of String class.
1. charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output : u
2. indexOf() function returns the index of first occurrence of a substring or a character. indexOf() method has
four forms:
 int indexOf(String str) It returns the index within this string of the first occurrence of the specified
substring.
 int indexOf(int ch, int fromIndex) It returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.
 int indexOf(int ch) It returns the index within this string of the first occurrence of the specified character.
 int indexOf(String str, int fromIndex) It returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.
Example:
String str="StudyTonight";
System.out.println(str.indexOf('u'));
System.out.println(str.indexOf('t', 3));
String subString="Ton";
System.out.println(str.indexOf(subString));
System.out.println(str.indexOf(subString,7));

Output:
2
11
5
-1
3. length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());
Output : 8
4. replace() method replaces occurances of character with a specified new character.
String str = "Change me";
System.out.println(str.replace('m','M'));
Output : Change Me
5. substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);
public String substring(int begin, int end);
String str = "0123456789";
System.out.println(str.substring(4,7));
Output : 456
System.out.println(str.substring(4));
Output : 456789
6. toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output : abcdef
7. toUpperCase() method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toUpperCase());
Output : ABCDEF
8. valueOf() method is present in String class for all primitive data types and for type Object.
public class Example{
public static void main(String args[]){
int num=35;
String s1=String.valueOf(num); //converting int to String
System.out.println(s1+" I Am A String");
}}
Output: 35 I Am A String
9. toString() method returns the string representation of the object used to invoke this method. It is declared
in the Object class, hence can be overrided by any java class. (Object class is super class of all java
classes.)
public class Car {
public static void main(String args[])
{
Car c=new Car();
System.out.println(c);
}
public String toString()
{
return "This is my car object";
}
}
Output : This is my car object
14. Write a short notes on the following:
Abstract Class ii) Static Class iii) Sub Class iv) Inner Class
Abstract class:A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example abstract class
abstract class A{}
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Static class:A static class i.e. created inside a class is called static nested class in java. It cannot access non-static
data members and methods. It can be accessed by outer class name.
 It can access static data members of outer class including private.
 Static nested class cannot access non-static (instance) data member or method.
Java static nested class example with instance method
class TestOuter1{
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();
}
}
Sub class:A subclass inherits variables and methods from its superclass and can use them as if they were declared
within the subclass itself:
class Animal {
float weight;
...
void eat() {
...
}
...
}

class Mammal extends Animal {


// inherits weight
int heartRate;
...

// inherits eat()
void breathe() {
...
}
}
Inner class:Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more readable and
maintainable.
Additionally, it can access all the members of outer class including private data members and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
15. Explain Constructor Overloading and Method Overloading with suitable 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.
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25

Method Overloading
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
1) Method Overloading: changing no. of arguments
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Output:
22
33

2) Method Overloading: changing data type of arguments


1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Output:
22
24.9

Unit III
4 - Marks :
1. Outline Multithreading.
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time
than process.
Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at same
time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread

2. What is an Interface? What is the use of it?


The interface in java is a mechanism to achieve abstraction.
There can be only abstract methods in the java interface not method body.
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared
both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
There are mainly three reasons to use interface. They are given below.
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

3. What is an Error? List its types.


An exception (or exceptional event) is a problem that arises during the execution of a program. A user has entered
an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of memory.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked
exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Unchecked exceptions come in two types:
 Errors
 Runtime exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions
e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-
time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

4. What are the ways to create a Thread?


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends
Object class and implements Runnable interface
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

5. How to prevent from Dead Lock?


In some situations it is possible to prevent deadlocks. I'll describe three techniques in this text:
1. Lock Ordering
2. Lock Timeout
3. Deadlock Detection
Lock Ordering
Deadlock occurs when multiple threads need the same locks but obtain them in different order.
If you make sure that all locks are always taken in the same order by any thread, deadlocks cannot occur
Lock Timeout
Another deadlock prevention mechanism is to put a timeout on lock attempts meaning a thread trying to obtain a
lock will only try for so long before giving up. If a thread does not succeed in taking all necessary locks within the
given timeout, it will backup, free all locks taken, wait for a random amount of time and then retry. The random
amount of time waited serves to give other threads trying to take the same locks a chance to take all locks, and thus
let the application continue running without locking
Deadlock detection
Thread A may wait for Thread B, Thread B waits for Thread C, Thread C waits for Thread D, and Thread D waits
for Thread A. In order for Thread A to detect a deadlock it must transitively examine all requested locks by Thread
B. From Thread B's requested locks Thread A will get to Thread C, and then to Thread D, from which it finds one
of the locks Thread A itself is holding. Then it knows a deadlock has occurred
6 - Marks :
6. Write the usages of throw and throws.
There are many differences between throw and throws keywords. A list of differences between throw and
throws are given below:
No. Throw throws
Java throw keyword is used to explicitly throw an
1) Java throws keyword is used to declare an exception.
exception.
Checked exception cannot be propagated using throw
2) Checked exception can be propagated with throws.
only.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
You can declare multiple exceptions e.g.
5) You cannot throw multiple exceptions. public void method()throws
IOException,SQLException

7. Inner Thread – Comment on it.


Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with
each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented
by following methods of Object class:
 wait()
 notify()
 notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.
Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of
them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
8. What is a Package? What are the steps to create a package?
A package is a collection of related classes. It helps Organize your classes into a folder structure and make it
easy to locate and use them. More importantly, it helps improve re-usability.
Each package in Java has its unique name and organizes its classes and interfaces into a separate namespace, or
name group
General form of package statement is
Packagr pkg;
Pkg is name of the package
Steps to create a Java package:
1. Come up with a package name
2. Pick up a base directory
3. Make a subdirectory from the base directory that matches your package name.
4. Place your source files into the package subdirectory.
5. Use the package statement in each source file.
6. Compile your source files from the base directory.
7. Run your program from the base directory.
9. What is a Thread? Discuss about the inter thread communication.
Thread class provide constructors and methods to create and perform operations on a thread.Thread class
extends Object class and implements Runnable interface
Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with
each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented
by following methods of Object class:
 wait()
 notify()
 notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.
Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.

2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of
them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
10. Write about Try … Catch… Final… with suitable example.
1. Control flow in try-catch clause OR try-catch-finally clause
 Case 1: Exception occurs in try block and handled in catch block
 Case 2: Exception occurs in try-block is not handled in catch block
 Case 3: Exception doesn’t occur in try-block
2. try-finally clause
 Case 1: Exception occurs in try block
 Case 2: Exception doesn’t occur in try-block
Control flow in try-catch OR try-catch-finally
Exception occurs in try block and handled in catch block: If a statement in try block raised an
exception, then the rest of the try block doesn’t execute and control passes to the corresponding catch
block. After executing catch block, the control will be transferred to finally block(if present) and then rest
program will be executed.
1. Control flow in try-catch:
class GFG
{
public static void main (String[] args)
{
int[] arr = new int[4];
try
{
int i = arr[6];

System.out.println("Inside try block");


}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Exception caught in Catch
block");
}
finally
{
System.out.println("finally block executed");
}
System.out.println("Outside try-catch-finally clause");
}
}

Output:
Exception caught in Catch block
finally block executed
Outside try-catch-finally clause

10 - Marks :
11. Illustrate the use of packages with suitable example.
A package as the name suggests is a pack(group) of classes, interfaces and other packages. In java we use
packages to organize our classes and interfaces. We have two types of packages in Java: built-in packages
and the packages we can create (also known as user defined package).
Advantages of using a package in Java
These are the reasons why you should use packages in Java:
 Reusability: While developing a project in java, we often feel that there are few things that we are writing
again and again in our code. Using packages, you can create such things in form of classes inside a package
and whenever you need to perform that same task, just import that package and use the class.
 Better Organization: Again, in large java projects where we have several hundreds of classes, it is always
required to group the similar types of classes in a meaningful package name so that you can organize your
project better and when you need something you can quickly locate it and use it, which improves the
efficiency.
 Name Conflicts: We can define two classes with the same name in different packages so to avoid name
collision, we can use packages
Types of packages in Java
As mentioned in the beginning of this guide that we have two types of packages in java.
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages.
12. How to handle exceptions in java? Explain.
Exception handling is one of the most important feature of java programming that allows us to handle the
runtime errors caused by exceptions. An Exception is an unwanted event that interrupts the normal flow of the
program. When an exception occurs program execution gets terminated.
There can be several reasons that can cause a program to throw exception. For example: Opening a non-
existing file in your program, Network connection problem, bad input data provided by user etc.
Advantage of exception handling
Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a
program has bunch of statements and an exception occurs mid way after executing certain statements then the
statements after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.
Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
13. Explain interface with suitable example.
Interface looks like a class but it is not a class. An interface can have methods and variables just like the class
but the methods declared in interface are by default abstract (only method signature, no body). Also, the
variables declared in an interface are public, static & final by default.
There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
14. Discuss about thread synchronization .
When we start two or more threads within a program, there may be a situation when multiple threads try to
access the same resource and finally they can produce unforeseen result due to concurrency issues. For
example, if multiple threads try to write within a same file then they may corrupt the data because one of the
threads can override data or while one thread is opening the same file at the same time another thread might be
closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access
the resource at a given point in time. This is implemented using a concept called monitors. Each object in
Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a
lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing their task by
using synchronized blocks. You keep shared resources within this block. Following is the general form of the
synchronized statement −
Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the
synchronized statement represents.

15. Write a program to implement Java thread


class MyThread implements Runnable {
String name;
Thread t;
MyThread (String threadname){
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThread {
public static void main(String args[]) {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

Unit IV
4 - Marks :
1. Write about File Stream.
The stream in the java.io package supports many data such as primitives, object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InputStream − The InputStream is used to read data from a source.
 OutputStream − The OutputStream is used for writing data to a destination.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to
byte streams but the most frequently used classes are, FileInputStream and FileOutputStream.
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to
perform input and output for 16-bit unicode. Though there are many classes related to character streams but the
most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream
and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time
and FileWriter writes two bytes at a time
2. How to use javadoc tool?
Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in
HTML format from Java source code, which requires documentation in a predefined format.Following
is a simple example where the lines inside /*….*/ are Java multi-line comments. Similarly, the line
which preceeds // is Java single-line comment.
Example
/**
* The HelloWorld program implements an application that
* simply displays "Hello World!" to the standard output.
*
* @author Zara Ali
* @version 1.0
* @since 2014-03-31
*/

3. Outline InputStreamReader methods.


The Java.io.InputStreamReader class is a bridge from byte streams to character streams.It reads bytes
and decodes them into characters using a specified charset.
void close()
1
This method closes the stream and releases any system resources associated with it.

String getEncoding()
2
This method returns the name of the character encoding being used by this stream.

int read()
3
This method reads a single character.

int read(char[] cbuf, int offset, int length)


4
This method reads characters into a portion of an array.

boolean ready()
5
This method tells whether this stream is ready to be read.

4. Explain Applet tag with its properties.


Applet tags?
- height : Defines height of applet
- width: Defines width of applet
- align: Defines the text alignment around the applet
- alt: An alternate text to be displayed if the browser support applets but cannot run this applet
- code: A URL that points to the class of the applet
- codebase: Indicates the base URL of the applet if the code attribute is relative
- hspace: Defines the horizontal spacing around the applet
- vspace: Defines the vertical spacing around the applet
- name: Defines a name for an applet
- title: Display information in tool tip
5. Write the usage of ‘System.in’ and ‘System.out’.
System.in is used to take input from command prompt and System.out is used for output at command
prompt.
in: in stream carries data from Keyboard to CPU. Any data you type at Keyboard like notepad is carried to
CPU by this stream. Any language would like to read from Keyboard should connect to in stream. Java
connects through System class as System.in. That is System.in is implicitly connected to input mechanism
of underlying OS.
2. out: out stream of OS carries data from CPU to command prompt. Any language for output should
connect to this stream like Java connects as System.out

6 - Marks :
6. What are the possibilities to execute an Applet program?
There are two methods to run a Java applet program.
♦ Using Java compatible web browser
♦ Using Applet Viewer included with your JDK.

Using Java compatible web browser

► Open any text editor like notepad.


► Type below code
<applet code = "test" width = 400 height = 300> </applet>
[Here width is the width of your output applet window and height is the height of your output
applet window.]

►Save as a .html file in location of your java file.


♦If you want to save your html file in different location,
Change above code to:
<applet code = "your location\test" width = 400 height = 300> </applet>
Example:
<applet code = "D:\my java files\test" width = 400 height = 300> </applet>
► After successful save, open your html file with any Java compatible web browser.

Using Applet Viewer

► Normally your JDK already contain an Applet Viewer for viewing applets (Search in your jdk folder).
► For using this method, add this line of code to your java program just before of your class.
/* <applet code = "test" width = 300 height = 300> </applet> */
► Save again.
► Compile your Program.
► After successful compilation, type: appletviewer test.java to run your applet.

7. Write an Applet program to display “Hello World”.


import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="HelloWorldApplet" width=100 height=100>
</applet>
*/
public class HelloWorldApplet extends Applet{
public void paint(Graphics g){
g.drawString("Hello World", 50, 50);
}
}

8. Explain any four CharArray methods.


char[] toCharArray(): This method converts string to character array. The char array size is same as the length
of the string.
char charAt(int index): This method returns character at specific index of string. This method
throws StringIndexOutOfBoundsException if the index argument value is negative or greater than the length of
the string.
getChars(int srcBegin, int srcEnd, char dst[], int dstBegin): This is a very useful method when you want to
convert part of string to character array. First two parameters define the start and end index of the string; the
last character to be copied is at index srcEnd-1. The characters are copied into the char array starting at index
dstBegin and ending at dstBegin + (srcEnd-srcBegin) – 1.
9. What is an Applet? How it differs from Console Application?
An applet is a small Internet-based program written in Java, a programming language for the Web, which
can be downloaded by any computer. The applet is also able to run in HTML. The applet is usually
embedded in an HTML page on a Web site and can be executed from within a browser
Applications Vs. Applets
You have seen two main differences between applications and applets. Let us summarize them.
Feature Application Applet
main()
Present Not present
method
Execution Requires JRE Requires a browser like Chrome
Called as stand-alone application as application can be Requires some third party tool help like a
Nature
executed from command prompt browser to execute
cannot access any thing on the system
Restrictions Can access any data or software available on the system
except browser’s services
Requires highest security for the system as
Security Does not require any security
they are untrusted

10. List any four Math functions and explain with example.
Method Description Arguments

abs Returns the absolute value of the argument Double, float, int, long

round Returns the closed int or long (as per the argument) double or float

ceil Returns the smallest integer that is greater than or equal to the argument Double

floor Returns the largest integer that is less than or equal to the argument Double

min Returns the smallest of the two arguments Double, float, int, long

max Returns the largest of the two arguments Double, float, int, long
public class Guru99 {
public static void main(String args[]) {
int i1 = -45;
double d1 = 84.6;
double d2 = 0.45;
System.out.println("Absolute value of i1: " + Math.abs(i1));
System.out.println("Round off for d1: " + Math.round(d1));
System.out.println("Ceiling of '" + d1 + "' = " + Math.ceil(d1));
System.out.println("Floor of '" + d1 + "' = " + Math.floor(d1));
System.out.println("Minimum out of '" + d1 + "' and '" + d2 + "' = " + Math.min(d1, d2));
System.out.println("Maximum out of '" + d1 + "' and '" + d2 + "' = " + Math.max(d1, d2));
}
}

Absolute value of i1: 45


Round off for d1: 85
ceiling of '84.6' = 85.0
Floor of '84.6' = 84.0
Minimum out of '84.6' and '0.45' = 0.45
Maximum out of '84.6' and '0.45' = 84.6

10 - Marks :
11. Discuss about Graphics in Applet with suitable example.
Example of Graphics in applet:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>

12. Explain the life cycle of Applet.


Java applet inherits features from the class Applet. Thus, whenever an applet is created, it undergoes a
series of changes from initialization to destruction. Various stages of an applet life cycle are depicted in
the figure below:

When a new applet is born or created, it is activated by calling init() method. At this stage, new objects to
the applet are created, initial values are set, images are loaded and the colors of the images are set. An applet is
initialized only once in its lifetime. It's general form is:
public void init( )
{
}
Running State
An applet achieves the running state when the system calls the start() method. This occurs as soon as the applet is
initialized. An applet may also start when it is in idle state. At that time, the start() method is overridden. It's
general form is:
public void start( )
{
}
Idle State
An applet comes in idle state when its execution has been stopped either implicitly or
explicitly. An applet is implicitly stopped when we leave the page containing the currently running applet.
An applet is explicitly stopped when we call stop() method to stop its execution. It's general form is:
public void stop
{
}
Dead State
An applet is in dead state when it has been removed from the memory. This can be done by
using destroy() method. It's general form is:
public void destroy( )
{
}
13. Write a Java program to create a File.
File is a simple storage of data, in java language we call it one object belongs to Java.io package it is used to store
the name of the file or directory and also the pathname. An instance of this class represents the name of a file or
directory on the file system. Also, this object can be used to create, rename, or delete the file or directory it
represents.

import java.io.*;
public class FileExample {
public static void main(String[] args) {
boolean flag = false;
// create File object
File stockFile = new File("d://Stock/stockFile.txt");
try {
flag = stockFile.createNewFile();
} catch (IOException ioe) {
System.out.println("Error while Creating File in Java" + ioe);
}
System.out.println("stock file" + stockFile.getPath() + " created ");
}
}

14. Describe the usage of Vector Class.


The java.util.Vector class implements a growable array of objects. Similar to an Array, it contains
components that can be accessed using an integer index. Following are the important points about Vector −
 The size of a Vector can grow or shrink as needed to accommodate adding and removing items.
 Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement.
 As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface.
 Unlike the new collection implementations, Vector is synchronized.
 This class is a member of the Java Collections Framework.
Constructor & Description:
1) Vector()
2) Vector(int initialCapacity)
3) Vector(int initialCapacity, int capacityIncrement)
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
// create an empty Vector vec with an initial capacity of 4
Vector<Integer> vec = new Vector<Integer>(4);
// use add() method to add elements in the vector
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);

// let us print all the elements available in vector


System.out.println("Added numbers are :- ");

for (Integer number : vec) {


System.out.println("Number = " + number);
}
}
}

15. Explain about String Buffer Class.


StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-
length, immutable character sequences while StringBuffer represents growable and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to the end. It will
automatically grow to make room for such additions and often has more characters preallocated than are actually
needed, to allow room for growth.
StringBuffer Constructors
StringBuffer( ): It reserves room for 16 characters without reallocation.
StringBuffer s=new StringBuffer();
StringBuffer(String str): It accepts a String argument that sets the initial contents of the StringBuffer object and
reserves room for 16 more characters without reallocation.
StringBuffer s=new StringBuffer("GeeksforGeeks");
Methods
Some of the most used methods are:
 length( ) and capacity( ): The length of a StringBuffer can be found by the length( ) method, while the
total allocated capacity can be found by the capacity( ) method.
 The append() method concatenates the given argument with this string.
 The insert() method inserts the given string with this string at the given position.
 The replace() method replaces the given string from the specified beginIndex and endIndex.
 The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
 The reverse() method of StringBuilder class reverses the current string.
Code Example:
import java.io.*;
class GFG
{
public static void main (String[] args)
{
StringBuffer s=new StringBuffer("GeeksforGeeks");
int p=s.length();
int q=s.capacity();
System.out.println("Length of string GeeksforGeeks="+p);
System.out.println("Capacity of string GeeksforGeeks="+q);
}
}

Unit V
4 - Marks :
1. Define Computer Network.
A computer network is a group of computer systems and other computing hardware devices that
are linked together through communication channels to facilitate communication and resource-sharing
among a wide range of users. Networks are commonly categorized based on their characteristics

2. How to find the Host name and IP Address of the machine?


import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnKnownHostException
{
InetAddress ip=InetAddress.getByName(“www.yahoo.com”);
System.out.println(“Hostname :”+ip.getHostName();
System.out.println(“IP Address :”+ip.getHostAddress();
}
}

3.What is an Event? List the Events of MouseListener.


An event in Java is an object that is created when something changes within a graphical user interface. If a
user clicks on a button, clicks on a combo box, or types characters into a text field, etc., then an event triggers,
creating the relevant event object.
List the Events of MouseListener
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
4.What is the use of Proxy Server?
 Proxy server helps the clients to protect their important information from getting hacked by hackers.
 A Proxy server can be used to restrict certain websites to people from using your network.
 A proxy server is also used in bypassing blocked websites.
 The proxy server is also used to enhance the security and privacy level of the client’s device while
doing surfing using different proxies.
 Proxy server many times used for speeding up the browsing and access data, because of their good
cache system.
 By using a Proxy the website you access will not be able to log your real IP address, as it will log the
proxy server’s IP address instead.
 A proxy server is that its cache can serve all users. If one or more Internet sites are frequently
requested, these are likely to be in the proxy's cache, which will improve user response time.
 A proxy can also log its interactions, which can be helpful for troubleshooting.

5.Write about TCP/IP.


Transmission Control Protocol/Internet Protocol (TCP/IP) is the language a computer uses to access the
Internet. It consists of a suite of protocols designed to establish a network of networks to provide a host
with access to the Internet.
TCP/IP is responsible for full-fledged data connectivity and transmitting the data end-to-end by providing
other functions, including addressing, mapping and acknowledgment. TCP/IP contains four layers, which
differ slightly from the OSI model.
6 - Marks :
6. Where to use Adapter? Why?
Adapter class is a simple java class that an adapter class provide default implementations of all
implements an interface with only EMPTY methods in an event listener class,methods are define in
implementation .Instead of implementing interface
that class with empty body; we can override only
extends Adapter class ,we provide implementation only
required methods of that class ,by inherit that class.
for require method

7. How to create Radio Button in Java?


Radio buttons are groups of buttons in which only one button at a time can be selected. The Swing
release supports radio buttons with the JRadioButton andButtonGroup classes.
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
8. What is the difference between Frame and Panel?
Frame Panel
A resizable, movable window with title bar A region internal to a Frame or another
and close button. Panel. Not bounded by a visible
border.
It is Derived From Window It is Derived From Container.
Default layout is BorderLayout Default layout is FlowLayout.
It contains Panels. It contains component.

9. List any 8 AWT Controls .


Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java. Java
AWT components are platform-dependent. AWT is heavyweight i.e. its components are using the resources of OS.
The AWT supports the following types of controls:
 Labels
 Push buttons
 Check boxes
 Choice lists
 Lists
 Scroll bars
 Text Area
 Text Field
10. Outline types of Layouts in Java.
AWT Layout Manager Classes:
LayoutManager & Description
1. BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.
2. CardLayout
The CardLayout object treats each component in the container as a card. Only one card is visible at a time.
3. FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4. GridLayout
The GridLayout manages the components in form of a rectangular grid.
5. GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the component
vertically,horizontally or along their baseline without requiring the components of same size.
10 - Marks :
11. Explain Socket Programming with example.
Java Socket programming is used for communication between the applications running on different JRE.Java
Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and
DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number
MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
12. Write a program to implement Menu in Java.
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
13. Explain any four Listener Interfaces and its methods.
Listeners are created by implementing one or more interfaces defined by the java.awt.event Package.
Commonly used Event Listener Interfaces:
1.ActionListener : This interface defines the actionPerformed(). It is invoked when an action event
occurs.f
void actionPerformed(ActionEvent ae)
2..ItemListener:
This interface defines itemStateChanged().It is invoked
when the state of an item changes.
void itemStateChanged(ItemEvent ie)
3.KeyListener:
This interface has 3 methods.
The keyPressed() and keyReleased() are invoked when a key is pressed and released.
The keyTyped() is invoked when a character has been entered.
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
4. MouseListener:
This interface defined 5 methods.
(i).If the mouse is pressed & released at the same point mouseClicked() is invoked.
void mouseClicked(MouseEvent me)
(ii).When the mouse enters a component the mouseEntered() is called.
void mouseEntereded(MouseEvent me)
(iii).When it leaves,mouseExited() is called.
void mouseExited(MouseEvent me)
(iv) & (v) The mousePressed() & mouseReleased() are invoked when the mouse is pressed & released.
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
5.MouseMotionListener:
This interface has 2 methods. The mouseDragged() & mouseMoved() methods are invoked when the
mouse is dragged & moved multiple times.
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
14. Write a short on following AWT Controls.
(i)Button (ii) TextBox (iii) TextArea (iv) Label (v) List
(i) Button Class: The button class is used to create a labeled button that has platform independent implementation.
Button defines two types of constructors:
Button( ),Button(String str)
Methods: 1) void setLabel(String str) 2) String getLabel()
import java.awt.*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
2) TextField Class : The TextField class implements a single -line text-entry area. Text fields allow the user to
enter strings and to edit the content.
Constructors: TextField()
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
Methods: 1) String getText() 2) void setText(String str)
import java.awt.*;
class TextFieldExample
{
public static void main(String args[])
{
Frame f= new Frame("TextField Example");
TextField t1;
t1=new TextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
f.add(t1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
3) TextArea Class: The TextArea class implements a multi line region that displays text. It allows the editing of
multiple line text.
Constructors:
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
Methods:
getText( ), setText( ), getSelectedText( ), select( ), void append(String str),
void insert(String str, int index)
Example:
import java.awt.*;
public class TextAreaExample
{
public static void main(String args[])
{
Frame f= new Frame();
TextArea area=new TextArea("Welcome to javatpoint");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
4) Label Class: It is used to display a single line of read only text. The text can be changed by an application
but a user cannot edit it directly.
Constructors:
Label( ), Label(String str)

Methods:
void setText( String str), String getText( )
Example:
import java.awt.*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label L1;
L1=new Label("First Label.");
L1.setBounds(50,100, 100,30);
f.add(L1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
5) List Class: The List class represents a list of text items.,user can choose either one item or multiple items.
Constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
Methods:
getSelectedItem( ) or getSelectedIndex(),void add(String name, int index), void add(String name)
Example
import java.awt.*;
public class ListExample
{
public static void main(String args[])
{
Frame f= new Frame();
List L1=new List(5);
L1.setBounds(100,100, 75,75);
L1.add("Item 1");
L1.add("Item 2");
L1.add("Item 3");
L1.add("Item 4");
L1.add("Item 5");
f.add(L1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
15. Discuss on Layouts in Java.
Layout means the arrangement of components within the container. In other way we can say that placing the
components at a particular position within the container. The task of layouting the controls is done automatically
by the Layout Manager.
AWT Layout Manager Classes:Following is the list of commonly used controls while designing GUI using
AWT.
LayoutManager & Description
1. BorderLayout:The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.
2. CardLayout:The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
3. FlowLayout:The FlowLayout is the default layout.It layouts the components in a directional flow.
4. GridLayout:The GridLayout manages the components in form of a rectangular grid.
5. GridBagLayout:This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the components of same size.

You might also like