You are on page 1of 46

Amity Institute of Information Technology, Noida

Uttar Pradesh

Practical File on

Java Programming
A report submitted for the partial fulfilment of the requirement for the
bachelor’s in computer application course (2019-2022) of Amity University.

Submitted To: Submitted By:


Dr Sarvesh Tanwar Akshat Srivastava
T201 A10046619014
BCA (Evening)
1. Write a Program to print the text “Welcome to World of Java” Save it with name
Welcome java in your folder.

Source Code:
public class Welcome {

public static void main(String[] args) {

System.out.println("----------------------");

System.out.println("Welcome to World of Java");

System.out.println("----------------------");

Output:

2. Java Program to check Even or Odd number.

Source Code:
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = reader.nextInt();
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
Output:

3. Write a Java program to calculate a Factorial of a number.

Source Code:

import java.util.Scanner;

public class Factorial {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("---------------------");

System.out.print("Enter Number: ");

int num = scanner.nextInt();

scanner.close();

int fact = 1; for (int i = 1; i <= num; i++) {

fact *= i; }

System.out.println("Factorial of " + num + " is " + fact);

System.out.println("---------------------");

Output:
4. Write a Java program that counts the number of objects created by using static
variable.
Source Code:

public class FibonacciSeries {

public static void main(String[] args) {

System.out.println("---------------------");

int n = 10;

int a = 0, b = 1, c;

System.out.print(a + " " + b + " ");

for (int i = 0; i < n; i++) {

c = a + b;

a = b;

b = c;

System.out.print(c + " ");

System.out.println();

System.out.println("---------------------");

Output:

5. Write a java Program to check the number is Prime or not.


Source Code:

import java.util.Scanner;

public class PrimeOrNot {


public boolean isPrime(int num) {

for (int i = 2; i * i <= num; i++) {

if (num % i == 0) return false;

return true;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

PrimeOrNot primeOrNot = new PrimeOrNot();

System.out.println("---------------------");

System.out.print("Enter Number: ");

int num = scanner.nextInt();

scanner.close();

if(primeOrNot.isPrime(num)) System.out.println(num + " is a Prime Number");

else System.out.println(num + " is not a Prime Number");

System.out.println("---------------------");

Output:

6. Write a java program to check the given number is Armstrong Number or not.
Source Code:

public class Armstrong {

public static void main(String[] args) {

int number = 371, originalNumber, remainder, result = 0;

originalNumber = number;

while (originalNumber != 0)

{
remainder = originalNumber % 10;

result += Math.pow(remainder, 3);

originalNumber /= 10;

if(result == number)

System.out.println(number + " is an Armstrong number.");

else

System.out.println(number + " is not an Armstrong number.");

Output:

7. Write a Java program that prompts the user for an integer and then prints out all the
prime numbers up to that Integer.
Source Code:

import java.util.Scanner;

class PrimeNumbers

{ public static void main(String[] args)

{ int n;

int p;

Scanner s=new Scanner(System.in);

System.out.println("Enter a number: ");

n=s.nextInt();

for(int i=2;i<n;i++)

{ p=0;

for(int j=2;j<i;j++)
{ if(i%j==0)

p=1;

if(p==0)

System.out.println(i);

} } }

Output:

8. Write a Java program that checks whether a given string is a palindrome or not Ex:
MADAM is a palindrome.
Source Code:

class Main {

public static void main(String[] args) {

String str = "MADAM", reverseStr = "";

int strLength = str.length();

for (int i = (strLength - 1); i >=0; --i) {

reverseStr = reverseStr + str.charAt(i);

if (str.toLowerCase().equals(reverseStr.toLowerCase())) {

System.out.println(str + " is a Palindrome String.");

else {

System.out.println(str + " is not a Palindrome String.");

} } }
Output:

Write a Java program to perform basic Calculator operations


Source Code:

public class Calculator {

private static int add(int a,int b) {

return a + b;

private static int sub(int a,int b) {

return a - b;

private static int mul(int a,int b) {

return a * b;

private static float div(float a,float b) {

return a / b;

private static int mod(int a,int b) {

return a % b;

public static void main(String[] args) {

System.out.println("---------------------");

int a = 97, b = 62;

System.out.println("Addition: " + add(a, b));

System.out.println("Subtraction: " + sub(a, b));

System.out.println("Multiplication: " + mul(a, b));

System.out.println("Division: " + div(a, b));

System.out.println("Modulas: " + mod(a, b));

System.out.println("---------------------");
}

Output:

9. Write a Java program to multiply two given matrices


Source Code:

public class MatrixMultiplicationExample{

public static void main(String args[]){

//creating two matrices

int a[][]={{1,1,1},{2,2,2},{3,3,3}};

int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices

int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

c[i][j]=0;

for(int k=0;k<3;k++)

c[i][j]+=a[i][k]*b[k][j];

}//end of k loop

System.out.print(c[i][j]+" "); //printing matrix element


}//end of j loop

System.out.println();//new line }

}}

Output:

10. Write a Java program that reverses a given String

Source Code:

import java.util.Scanner;

public class ReverseString {

public static String reverseString(String str) {

String reverseStr = "";

for (int i = str.length() - 1; i >= 0; i--) {

reverseStr += str.charAt(i);

return reverseStr;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("---------------------");

System.out.print("Enter String: ");

String str = scanner.next();

scanner.close();

System.out.println("Reverse String: " + reverseString(str));


System.out.println("---------------------");

Output:

11. Write a Java program to sort the elements using bubble sort
Source Code:

public class BubbleSortExample {

static void bubbleSort(int[] arr) {

int n = arr.length;

int temp = 0;

for(int i=0; i < n; i++){

for(int j=1; j < (n-i); j++){

if(arr[j-1] > arr[j]){

//swap elements

temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

} }

public static void main(String[] args) {

int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Bubble Sort");


for(int i=0; i < arr.length; i++){

System.out.print(arr[i] + " ");

System.out.println();

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");

for(int i=0; i < arr.length; i++){

System.out.print(arr[i] + " ");

Output:

12. Write a Java program to search an element using binary search


Source Code:

class BinarySearchExample{  
 public static void binarySearch(int arr[], int first, int last, int key){  
   int mid = (first + last)/2;  
   while( first <= last ){  
      if ( arr[mid] < key ){  
        first = mid + 1;     
      }else if ( arr[mid] == key ){  
        System.out.println("Element is found at index: " + mid);  
        break;  
      }else{  
         last = mid - 1;  
      }  
      mid = (first + last)/2;  
   }  
   if ( first > last ){  
      System.out.println("Element is not found!");  
   }  
 }  
 public static void main(String args[]){  
        int arr[] = {10,20,30,40,50};  
        int key = 30;  
        int last=arr.length-1;  
        binarySearch(arr,0,last,key);     
 }  
}  
Output:

13. Write a java program that implements Array Index out of bound Exception using built-
in-Exception
Source Code:

class ArithmeticException_Demo {

public static void main(String args[])

try {

int a = 30, b = 0;

int c = a / b; // cannot divide by zero

System.out.println("Result = " + c);

catch (ArithmeticException e) {

System.out.println("Can't divide a number by 0");

}
}

Output:

14. Write a java program to identify the significance of finally block in handling exceptions
Source Code:

import java.io.*;

class GFG {

public static void main(String[] args)

{ try { System.out.println("inside try block");

// Not throw any exception

System.out.println(34 / 2);

// Not execute in this case

catch (ArithmeticException e) {

System.out.println("Arithmetic Exception");

// Always execute

finally {

System.out.println(

"finally : i execute always.");

} } }

Output:
15. Write a java program that implements user defined exception
Source Code:

class MyException extends Exception{

String str1;

/* Constructor of custom exception class

* here I am copying the message that we are passing while

* throwing the exception to a string and then displaying

* that string along with the message.

*/

MyException(String str2) {

str1=str2;

public String toString(){

return ("MyException Occurred: "+str1) ;

class Example1{

public static void main(String args[]){

try{

System.out.println("Starting of try block");

// I'm throwing the custom exception using throw

throw new MyException("This is My error Message");

}
catch(MyException exp){

System.out.println("Catch Block") ;

System.out.println(exp) ;

Output:

16. Write a Java program that displays area of different Figures (Rectangle, Square,
Triangle) using the method overloading

Source Code:

class OverloadDemo

void area(float x)

System.out.println("the area of the square is "+Math.pow(x, 2)+" 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[])

OverloadDemo ob = new OverloadDemo();

ob.area(5);

ob.area(11,12);

ob.area(2.5);

Output:

Write a java program to calculate gross salary & net salary taking the following data
Source Code:

import java.util.Scanner;

public class salary

public static void main(String args[])

double basic,da,hra,gross;

System.out.println("Enter Basic salary of the employee\n");

Scanner obj1=new Scanner(System.in);

basic=obj1.nextDouble();

da=40*basic/100;

hra=20*basic/100;

gross= basic+da+hra;

System.out.println("The D.A of the basic salary of the employee is:" +da);

System.out.println("The H.R.A of the basic salary of the employee is:" +hra);


System.out.println("The Gross salary of the employee is:" +gross);

Output:

17. Write a java program to find the details of the students eligible to enroll for the
examination (Students, Department combinedly give the eligibility criteria for the
enrolment class) using interfaces
Source Code:

import java.util.Scanner;

public class GetStudentDetails

public static void main(String args[])

String name;

int roll, math, phy, eng;

Scanner SC=new Scanner(System.in);

System.out.print("Enter Name: ");

name=SC.nextLine();

System.out.print("Enter Roll Number: ");

roll=SC.nextInt();

System.out.print("Enter marks in Maths, Physics and English: ");

math=SC.nextInt();

phy=SC.nextInt();

eng=SC.nextInt();

int total=math+eng+phy;
float perc=(float)total/300*100;

System.out.println("Roll Number:" + roll +"\tName: "+name);

System.out.println("Marks (Maths, Physics, English): " +math+","+phy+","+eng);

System.out.println("Total: "+total +"\tPercentage: "+perc);

Output:

18. . Write a java program to calculate gross salary & net salary taking the following data
Source Code:

import java.util.Scanner;

public class GrossSalary {

    static float calculateGrossSalary(int basicSalary, int hra, int da, int pf) {

        return basicSalary + (basicSalary * (hra/100f) + (basicSalary * (da/100f)) - (basicSalary * (pf/100f)));

    }

    public static void main(String[] args) {

        System.out.println("-----------------------");

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter Basic Salary: ");

        int basicSalary = scanner.nextInt();

        System.out.print("Enter HRA(%): ");

        int hra = scanner.nextInt();

        System.out.print("Enter DA(%): ");

        int da = scanner.nextInt();

        System.out.print("Enter PF(%): ");

        int pf = scanner.nextInt();

        scanner.close();
        int _grossSalary = (int) calculateGrossSalary(basicSalary, hra, da, pf);

        System.out.println("Gross Salary: " + _grossSalary);

        System.out.println("-----------------------");

    }

Output:

19. Write a Java program to find the details of the students eligible to enroll for the
examination (Students, Department combinedly give the eligibility criteria for the
enrollment class) using interfaces
Source Code:

import java.util.Scanner;

interface StudentDetails {

int id = 16;

StringBuilder name = new StringBuilder("Akshat");

String course = "BCA";

void getData();

class Department implements StudentDetails {

int attendance = 0;

public void setAttendance() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Attendance: ");

attendance = scanner.nextInt();

scanner.close();

@Override

public void getData() {

System.out.println("-----------------------");

System.out.println("Student ID: " + id);


System.out.println("Student Name: " + name);

System.out.println("Student Class: " + course);

System.out.println("-----------------------");

}}

class Exam extends Department {

public boolean eligible() {

return attendance >= 75;

public class Students {

public static void main(String[] args) {

Exam exam = new Exam();

exam.setAttendance();

exam.getData();

System.out.println("Is Eligible: " + exam.eligible());

Output:

Implement Operators
Left Shift Operator

Source Code:

package Shift;

public class LeftShift {

public static void main(String[] args) {

System.out.println(52 << 2);


System.out.println(2 << 2);

System.out.println(31 << 1);

System.out.println(20 << 3);

Output:

Right Shift Operator

Source Code:

package Shift;

public class RightShift {

public static void main(String[] args) {

System.out.println(52 >> 2);

System.out.println(2 >> 2);

System.out.println(31 >> 1);

System.out.println(20 >> 3);

Output:

All Operators using methods

Source Code:
package Shift;
class JavaOperators {

private int num = 5;

private int num2 = 7;

void logical() {

System.out.println("-----Logical-----");

if(num > 0 && num < 10) System.out.println(num + " is between 0 - 10");

if(false || true) System.out.println("True");

if(num != 6) System.out.println("Number is not equal to 6");

void relational() {

System.out.println("-----Relational-----");

if(num == num2) System.out.println("both are equal");

if(num > num2) System.out.println(num + " is greater");

if(num < num2) System.out.println(num2 + " is greater");

if(num != num2) System.out.println("both are not equal");

if(num >= num2) System.out.println(num + " is greater equal to " + num2);

if(num <= num2) System.out.println(num2 + " is greater equal to " + num);

void bitwise() {

System.out.println("-----Bitwise-----");

System.out.println("AND: " + (num & num2));

System.out.println("OR: " + (num | num2));

System.out.println("XOR: " + (num ^ num2));

System.out.println("Complement: " + ~num)  ;

public class OP {

public static void main(String[] args) {

JavaOperators javaOperators = new JavaOperators();

javaOperators.logical();

javaOperators.relational();

javaOperators.bitwise();

Output:
20. Implement Exceptions
Arithmetic Exception

Source Code:

package ExeptionHandling;

public class ArithmeticExp {

public static void main(String[] args) {

int num = 7;

int num2 = 0;

try {

System.out.println(num/num2);

} catch (ArithmeticException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

Output:

Array Out of Bound Exception


Source Code:

package ExeptionHandling;

public class ArrayExp {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5};

try {

System.out.println(arr[22]);

} catch (ArrayIndexOutOfBoundsException e) {    

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

Output:

File Not Found Exception

Source Code:

package ExeptionHandling;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

public class FileExp {

public static void main(String[] args) {

try {

File file = new File("");

FileReader fileReader = new FileReader(file);

fileReader.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (Exception e) {
e.printStackTrace();

Output:

21. Array Exercises


Traversing Array

Source Code:

package JavaArrays;

public class TraversingArray {

public static void main(String[] args) {

int[] nums = {8, 3, 7, 9, 2, 4, 6, 1};

for (int i : nums) {

System.out.println(i);

Output:

22. Write a Program to find the percentage and grade of multiple students using methods
Source Code:
import java.util.Scanner;

/***

@author Akshat

*/

class Student {

String name;

byte javaMarks;

byte pythonMarks;

byte cMarks;

byte cppMarks;

short totalMarks;

float percentage;

String grade;

private void gradeCalculate() {

if (percentage >= 90)

grade = "A+";

else if (percentage >= 80)

grade = "B+";

else if (percentage >= 60)

grade = "C";

else if (percentage >= 40)

grade = "D";

else

grade = "Fail";

Student(String name, byte javaMarks, byte pythonMarks, byte cMarks, byte cppMarks) {

this.name = name;

this.javaMarks = javaMarks;

this.pythonMarks = pythonMarks;

this.cMarks = cMarks;

this.cppMarks = cppMarks;

totalMarks = (short) (javaMarks + pythonMarks + cMarks + cppMarks);

percentage = (totalMarks * 100.00f) / 400.00f;

gradeCalculate();

public void display() {


System.out.println("Name: " + name + "\t" + "Java Marks: " + javaMarks + "\t" + "Python Marks: " + pythonMarks +
"\t" + "C Marks: " + cMarks + "\t" + "C++ Marks: " + cppMarks + "\t" + "Total Marks: " + totalMarks + "\t" +
"Percentage: " + percentage + "\t" + "Grade: " + grade);

public class GradeProgram {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Number of Students: ");

byte numberOfStudents = scanner.nextByte();

Student[] students = new Student[numberOfStudents];

for (int i = 0; i < students.length; i++) {

System.out.print("Enter Name of Student: ");

scanner.nextLine();

String name = scanner.nextLine();

System.out.print("Enter Java Marks: ");

byte javaMarks = scanner.nextByte();

System.out.print("Enter Python Marks: ");

byte pythonMarks = scanner.nextByte();

System.out.print("Enter C Marks: ");

byte cMarks = scanner.nextByte();

System.out.print("Enter C++ Marks: ");

byte cppMarks = scanner.nextByte();

students[i] = new Student(name, javaMarks, pythonMarks, cMarks, cppMarks);

scanner.close();

for (int i = 0; i < students.length; i++) {

students[i].display();

Output:
23. Inheritance

Constructor

Default Constructor

Source Code:

package Constructor;

class Demo {

Demo() {

System.out.println("Default Constructor");

public class DefaultCon {

public static void main(String[] args) {

Demo demo = new Demo();

Output:

Parameterized Constructor

Source Code:

package Constructor;

class DemoTwo {

private int num;


private int num2;

DemoTwo(int num, int num2) {

this.num = num;

this.num2 = num2;

System.out.println("SUM: " + (num + num2));

public class ParaCon {

public static void main(String[] args) {

DemoTwo demoTwo = new DemoTwo(12, 8);

Output:

Constructor Overloading

Source Code:

package Constructor;

class DemoThree {

DemoThree(int num, int num2) {

System.out.println("SUM: " + (num + num2));

DemoThree(int ...nums) {

int sum = 0;

for (int i = 0; i < nums.length; i++) {

sum += nums[i];

System.out.println("Total SUM: " + sum);

public class OverloadingCon {

public static void main(String[] args) {

System.out.println("----------");

DemoThree demoThree = new DemoThree(98, 13);


DemoThree demoThre2 = new DemoThree(98, 13, 78, 32, 4, 65);

System.out.println("----------");

Output:

24. Threads in Java


Thread using Runnable Interface

Source Code:

package JavaThreads;

class Threading1 implements Runnable {

@Override

public void run() {

while(true) {

System.out.println("Thread ID 1: " + Thread.currentThread().getId());

class Threading2 implements Runnable {

@Override

public void run() {

while(true) {

System.out.println("Thread ID 2: " + Thread.currentThread().getId());

public class MultiThreadingTwo {

public static void main(String[] args) {

Threading1 bullet1 = new Threading1();

Thread gun1 = new Thread(bullet1);

Thread gun2 = new Thread(new Threading2());

gun1.setPriority(Thread.MAX_PRIORITY);
gun1.start();

gun2.start();

Output:

Java Program for Thread priority

Source Code:

package JavaThreads;

class HelloWorld extends Thread{

@Override

public void run() {

super.run();

while(true) {

System.out.println("Hello Wolrd");

class Numbers extends Thread {

@Override

public void run() {

super.run();

for (int i = 0; true; i++) {

System.out.println(i);

}
public class MultiThreading {

public static void main(String[] args) {

HelloWorld obj1 = new HelloWorld();

Numbers obj2 = new Numbers();

obj2.setPriority(Thread.MAX_PRIORITY);

obj1.start();

obj2.start();

Output:

Program for sleep method in Java

Source Code:

Output:

Program for multiple Threads

Source Code:

package JavaThreads;

import PrimeOrNot;

import java.util.Scanner;
class Factorial extends Thread {

int fact = 1;

int num;

Factorial(int num) {

this.num = num;

@Override

public void run() {

for (int i = 1; i <= num; i++) {

fact *= i;

try {

Thread.sleep(5);

} catch (Exception e) {

e.printStackTrace();

System.out.println("Factorial of " + num + " is " + fact);

class PrimeNumbers extends Thread {

int num;

PrimeNumbers(int num) {

this.num = num;

@Override

public void run() {

for (int i = 2; i <= num; i++) {

if(PrimeOrNot.isPrime(i)) System.out.println("Prime Number: " + i);

try {

Thread.sleep(5);

} catch (Exception e) {

e.printStackTrace();

}
}

public class FactorialThread {

public static void main(String[] args) {

System.out.println("----------------------------");

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Number for Prime Numbers: ");

int num1 = scanner.nextInt();

System.out.print("Enter Number for Factorial: ");

int num2 = scanner.nextInt();

scanner.close();

PrimeNumbers primeNumbers = new PrimeNumbers(num1);

Factorial factorial = new Factorial(num2);

factorial.setPriority(Thread.MIN_PRIORITY);

primeNumbers.setPriority(Thread.MAX_PRIORITY);

primeNumbers.start();

factorial.start();

Output:

Importing package in Java

Source Code:

package Searching;

import Sorting.InsertionSort;

import java.util.Scanner;

public class BinarySearch {

public static String bSearch(int num, int arr[]) {


byte minIndex = 0;

byte maxIndex = (byte) (arr.length - 1);

while (minIndex <= maxIndex) {

byte midIndex = (byte) ((minIndex + maxIndex) / 2);

// System.out.println(minIndex + " " + midIndex + " " + maxIndex);

if (arr[midIndex] == num)

return num + " is Present at " + (midIndex+1) + " Position";

else if (arr[midIndex] < num)

minIndex = (byte) (midIndex + 1);

else

maxIndex = (byte) (midIndex - 1);

return "Number Not Found!!";

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Number of Length of an Array: ");

byte numberOfLength = scanner.nextByte();

int[] arr = new int[numberOfLength];

System.out.println("Enter Elements one by one");

for (byte i = 0; i < arr.length; i++) {

arr[i] = scanner.nextInt();

System.out.println("Enter Number to Search");

int num = scanner.nextInt();

scanner.close();

arr = InsertionSort.iSort(arr);

for (int i : arr) {

System.out.print(i + " ");

System.out.println();

System.out.println(bSearch(num, arr));

Output:
25. Java String
String compareTo()

Source Code:

package JavaStrings;

public class CompareString {

public static void main(String[] args) {

String str = new String("Hello");

String str2 = new String("hello");

System.out.println(str.compareTo(str2));

Output:

String concat()

Source Code:

package JavaStrings;

public class ConcatString {

public static void main(String[] args) {


String str = "Hello ";

String str2 = "World!!";

System.out.println(str.concat(str2));

Output:

String Builder example

Source Code:

package JavaStrings;

import java.lang.StringBuilder;

public class SBuilder {

public static void main(String[] args) {

StringBuilder str = new StringBuilder("Akshat");

str.append(" Srivastava");

System.out.println(str);

Output:

String Buffer example

Source Code:

package JavaStrings;

import java.lang.StringBuffer;

public class SBuffer {

public static void main(String[] args) {

StringBuffer str = new StringBuffer("Hello World!!");


System.out.println(str.indexOf("r"));

Output:

26. Applet Programs


Hello World program

Source Code:

import java.applet.Applet;

import java.awt.Graphics;

public class HelloWorld extends Applet{

public void paint(Graphics g) {

g.drawString("Hello World!!", 100, 200);

<html>

<body>

<applet code=HelloWorld.class width=200 height=200>

</applet>

</body>

</html>

Output:
Animation program

Source Code:

import java.awt.*;

import java.applet.*;

public class JavaAnimation extends Applet {

Image img;

public void init() {

img = getImage(getDocumentBase(), "img.jpeg");

public void paint(Graphics graphics) {

for(int i = 50; i < 600; i++) {

graphics.drawImage(img, i, 5, this);

try {

Thread.sleep(200);

} catch (Exception e) {

e.printStackTrace();

<html>

<body>
<applet code=JavaAnimation.class width=1200 height=900>

</applet>

</body>

</html>

Output:

Ball program

Source Code:

import java.awt.*;

import java.applet.*;

public class BallProgram extends Applet{

int x = 0, y = 0, p = 2, q = 1;

int ballWidth = 100, ballHeight = 100, width, height;

Thread thread;

public void init() {

width = getSize().width;

height = getSize().height;

thread = new Thread();

public void start() {

thread.start();

public void run() {

while(true) {
x += p;

y += q;

repaint();

try {

Thread.sleep(200);

} catch (Exception e) {

e.printStackTrace();

if((x + ballWidth) >= width || x <= 0) {

p *= -1;

if((y + ballHeight) >= height || y <= 0) {

y *= -1;

public void paint(Graphics graphics) {

graphics.setColor(Color.blue);

graphics.fillOval(x, y, ballWidth, ballHeight);

<html>

<body>

<applet code=BallProgram.class width=200 height=200>

</applet>

</body>

</html>

Output:
Rectangle program

Source Code:

import java.awt.*;

import java.applet.*;

public class RectangleProgram extends Applet {

public void paint(Graphics graphics) {

graphics.setColor(Color.red);

graphics.draw3DRect(100, 100, 50, 50, true);

graphics.setColor(Color.blue);

graphics.fill3DRect(200, 200, 100, 100, true);

<html>

<body>

<applet code=RectangleProgram.class width=200 height=200>

</applet>

</body>

</html>

Output:
27. Creating a pom.xml file and demo maven project
Source Code:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>

<artifactId>mprogram</artifactId>

<version>1.0-SNAPSHOT</version>

<name>mprogram</name>

<!-- FIXME change it to the project's website -->

<url>http://www.example.com</url>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<maven.compiler.source>1.7</maven.compiler.source>

<maven.compiler.target>1.7</maven.compiler.target>

</properties>

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

<scope>test</scope>
</dependency>

</dependencies>

<build>

<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom)
-->

<plugins>

<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->

<plugin>

<artifactId>maven-clean-plugin</artifactId>

<version>3.1.0</version>

</plugin>

<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-


bindings.html#Plugin_bindings_for_jar_packaging -->

<plugin>

<artifactId>maven-resources-plugin</artifactId>

<version>3.0.2</version>

</plugin>

<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.8.0</version>

</plugin>

<plugin>

<artifactId>maven-surefire-plugin</artifactId>

<version>2.22.1</version>

</plugin>

<plugin>

<artifactId>maven-jar-plugin</artifactId>

<version>3.0.2</version>

</plugin>

<plugin>

<artifactId>maven-install-plugin</artifactId>

<version>2.5.2</version>

</plugin>

<plugin>

<artifactId>maven-deploy-plugin</artifactId>

<version>2.8.2</version>

</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->

<plugin>

<artifactId>maven-site-plugin</artifactId>

<version>3.7.1</version>

</plugin>

<plugin>

<artifactId>maven-project-info-reports-plugin</artifactId>

<version>3.0.0</version>

</plugin>

</plugins>

</pluginManagement>

</build>

</project>

App:

package com.example;

/**

Hello world!

*/

public class App

public static void main( String[] args )

System.out.println("Hello World!");

You might also like