Notes Java
Notes Java
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.
C++ Java
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.
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] ...]
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.
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) 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.
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.
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() {
...
}
...
}
// 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);}
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
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) 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];
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.
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
*/
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.
boolean ready()
5
This method tells whether this stream is ready to be read.
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.
► 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.
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));
}
}
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>
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 ");
}
}
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
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.