Java File 44214802718 2
Java File 44214802718 2
Semester: 5th
Group: 5C-8
Bhor sharma
PRACTICAL RECORD
Bhor sharma
Bhor sharma
Bhor sharma
LAB-1
Topics covered
Bhor sharma
Compilation
First, the source ‘.java’ file is passed through the compiler, which then encodes the
source code into a machine independent encoding, known as Bytecode. The content of
each class contained in the source file is stored in a separate ‘.class’ file. While
converting the source code into the bytecode, the compiler follows the following steps:
Parse: Reads a set of *.java source files and maps the resulting token sequence
into AST (Abstract Syntax Tree)-Nodes.
Enter: Enters symbols for the definitions into the symbol table.
Process annotations: If Requested, processes annotations found in the specified
compilation units.
Attribute: Attributes the Syntax trees. This step includes name resolution, type
checking and constant folding.
Flow: Performs dataflow analysis on the trees from the previous step. This
includes checks for assignments and reachability.
Desugar: Rewrites the AST and translates away some syntactic sugar.
Generate: Generates ‘.Class’ files.
Execution
The class files generated by the compiler are independent of the machine or the OS,
which allows them to be run on any system. To run, the main class file (the class that
contains the method main) is passed to the JVM, and then goes through three main
stages before the final machine code is executed.
Primitive data types - includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such as String, Arrays and Classes (you will learn more
about these in a later chapter)
Bhor sharma
Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Reading user input:
The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation.
Bhor sharma
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Strings in Java are Objects that are backed internally by a char array. Since arrays
are immutable(cannot grow), Strings are immutable as well. Whenever a change to
a String is made, an entirely new String is created.
Below is the basic syntax for declaring a string in Java programming language.
Syntax:
<String_Type> <string_variable> = “<sequence_of_string>”;
List of Experiments
Bhor sharma
26/08/20 ETCS-357
Experiment-1
Bhor sharma
Code:
import java.util.Scanner;
public class Helloworld {
System.out.println("Hello world");
}
BHOR SHARMA
44214802718
Bhor sharma
Experiment-2
Aim:- WAP to program print convert String to character using toString() and
valueOf() method.
Code:
import java.util.Scanner;
public class Stringtochar {
BHOR SHARMA
44214802718
Bhor sharma
Experiment-3
Aim:- WAP to program convert char to string.
Code:
import java.util.Scanner;
public class CharConversion {
char c ='k';
String s = Character.toString(c);
System.out.println(c);
}
BHOR SHARMA
44214802718
Bhor sharma
Experiment-4
Aim:- WAP to program convert char Array to string.
Code:
import java.util.Scanner;
public class ChartoString {
BHOR SHARMA
44214802718
Bhor sharma
Roll Number:44214802718 P a g e | 10
26/08/20 ETCS-357
Experiment-5
Aim:- WAP to program to find ASCII code of character.
Code:
import java.util.Scanner;
public class Asciicodeofchar {
BHOR SHARMA
44214802718
Bhor sharma
Roll Number:44214802718 P a g e | 11
26/08/20 ETCS-357
Experiment-6
Aim:- WAP to program to display first n prime number.
Code:
import java.util.Scanner;
public class Firstnprime {
BHOR SHARMA
44214802718
Bhor sharma
Roll Number:44214802718 P a g e | 12
LAB-2
Bhor sharma
Roll Number:44214802718 P a g e | 13
LAB-2
Topics covered
Roll Number:44214802718 P a g e | 14
BRANCHING STATEMENTS:
Branching statements are used to jump from the current executing loop.
break – Terminates the loop or switch statement and transfers execution to
the statement immediately following the loop or switch.
continue – Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
Command line arguments:
The java command-line argument is an argument i.e. passed at the time of running
the java program.
The arguments passed from the console can be received in the java program and it
can be used as an input.
So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
Bhor sharma
Roll Number:44214802718 P a g e | 15
List of Experiments
Bhor sharma
Roll Number:44214802718 P a g e | 16
02/09/20 ETCS-357
Experiment-7
Aim: WAP to check vowel or consonant using switch case.
Code:
import java.util.Scanner;
class Vowel
{
public static void main(String[ ] arg)
{
boolean isVowel=false;;
Scanner scanner=new Scanner(System.in);
System.out.println("Enter a character : ");
char ch=scanner.next().charAt(0);
scanner.close();
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : isVowel = true;
}
if(isVowel == true) {
System.out.println(ch+" is a Vowel");
}
else {
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println(ch+" is a Consonant");
else
System.out.println("Input is not an alphabet");
}
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 17
BHOR SHARMA
Bhor sharma
Roll Number:44214802718 P a g e | 18
44214802718
02/09/20 ETCS-357
Experiment-8
Aim: WAP to display first n prime numbers.
Code:
import java.util.Scanner;
public class Firstnprime {
BHOR SHARMA
Bhor sharma
Roll Number:44214802718 P a g e | 19
44214802718
02/09/20 ETCS-357
Experiment-9
Aim: WAP to check whether input is leap year or not
Code:
import java.util.Scanner;
public class Leapyear {
int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Year:");
year = scan.nextInt();
scan.close();
boolean isLeap = false;
if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else {
isLeap = false;
}
if(isLeap==true)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 20
BHOR SHARMA
44214802718
Bhor sharma
Roll Number:44214802718 P a g e | 21
02/09/20 ETCS-357
Experiment-10
Aim: Write an application that accepts 2 doubles as its command line
arguments,multiply these together and display product.
Code:
import java.util.Scanner;
import java.util.*;
public class Double {
Bhor sharma
Roll Number:44214802718 P a g e | 22
BHOR SHARMA
44214802718
Bhor sharma
Roll Number:44214802718 P a g e | 23
02/09/20 ETCS-357
Experiment-11
Aim: Write an application that accepts one command line argument
and display whether odd or even.
Code:
import java.util.Scanner;
class Odd
{
// Returns true if n is even, else odd
public static boolean isEven(int n)
{
return (n % 2 == 0);
}
BHOR SHARMA
44214802718
Bhor sharma
Roll Number:44214802718 P a g e | 24
02/09/20 ETCS-357
Experiment-12
Aim: Write an application that accepts radius as its argument and
display the area.
Code:
import java.util.Scanner;
public class Area
{
public static void main(String[] args)
{
int r;
double pi = 3.14, area;
Scanner s = new Scanner(System.in);
System.out.print("Enter radius of circle:");
r = s.nextInt();
area = pi * r * r;
System.out.println("Area of circle:"+area);
}
}
BHOR SHARMA
44214802718
09/09/20 ETCS-357
Bhor sharma
Roll Number:44214802718 P a g e | 25
LAB-3
Topics Covered
Arrays,
Methods,
Method Overloading
Java Arrays:
Normally, an array is a collection of similar type of elements which has contiguous
memory location.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C+
+, we need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We
can store primitive values or objects in an array in Java. Like C/C++, we can also
create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available
in C/C++.
Bhor sharma
Roll Number:44214802718 P a g e | 26
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Methods:
A Java method is a collection of statements that are grouped together to perform an
operation. When you call the System.out.println() method, for example, the system
actually executes several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values,
invoke a method with or without parameters, and apply method abstraction in the
program design.
Creating Method
Roll Number:44214802718 P a g e | 27
// method body
}
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of
the method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
method body − The method body defines what the method does with the
statements.
Example
Here is the source code of the above defined method called min(). This method takes
two parameters num1 and num2 and returns the maximum between the two −
/** the snippet returns the minimum between two numbers */
return min;
}
Method Calling
For using a method, it should be called. There are two ways in which a method is
called i.e., method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then returns
control to the caller in two conditions, when −
Roll Number:44214802718 P a g e | 28
The method returning value can be understood by the following example −
int result = sum(6, 9);
Method Overloading
When a class has two or more methods by the same name but different parameters, it
is known as method overloading. It is different from overriding. In overriding, a method
has the same method name, type, number of parameters, etc.
this is a keyword in Java which is used as a reference to the object of the current
class, with in an instance method or a constructor. Using this you can refer the
members of a class such as constructors, variables and methods.
Note − The keyword this is used only within instance methods or constructors
Roll Number:44214802718 P a g e | 29
Call one type of constructor (parametrized constructor or default) from other in a
class. It is known as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Variable Arguments(var-args)
JDK 1.5 enables you to pass a variable number of arguments of the same type to a
method. The parameter in the method is declared as follows −
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis (...). Only one
variable-length parameter may be specified in a method, and this parameter must be
the last parameter. Any regular parameters must precede it.
Bhor sharma
Roll Number:44214802718 P a g e | 30
This means that you cannot know when or even if finalize( ) will be executed. For
example, if your program ends before garbage collection occurs, finalize( ) will not
execute.
Bhor sharma
Roll Number:44214802718 P a g e | 31
List of Experiments
Write a program to find out the array index or position where sum of
numbers preceding the index is equals to sum of numbers succeeding the
index
Write a program that creates and initializes a four-element int array.
Calculate and display the average of its values
WAP that creates a 2d array with int values the first element should be an
array containing 32. The second array should be an array containing 500 and
300. The third element should be an array containing 39, 45 and 600.
Declare, allocate and initialize the array display it’s length and elements.
WAP to sort an array
Create a java program to implement stack and queue concept
Using the concept of method overloading Write method for calculating the
area of triangle ,circle and rectangle.
Bhor sharma
Roll Number:44214802718 P a g e | 32
Experiment-13
Aim: Write a program to find out the array index or position where
sum of numbers preceding the index is equals to sum of numbers
succeeding the index.
Code:
import java.util.Scanner;
}
int sumright[] = new int[n];
for(int i=n-2;i>=0;i--)
{
sumright[i]=sumright[i+1]+arr[i+1];
}
for(int i=0;i<n;i++)
{
if(sumleft[i]==sumright[i])
{
System.out.println(i);
return ;
Bhor sharma
Roll Number:44214802718 P a g e | 33
}
}
System.out.println(-1);
}
Bhor sharma
Roll Number:44214802718 P a g e | 34
09/09/20 ETCS-357
Experiment-14
Aim: Write a program that creates and initializes a four-element int
array. Calculate and display the average of its values.
Code:
public class Average
{
public static void main(String[] args) {
int a []={10,20,30,40};
int avg=0,sum=0;
for(int i=0;i<a.length;i++)
sum=sum+a[i];
avg=sum/(a.length);
System.out.println("Average = "+avg);
}
}
BHOR SHARMA
44214802718
09/09/20 ETCS-357
Bhor sharma
Roll Number:44214802718 P a g e | 35
Experiment-15
Aim: WAP that creates a 2d array with int values the first element
should be an array containing 32. The second array should be an array
containing 500 and 300. The third element should be an array
containing 39, 45 and 600. Declare, allocate and initialize the array
display it’s length and elements.
Code:
public class Twodarray {
Bhor sharma
Roll Number:44214802718 P a g e | 36
Bhor sharma
Roll Number:44214802718 P a g e | 37
BHOR SHARMA
44214802718
09/09/20 ETCS-357
Experiment-16
Aim: WAP to sort an array.
Code:
class Sort
{
void Sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 38
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
Bhor sharma
Roll Number:44214802718 P a g e | 39
BHOR SHARMA
44214802718
09/09/20 ETCS-357
Experiment-17
Aim: Create a java program to implement stack and queue concept.
Code 1:
class Stack {
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack
boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}
boolean push(int x)
{
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
a[++top] = x;
System.out.println(x + " pushed into stack");
Bhor sharma
Roll Number:44214802718 P a g e | 40
return true;
}
}
int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top--];
return x;
}
}
int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top];
return x;
}
}
}
class Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 41
Code 2:
import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("One");
queue.add("Two");
queue.add("Three");
queue.add("Four");
queue.add("Five");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 42
BHOR SHARMA
44214802718
09/09/20 ETCS-357
Experiment-18
Aim: Using the concept of method overloading Write method for
calculating the area of triangle ,circle and rectangle.
Code:
class Area
{
Bhor sharma
Roll Number:44214802718 P a g e | 43
void area(float x,float y, float z)
{
float s = (x+y+z)/2;
float a = s*(s-x)*(s-y)*(s-z);
System.out.println("the area of the triangle is "+Math.pow(a,
0.5)+" sq units");
}
void area(float x, float y)
{
System.out.println("the area of the rectangle is "+x*y+" sq
units");
}
void area(double x)
{
double z = 3.14 * x * x;
System.out.println("the area of the circle is "+z+" sq
units");
}
}
class Overload
{
public static void main(String args[])
{
Area ob = new Area();
ob.area(5,6,7);
ob.area(11,12);
ob.area(2.5);
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 44
BHOR SHARMA
44214802718
LAB-4
Topics Covered
Bhor sharma
Roll Number:44214802718 P a g e | 45
A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one
type. In general, class declarations can include these components, in order:
Modifiers : A class can be public or has default access (Refer this for
details).
Class name: The name should begin with a initial letter (capitalized by
convention).
Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement
more than one interface.
Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that
provides the state of the class and its objects, and methods are used to
implement the behavior of the class and its objects.
Object
It is a basic unit of Object Oriented Programming and represents the real life
entities. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the
response of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object to
interact with other objects.
Example of an object : dog
Bhor sharma
Roll Number:44214802718 P a g e | 46
Objects correspond to things found in the real world. For example, a graphics
program may have objects such as “circle”, “square”, “menu”. An online shopping
system might have objects such as “shopping cart”, “customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class. But the values of
those attributes, i.e. the state are unique for each object. A single class may have
any number of instances.
Example :
Bhor sharma
Roll Number:44214802718 P a g e | 47
As we declare variables like (type name;). This notifies the compiler that we will
use name to refer to data whose type is type. With a primitive variable, this
declaration also reserves the proper amount of memory for the variable. So for
reference variable, type must be strictly a concrete class name. In
general,we can’t create objects of an abstract class or an interface.
Dog Tuffy;
If we declare reference variable(tuffy) like this, its value will be
undetermined(null) until an object is actually created and assigned to it. Simply
declaring a reference variable does not create an object.
Constructors are used to initialize the object’s state. Like methods, a constructor
also contains collection of statements(i.e. instructions) that are executed at time
of Object creation.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables
(say length, breadth, and height). But when it comes to creating its object(i.e Box
will now exist in computer’s memory), then can a box be there with no value
defined for its dimensions. The answer is no.
Bhor sharma
Roll Number:44214802718 P a g e | 48
So constructors are used to assign values to the class variables at the time of
object creation, either explicitly done by the programmer or by Java itself (default
constructor).
class Geek
{
.......
// A Constructor
new Geek() {}
.......
}
Bhor sharma
Roll Number:44214802718 P a g e | 49
Static is a non-access modifier in Java which is applicable for the following:
1. blocks
2. variables
3. methods
4. nested classes
To create a static member(block,variable,method,nested class), precede its
declaration with the keyword static. When a member is declared static, it can be
accessed before any objects of its class are created, and without reference to any
object. For example, in below java program, we are accessing static
method m1() without creating any object of Test class.
Bhor sharma
Roll Number:44214802718 P a g e | 50
List of Experiments
WAP that creates a class circle with instance variables for the
center and the radius. Initialize and display its variables.
Modify experiment 1 to have a constructor in class to initialize its
variables.
Modify experiment 2 to show constructor overloading.
WAP to display the use of this keyword.
Write a program that can count the number of instances created for
the class.
WAP that describes a class person. It should have instance
variables to record name, age and salary. Create a person object.
Set and display its instance variables.
Bhor sharma
Roll Number:44214802718 P a g e | 51
EXPERIMENT-19
AIM: WAP that creates a class circle with instance variables for the
center and the radius. Initialize and display its variables.
Code:
public class circle {
private int x;
private int y;
private int radius;
public void setInput(int a,int b, int c) {
x = a;
y = b;
radius = c;
}
public void display() {
System.out.println("Coordinates of center are : ("+x +" , "+y+" )");
System.out.println("Radius is : " + radius);
}
Bhor sharma
Roll Number:44214802718 P a g e | 52
EXPERIMENT-20
AIM: Modify experiment 19 to have a constructor in class to initialize
its variables.
Code:
public class classModify {
private int x;
private int y;
private int radius;
public classModify()
{
x=0;
y=0;
radius=10;
}
public void setInput(int a,int b, int c) {
x = a;
y = b;
radius = c;
}
public void display() {
System.out.println("Coordinates of center are : ("+x +" , "+y+" )");
System.out.println("Radius is : " + radius);
}
Bhor sharma
Roll Number:44214802718 P a g e | 53
Bhor sharma
Roll Number:44214802718 P a g e | 54
EXPERIMENT-21
AIM: Modify experiment 20 to show constructor overloading.
Code:
public class classModifed {
private int x;
private int y;
private int radius;
public classModify1()
{
x=0;
y=0;
radius=10;
}
public classModifed(int a,int b ,int c)
{
x=a;
y=b;
radius=c;
}
public void setInput(int a,int b, int c) {
x = a;
y = b;
radius = c;
}
public void display() {
System.out.println("Coordinates of center are : ("+x +" , "+y+" )");
System.out.println("Radius is : " + radius);
}
Bhor sharma
Roll Number:44214802718 P a g e | 55
}
EXPERIMENT-22
AIM: WAP to display the use of this keyword.
Code:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Bhor sharma
Roll Number:44214802718 P a g e | 56
EXPERIMENT-23
AIM: Write a program that can count the number of instances created for
the class.
Code:
class Test {
static int noOfObjects = 0;
{
noOfObjects += 1;
}
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("GFG");
System.out.println(Test.noOfObjects);
Bhor sharma
Roll Number:44214802718 P a g e | 57
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 58
EXPERIMENT-24
AIM: WAP that describes a class person. It should have instance
variables to record name, age and salary. Create a person object. Set and
display its instance variables.
Code:
class person{
String name;
int age;
float sal;
}
class personProg
{
public static void main(String args[])
{
person pr = new person();
pr.name = "Bhor Sharma";
pr.age = 21;
pr.sal = 1000000;
System.out.println("Name of the Person is: "+pr.name);
System.out.println("Age of the Person is: "+pr.age);
System.out.println("Salary of the Person is: "+pr.sal);
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 59
Bhor sharma
Roll Number:44214802718 P a g e | 60
Bhor sharma
Roll Number:44214802718 P a g e | 61
Experiment-25
Aim: WAP to implement overriding of classes
Code:
class Parent {
void show()
System.out.println("Parent's show()");
// Inherited class
@Override
void show()
System.out.println("Child's show()");
// Driver class
class Main {
Bhor sharma
Roll Number:44214802718 P a g e | 62
// show is called
obj1.show();
// POLYMORPHISM.
obj2.show();
Bhor sharma
Roll Number:44214802718 P a g e | 63
EXPERIMENT-26
Code:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
Bhor sharma
Roll Number:44214802718 P a g e | 64
EXPERIMENT-27
Code:
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
Bhor sharma
Roll Number:44214802718 P a g e | 65
System.out.println("Max: 75Kmph");
}
}
public class Maruti800 extends Maruti{
public Maruti800()
{
System.out.println("Maruti Model: 900");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
OUTPUT:
Bhor sharma
Roll Number:44214802718 P a g e | 66
Bhor sharma
Roll Number:44214802718 P a g e | 67
EXPERIMENT-28
Code:
1.
class Animal {
@Override
public void display(){
System.out.println("I am a dog");
}
display();
super.display();
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 68
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printMessage();
}
}
2.
class Animal {
protected String type="animal";
}
class Attributes{
Bhor sharma
Roll Number:44214802718 P a g e | 69
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printType();
}
}
3.
class Animal {
Animal() {
System.out.println("I am an animal");
}
}
System.out.println("I am a dog");
}
}
class SuperConstruct{
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
Bhor sharma
Roll Number:44214802718 P a g e | 70
Bhor sharma
Roll Number:44214802718 P a g e | 71
LAB-7
TOPICS COVERED
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
o Plugin is required at client browser to execute applet.
Bhor sharma
Roll Number:44214802718 P a g e | 72
Hierarchy of Applet
Bhor sharma
Roll Number:44214802718 P a g e | 73
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Code:
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
Bhor sharma
Roll Number:44214802718 P a g e | 74
5. </body>
6. </html>
c:\>javac First.java
c:\>appletviewer First.java
Bhor sharma
Roll Number:44214802718 P a g e | 75
Experiment-29
Code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class First extends Applet{
public void init()
{
setBackground(Color.BLACK);
setForeground(Color.blue);
}
public void paint(Graphics g){
g.drawString("Hello world",150,150);
showStatus("Bhor Sharma 44214802718");
}
}
Output:
Bhor sharma
Roll Number:44214802718 P a g e | 76
Bhor sharma
Roll Number:44214802718 P a g e | 77
Experiment – 30
Code:
import java.applet.Applet;
import java.awt.*;
import java.util.*;
public class analogClock extends Applet {
@Override
public void init()
{
// Applet window size & color
this.setSize(new Dimension(800, 400));
setBackground(new Color(50, 50, 50));
new Thread() {
@Override
public void run()
{
while (true) {
repaint();
delayAnimation();
}
}
}.start();
}
// Animating the applet
private void delayAnimation()
{
try {
// Animation delay is 1000 milliseconds
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
// Paint the applet
@Override
public void paint(Graphics g)
Bhor sharma
Roll Number:44214802718 P a g e | 78
{
// Get the system time
Calendar time = Calendar.getInstance();
int hour = time.get(Calendar.HOUR_OF_DAY);
int minute = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
// 12 hour format
if (hour > 12) {
hour -= 12;
}
// Draw clock body center at (400, 200)
g.setColor(Color.white);
g.fillOval(300, 100, 200, 200);
// Labeling
g.setColor(Color.black);
g.drawString("12", 390, 120);
g.drawString("9", 310, 200);
g.drawString("6", 400, 290);
g.drawString("3", 480, 200);
// Declaring variables to be used
double angle;
int x, y;
// Second hand's angle in Radian
angle = Math.toRadians((15 - second) * 6);
// Position of the second hand
// with length 100 unit
x = (int)(Math.cos(angle) * 100);
y = (int)(Math.sin(angle) * 100);
// Red color second hand
g.setColor(Color.red);
g.drawLine(400, 200, 400 + x, 200 - y);
// Minute hand's angle in Radian
angle = Math.toRadians((15 - minute) * 6);
// Position of the minute hand
// with length 80 unit
x = (int)(Math.cos(angle) * 80);
y = (int)(Math.sin(angle) * 80);
// blue color Minute hand
g.setColor(Color.blue);
g.drawLine(400, 200, 400 + x, 200 - y);
// Hour hand's angle in Radian
Bhor sharma
Roll Number:44214802718 P a g e | 79
angle = Math.toRadians((15 - (hour * 5)) * 6);
// Position of the hour hand
// with length 50 unit
x = (int)(Math.cos(angle) * 50);
y = (int)(Math.sin(angle) * 50);
// Black color hour hand
g.setColor(Color.black);
g.drawLine(400, 200, 400 + x, 200 - y);
}
}
OUTPUT:
Bhor sharma
Roll Number:44214802718 P a g e | 80