You are on page 1of 84

JAVA PROGRAMMING LAB

Student name: Bhor Sharma

Roll No.: 44214802718

Semester: 5th

Group: 5C-8

Maharaja Agrasen Institute of Technology, PS

Bhor sharma

Roll Number:44214802718 Page |1


JAVA PROGRAMMING LAB

PRACTICAL RECORD

PAPER CODE : ETCS-357


Name of the student :BHOR SHARMA
University Roll No. : 44214802718
Branch : CSE
Section/ Group : 5C-8
PRACTICAL DETAILS

Exp. no Experiment Name Date of Date of Remarks Marks


performance checking
(10)

1 WAP to program print “Hello 26/08/20


world” on the screen

2 WAP to program print convert 26/08/20


String to character using toString()
and valueOf() method

3 WAP to program convert char to 26/08/20


string

4 WAP to program convert char 26/08/20


Array to string

5 WAP to program to find ASCII 26/08/20


code of character

6 WAP to program to display first n 26/08/20


prime number

7 WAP to check vowel or consonant 02/09/20


using switch case

Bhor sharma

Roll Number:44214802718 Page |2


Exp. no Experiment Name Date of Date of Remarks Marks
performance checking
(10)

8 WAP to display n prime numbers 02/09/20


using command line

9 WAP to check whether the input 02/09/20


year is leap or not

10 Write an application that accepts 02/09/20


two doubles as its command line
arguments, multiply these together
and display the product

11 Write an application that accepts one 02/09/20


command line argument, display the
line of reporting if number is even or
odd

12 Write an application that accepts 02/09/20


radius of a circle as its command
line argument display the area

13 Write a program to find out the array 09/09/20


index or position where sum of
numbers preceding the index is
equals to sum of numbers
succeeding the index

14 Write a program that creates and 09/09/20


initializes a four-element int array.
Calculate and display the average of
its values

15 WAP that creates a 2d array with int 09/09/20


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.

Bhor sharma

Roll Number:44214802718 Page |3


16 WAP to sort an array 09/09/20

17 Create a java program to implement 09/09/20


stack and queue concept

18 Using the concept of method 09/09/20


overloading Write method for
calculating the area of
triangle ,circle and rectangle.

19 WAP that creates a class circle with 16/09/20


instance variables for the center and
the radius. Initialize and display its
variables.

20 Modify experiment 19 to have a 16/09/20


constructor in class to initialize its
variables.

21 Modify experiment 20 to show 16/09/20


constructor overloading.

22 WAP to display the use of this 16/09/20


keyword.

23 Write a program that can count the 16/09/20


number of instances created for the
class.

24 WAP that describes a class person. 16/09/20


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 Page |4


LAB-1

1. Basic concept of java programming.


2. Compilation and Execution process.
3. Data types.
Bhor sharma

Roll Number:44214802718 Page |1


4. Operators.
5. Reading user input.
6. Strings.

LAB-1
Topics covered

 Basic concept of Java programming,


 Compilation and Execution Process,

Bhor sharma

Roll Number:44214802718 Page |2


 Data Types,
 operators,
 Reading user input,
 Strings

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.

Data types are divided into two groups:

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

Roll Number:44214802718 Page |3


Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no
additional methods.

There are eight primitive data types in Java:

Data Type Size Description


byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -263 to 263
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values

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

Roll Number:44214802718 Page |4


Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:

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

Roll Number:44214802718 Page |5


 WAP to program print “Hello world” on the screen
 WAP to program print convert String to character using toString() and
valueOf() method
 WAP to program convert char to string
 WAP to program convert char Array to string
 WAP to program to find ASCII code of character
 WAP to program to display first n prime number

26/08/20 ETCS-357

Experiment-1

Bhor sharma

Roll Number:44214802718 Page |6


Aim:- WAP to program print “Hello world” on the screen.

Code:

import java.util.Scanner;
public class Helloworld {

public static void main(String[] args) {

System.out.println("Hello world");
}

BHOR SHARMA
44214802718

Bhor sharma

Roll Number:44214802718 Page |7


26/08/20 ETCS-357

Experiment-2
Aim:- WAP to program print convert String to character using toString() and
valueOf() method.
Code:
import java.util.Scanner;
public class Stringtochar {

public static void main(String[] args) {


String a="abc";
for (int i = 0; i < a.length(); i++) {
System.out.println(a.charAt(i));
}

BHOR SHARMA
44214802718

Bhor sharma

Roll Number:44214802718 Page |8


26/08/20 ETCS-357

Experiment-3
Aim:- WAP to program convert char to string.
Code:
import java.util.Scanner;
public class CharConversion {

public static void main(String[] args){

char c ='k';
String s = Character.toString(c);
System.out.println(c);
}

BHOR SHARMA
44214802718
Bhor sharma

Roll Number:44214802718 Page |9


26/08/20 ETCS-357

Experiment-4
Aim:- WAP to program convert char Array to string.
Code:
import java.util.Scanner;
public class ChartoString {

public static void main(String[] args) {

char arr[]= new char[10];


for(int i=0;i<10;i++)
{
arr[i]=(char)('a'+i);
}
String ans="";
for(int i=0;i<10;i++)
{
ans+=arr[i];
}
System.out.println(ans);

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 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);


char c = s.next().charAt(0);
System.out.println((int)c);

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 {

public static void main(String[] args) {


Scanner s = new Scanner(System.in);
int n= s.nextInt();
boolean prime[]= new boolean[n+1];
for(int i=0;i<n;i++)
{
prime[i]=true;
}
prime[0]=false;
prime[1]=false;
for(int i=2;i<=Math.sqrt(n);i++)
{
if(prime[i])
{
for(int j=i*i;j<=n;j+=i)
{
prime[j]=false;
}
}
}
for(int i=0;i<n;i++)
{
if(prime[i])
{
System.out.print(i+" ");
}
}

BHOR SHARMA
44214802718
Bhor sharma

Roll Number:44214802718 P a g e | 12
LAB-2

1. Java Control statements.


2. Control line arguments.

Bhor sharma

Roll Number:44214802718 P a g e | 13
LAB-2
Topics covered

 Java Control statements,


 Command line arguments

JAVA CONTROL STATEMENTS :


The Java control statements inside a program are usually executed sequentially.
Sometimes a programmer wants to break the normal flow and jump to another
statement or execute a set of statements repeatedly.
Control statements in java which breaks the normal sequential flow of the program
are called control statements.
Control statements in java enables decision making, looping and branching.
DECISION MAKING STATEMENTS:
These statements decides the flow of the execution based on some conditions.
 If then
 If then else
 switch
LOOPS CONTROL STATEMENT:
Loop control statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that were created in that
scope are destroyed.
Statements inside a loop are executed repeatedly provided with some condition
which terminates the loop.
 for – For loop executes a set of statements repeatedly until a specified
condition evaluates to false.
 while & do while – Do while loop is similar to that of the while loop except
that the condition is evaluated at the end of the loop in do-while whereas in
while loop, it is evaluated before entering into the loop.
Bhor sharma

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

 WAP to check vowel or consonant using switch case


 WAP to display n prime numbers using command line
 WAP to check whether the input year is leap or not
 Write an application that accepts two doubles as its command line
arguments, multiply these together and display the product
 Write an application that accepts one command line argument, display the
line of reporting if number is even or odd
 Write an application that accepts radius of a circle as its command line
argument display the area

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 {

public static void main(String[] args) {


Scanner s = new Scanner(System.in);
int n= s.nextInt();
boolean prime[]= new boolean[n+1];
for(int i=0;i<n;i++)
{
prime[i]=true;
}
prime[0]=false;
prime[1]=false;
for(int i=2;i<=Math.sqrt(n);i++)
{
if(prime[i])
{
for(int j=i*i;j<=n;j+=i)
{
prime[j]=false;
}
}
}
for(int i=0;i<n;i++)
{
if(prime[i])
{
System.out.print(i+" ");
}
}

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 {

public static void main(String[] args) {

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 {

public static void main(String[] args) {

/* This reads the input provided by user


* using keyboard
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");

// This method reads the number provided using keyboard


double num1 = scan.nextDouble();

System.out.print("Enter second number: ");


double num2 = scan.nextDouble();

// Closing Scanner after the use


scan.close();

// Calculating product of two numbers


double product = num1*num2;

// Displaying the multiplication result


System.out.println("Output: "+product);
}
}

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);
}

public static void main(String[] args)


{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
if(isEven(n) == true)
System.out.print("Even");
else
System.out.print("Odd");
}
}

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.

Java array is an object which contains elements of a similar data type.


Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store only
a fixed set of elements in a Java array.

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

Considering the following example to explain the syntax of a method −


Syntax
public static int methodName(int a, int b) {
// body
}
Here,
 public static − modifier
 int − return type
 methodName − name of the method
 a, b − formal parameters
 int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is shown
in the following syntax −
Syntax
modifier returnType nameOfMethod (Parameter List) {
Bhor sharma

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 */

public static int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;

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 −

 the return statement is executed.


 it reaches the method ending closing brace.
The methods returning void is considered as call to a statement. Lets consider an
example −
System.out.println("This is an example");
Bhor sharma

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.

Using Command-Line Arguments


Sometimes you will want to pass some information into a program when you run it.
This is accomplished by passing command-line arguments to main( ).
A command-line argument is the information that directly follows the program's name
on the command line when it is executed. To access the command-line arguments
inside a Java program is quite easy. They are stored as strings in the String array
passed to main( ).

The this keyword

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

In general, the keyword this is used to −


 Differentiate the instance variables from local variables if they have same
names, within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}
Bhor sharma

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.

The finalize( ) Method


It is possible to define a method that will be called just before an object's final
destruction by the garbage collector. This method is called finalize( ), and it can be
used to ensure that an object terminates cleanly.
For example, you might use finalize( ) to make sure that an open file owned by that
object is closed.
To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime
calls that method whenever it is about to recycle an object of that class.
Inside the finalize( ) method, you will specify those actions that must be performed
before an object is destroyed.
The finalize( ) method has this general form −
protected void finalize( ) {
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code
defined outside its class.

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;

public class Index {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++)
{
arr[i]=s.nextInt();
}
int sumleft[] = new int[n];
for(int i=1;i<n;i++)
{
sumleft[i]=sumleft[i-1]+arr[i-1];

}
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 {

public static void main(String[] args) {


int arr[][]=new int[3][];
arr[0]=new int[1];
arr[1]=new int[2];
arr[2]=new int[3];
arr[0][0]=32;
arr[1][0]=500;
arr[1][1]=300;
arr[2][0]=39;
arr[2][1]=45;
arr[2][2]=600;
for(int i=0;i<3;i++){
for(int j=0;j<arr[i].length;j++){
System.out.println(arr[i][j]+" ");
}
System.out.println();
}
}
}

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;
}
}

void printArray(int arr[])


{
int n = arr.length;

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();
}

public static void main(String args[])


{
Sort ob = new Sort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
ob.Sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

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

 Classes and Objects


 Constructors
 Static
Classes and Objects are basic concepts of Object Oriented Programming which
revolve around the real life entities.
Class

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).

When is a Constructor called ?


Each time an object is created using new() keyword at least one constructor (it
could be default constructor) is invoked to assign initial values to the data
members of the same class.

A constructor is invoked at the time of object or instance creation. For Example:

class Geek
{
.......

// A Constructor
new Geek() {}

.......
}

// We can create an object of the above class


// using the below statement. This statement
// calls above constructor.
Geek obj = 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

class Child extends Parent {

// This method overrides show() of Parent

@Override

void show()

System.out.println("Child's show()");

// Driver class

class Main {

public static void main(String[] args)

// If a Parent type reference refers

// to a Parent object, then Parent's

Bhor sharma

Roll Number:44214802718 P a g e | 62
// show is called

Parent obj1 = new Parent();

obj1.show();

// If a Parent type reference refers

// to a Child object Child's show()

// is called. This is called RUN TIME

// POLYMORPHISM.

Parent obj2 = new Child();

obj2.show();

Bhor sharma

Roll Number:44214802718 P a g e | 63
EXPERIMENT-26

AIM: WAP to illustrate simple inheritance.

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

AIM: WAP to illustrate multilevel inheritance.

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

AIM: WAP illustrating all uses of super keywords.

Code:
1.
class Animal {

public void display(){


System.out.println("I am an animal");
}
}

class Dog extends Animal {

@Override
public void display(){
System.out.println("I am a dog");
}

public void printMessage(){

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 Dog extends Animal {


public String type="mammal";

public void printType() {


System.out.println("I am a " + type);
System.out.println("I am an " + super.type);
}
}

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");
}
}

class Dog extends Animal {


Dog() {
super();

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:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

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

As displayed in the above diagram, Applet class extends Panel.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

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).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html
file and place the applet code in html file. Now click the html file.

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>  

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is not
required but it is for testing purpose only.

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Bhor sharma

Roll Number:44214802718 P a g e | 75
Experiment-29

Aim: Write an applet that displays “Hello World” .

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

Aim: to develop an analog clock using applet.

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

You might also like