0% found this document useful (0 votes)
4 views45 pages

Core Java Lab Manual

The document outlines a series of Java programming exercises for a Core Java Lab at Noida International University, including tasks such as printing a multiplication table, determining prime numbers, finding the LCM, implementing stack and queue data structures, and creating applets. It also provides detailed code examples for each exercise and instructions for downloading and installing Eclipse IDE and JDK. Additionally, it explains the differences between OpenJDK and OracleJDK regarding licensing and usage.

Uploaded by

jaatrathi7933
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views45 pages

Core Java Lab Manual

The document outlines a series of Java programming exercises for a Core Java Lab at Noida International University, including tasks such as printing a multiplication table, determining prime numbers, finding the LCM, implementing stack and queue data structures, and creating applets. It also provides detailed code examples for each exercise and instructions for downloading and installing Eclipse IDE and JDK. Additionally, it explains the differences between OpenJDK and OracleJDK regarding licensing and usage.

Uploaded by

jaatrathi7933
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

NOIDA INTERNATIONAL UNIVERSITY SCHOOL OF

ENGINEERING AND TECHNOLOGY

(PCCCSE0405P) Core Java Lab

1. Write a program to print the table of a number


2. Write a program to determine the number is prime or not
3. Write a program to find the LCM of number
4. Write a program to implement stack and queue.
5. Write a Java package to polymorphism and interface
6. Write a Applet program in java to display a clock
7. Write a java program to add two binary numbers
8. Write a java program to convert a decimal number to binary number vice
versa.
Experiment-1

Write a program to print the table of a number

import [Link];
public class TableExample
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter number: ");
//reading a number whose table is to be print
int num=[Link]();
//loop start execution form and execute until the condition i<=10 becomes false
for(int i=1; i <= 10; i++)
{
//prints table of the entered number
[Link](num+" * "+i+" = "+num*i);
}
}
}

Output:
Experiment-2

Write a program to determine the number is prime or not

public class Main {


public static void main(String[] args) {
int num = 29;
boolean flag = false;
// 0 and 1 are not prime numbers
if (num == 0 || num == 1) {
flag = true;
}
for (int i = 2; i <= num / 2; ++i) {

// condition for nonprime number


if (num % i == 0) {
flag = true;
break;
}
}
if (!flag)
[Link](num + " is a prime number.");
else
[Link](num + " is not a prime number.");
}
}

Output
29 is a prime number.
Experiment-3

Write a program to find the LCM of number

// Java Program to find


// the LCM of two numbers
import [Link]. *;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Numbers
int a = 15, b = 25;
// Checking for the largest
// Number between them
int ans = (a > b) ? a : b;
// Checking for a smallest number that
// can de divided by both numbers
while (true) {
if (ans % a == 0 && ans % b == 0)
break;
ans++;
}
// Printing the Result
[Link]("LCM of " + a + " and " + b
+ " : " + ans); }
}

Output
LCM of 15 and 25:75
Experiment-4

Write a program to implement stack and queue.

Stack Code
public class StackExample {
private int maxSize;
private int[] stackArray;
private int top;

public StackExample(int size) {


maxSize = size;
stackArray = new int[maxSize];
top = -1;
}

// Method to push an element onto the stack


public void push(int value) {
if (top == maxSize - 1) {
[Link]("Stack overflow");
return;
}
stackArray[++top] = value;
[Link](value + " pushed into the stack");
}

// Method to pop an element from the stack


public int pop() {
if (top == -1) {
[Link]("Stack underflow");
return -1;
}
int poppedElement = stackArray[top--];
[Link](poppedElement + " popped from the stack");
return poppedElement;
}

// Method to peek the top element of the stack


public int top() {
if (top == -1) {
[Link]("Stack is empty");
return -1;
}
return stackArray[top];
}

// Method to check if the stack is empty


public boolean isEmpty() {
return (top == -1);
}

public static void main(String[] args) {


StackExample stack = new StackExample(5); // Creating a stack of size 5

// Pushing elements onto the stack


[Link](10);
[Link](20);

// Peeking the top element


[Link]("Top element of the stack: " + [Link]());

// Popping elements from the stack


[Link]();
[Link]();
[Link](); // Trying to pop from an empty stack

// Checking if the stack is empty


[Link]("Is stack empty? " + [Link]());
}
}

Output
10 pushed into the stack
20 pushed into the stack
Top element of the stack: 20
20 popped from the stack
10 popped from the stack
Stack underflow
Is stack empty? True
Queue

public class Queue {


int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;

Queue() {
front = -1;
rear = -1;
}

// check if the queue is full


boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

// check if the queue is empty


boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}

// insert elements to the queue


void enQueue(int element) {

// if queue is full
if (isFull()) {
[Link]("Queue is full");
}
else {
if (front == -1) {
// mark front denote first element of queue
front = 0;
}

rear++;
// insert element at the rear
items[rear] = element;
[Link]("Insert " + element);
}
}

// delete element from the queue


int deQueue() {
int element;

// if queue is empty
if (isEmpty()) {
[Link]("Queue is empty");
return (-1);
}
else {
// remove element from the front of queue
element = items[front];

// if the queue has only one element


if (front >= rear) {
front = -1;
rear = -1;
}
else {
// mark next element as the front
front++;
}
[Link](element + " Deleted");
return (element);
}
}

// display element of the queue


void display() {
int i;
if (isEmpty()) {
[Link]("Empty Queue");
}
else {
// display the front of the queue
[Link]("\nFront index-> " + front);

// display element of the queue


[Link]("Items -> ");
for (i = front; i <= rear; i++)
[Link](items[i] + " ");

// display the rear of the queue


[Link]("\nRear index-> " + rear);
}
}

public static void main(String[] args) {

// create an object of Queue class


Queue q = new Queue();

// try to delete element from the queue


// currently queue is empty
// so deletion is not possible
[Link]();

// insert elements to the queue


for(int i = 1; i < 6; i ++) {
[Link](i);
}

// 6th element can't be added to queue because queue is full


[Link](6);

[Link]();

// deQueue removes element entered first i.e. 1


[Link]();

// Now we have just 4 elements


[Link]();

}
}

Output
Queue is empty
Insert 1
Insert 2
Insert 3
Insert 4
Insert 5
Queue is full

Front index-> 0
Items ->
1 2 3 4 5
Rear index-> 4
1 Deleted

Front index-> 1
Items ->
2 3 4 5
Rear index-> 4
Experiment-5

Write a Java package to polymorphism and interface

Polymorphism Code

// Base class Person


class Person {

// Method that displays the


// role of a person
void role() {
[Link]("I am a person.");
}
}

// Derived class Father that


// overrides the role method
class Father extends Person {

// Overridden method to show


// the role of a father
@Override
void role() {
[Link]("I am a father.");
}
}

public class Main {


public static void main(String[] args) {

// Creating a reference of type Person


// but initializing it with Father class object
Person p = new Father();

// Calling the role method. It calls the


// overridden version in Father class
[Link]();
}
}
Output
I am a father.

Interface Code

interface Polygon {
void getArea(int length, int breadth);
}

// implement the Polygon interface


class Rectangle implements Polygon {

// implementation of abstract method


public void getArea(int length, int breadth) {
[Link]("The area of the rectangle is " + (length * breadth));
}
}

class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
[Link](5, 6);
}
}

Output
The area of the rectangle is 30
Experiment-6

Write a Applet program in java to display a clock

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class java Application6 extends Applet implements Runnable {
Thread t1 = null;
int hours = 0, minutes = 0, seconds = 0;
String time = "";

public void init() {


setBackground( [Link]);
}
public void start() {
t1 = new Thread( this );
[Link]();
}
public void run() {
try {
while (true) {
Calendar cal = [Link]();
hours = [Link]( Calendar.HOUR_OF_DAY);
if ( hours > 12 ) hours -= 12;
minutes = [Link]( [Link] );
seconds = [Link]( [Link] );

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");


Date d = [Link]();
time = [Link]( d );

repaint();
[Link](1000);
}
}
catch (Exception e) { }
}
public void paint( Graphics g ) {
[Link]( [Link] );
[Link]( time, 50, 50 );
}
}
Experiment-7

Write a java program to add two binary numbers

import [Link];
public class JavaExample {
public static void main(String[] args)
{
//Two variables to hold two input binary numbers
long b1, b2;
int i = 0, carry = 0;
//This is to hold the output binary number
int[] sum = new int[10];

//To read the input binary numbers entered by user


Scanner scanner = new Scanner([Link]);

//getting first binary number from user


[Link]("Enter first binary number: ");
b1 = [Link]();
//getting second binary number from user
[Link]("Enter second binary number: ");
b2 = [Link]();

//closing scanner after use to avoid memory leak


[Link]();
while (b1 != 0 || b2 != 0)
{
sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);
b1 = b1 / 10;
b2 = b2 / 10;
}
if (carry != 0) {
sum[i++] = carry;
}
--i;
[Link]("Output: ");
while (i >= 0) {
[Link](sum[i--]);
}
[Link]("\n");
}
}

Output:

Enter first binary number: 11100

Enter second binary number: 10101

Output: 110001
Experiment-8

Write a java program to convert a decimal number to binary number vice versa.

/ Java program to convert a decimal

// number to binary number

import [Link].*;

class GFG

// function to convert decimal to binary

static void decToBinary(int n)

// array to store binary number

int[] binaryNum = new int[1000];

// counter for binary array

int i = 0;

while (n > 0)

// storing remainder in binary array

binaryNum[i] = n % 2;

n = n / 2;

i++;

}
// printing binary array in reverse order

for (int j = i - 1; j >= 0; j--)

[Link](binaryNum[j]);

// driver program

public static void main (String[] args)

int n = 17;

[Link]("Decimal - " + n);

[Link]("Binary - ");

decToBinary(n);

Output

Decimal - 17

Binary - 10001
Following is a step-by-step guide to download and install Eclipse IDE:

Eclipse Download and Installation Steps

Step 1) Installing Eclipse

Open your browser and type [Link]

Step 2) Click on “Download” button.

Step 3) Click on “Download 64 bit” button


Step 4) Click on “Download” button

Step 4) Install Eclipse.

1. Click on “downloads” in Windows file explorer.

2. Click on “[Link]” file.

Step 5) Click on Run button


Step 6) Click on “Eclipse IDE for Java Developers”
Step 7) Click on “INSTALL” button

Step 8) Click on “LAUNCH” button.


Step 9) Click on “Launch” button.

Step 10) Click on “Create a new Java project” link.

Step 11) Create a new Java Project

1. Write project name.


2. Click on “Finish button”.

Step 12) Create Java Package.

1. Goto “src”.

2. Click on “New”.

3. Click on “Package”.
Step 13) Writing package name.

1. Write name of the package

2. Click on Finish button.


Step 14) Creating Java Class

1. Click on package you have created.

2. Click on “New”.

3. Click on “Class”.
Step 15) Defining Java Class.

1. Write class name

2. Click on “public static void main (String[] args)” checkbox.

3. Click on “Finish” button.


[Link] file will be created as shown below:
Step 16) Click on “Run” button.

Output will be displayed as shown below.


Note: Before Download Eclipse IDE (Integrated Development Environment),
Download JDK (Java Development Kit) and install in your system

To download JDK we can follow following procedures

How to Install JDK 21 (on Windows, macOS & Ubuntu) and Get Started with Java
Programming

The Java Development Kit (JDK), officially named "Java Platform Standard Edition"
or "Java SE", is needed for developing and running Java programs.

JDK Variants

Today, there are few variants of JDK:

1. OpenJDK: Currently, the "OpenJDK" (@ [Link] developed


by Oracle, Java community, Red Hat, Azul Systems, IBM, Microsoft, Amazon,
Apple, SAP, provides a free and open-source Java Platform Standard Edition (or
Java SE or JDK) official reference implementation. OpenJDK includes the
virtual machine (HotSpot), the Java Class Library, and the Java Compiler. It
does not include web-browser plugin and Web Start.
Popular OpenJDK builds includes Azul Zulu, Red Hat OpenJDK (IcedTea),
Amazon Corretto, Eclipse Adoptium's Temurin, SapMachine, Microsoft
OpenJDK, and more.

2. OracleJDK: This article is based on the "OracleJDK"


(@ [Link] (due to legacy), which is free for personal and
development use but no longer free for commercial use.

The main difference between OpenJdk and OracleJDK is licensing. OpenJDK is


completely open source with a GNU General Public License. OracleJDK requires a
commercial license from Oracle. Since 2019, businesses need to purchase a
commercial license in order to receive software updates.

1. How To Install JDK on Windows

Step 0: Un-Install Older Version(s) of JDK/JRE

I recommend that you install only the latest JDK. Although you can install multiple
versions of JDK/JRE concurrently, it is messy.

If you have previously installed older version(s) of JDK/JRE, un-install ALL of them.
Goto "Control Panel" ⇒ (optional) "Programs" ⇒ "Programs and Features" ⇒ Un-
install ALL programs begin with "Java", such as "Java SE Development Kit ...", "Java
SE Runtime ...", "Java X Update ...", and etc.

Step 1: Download JDK

1. Goto JDK (or Java SE) download site


@ [Link]

2. Choose "JDK 21" ⇒ "Windows" ⇒ Download "x64 Installer" (e.g., "jdk-


21_windows-x64_bin.exe" - about 167MB).

Step 2: Install JDK

Run the downloaded installer. Accept the defaults and follow the screen instructions to
complete the installation. By default, JDK is installed in directory "C:\Program Files\
Java\jdk-21".

Launch "File Explorer". Navigate to "C:\Program Files\Java" to inspect this


directories. Take note of your JDK Installed Directory jdk-21.

I shall refer to the JDK Installed Directory as <JAVA_HOME>, hereafter, in this


article (corresponding to environment variable %JAVA_HOME% in Windows
or $JAVA_HOME in Unix/macOS).
Step 3: (SKIP this Step for JDK 15 onwards, GOTO Step 4 - Kept here for
completeness) Include JDK's "bin" Directory in the PATH

Windows' Command Prompt (CMD) searches the current directory and the directories
listed in the PATH environment variable for executable programs.

JDK's programs (such as Java compiler "[Link]" and Java runtime "[Link]")
reside in the sub-directory "bin" of the JDK installed directory. JDK's "bin" needs to
be added into the PATH.

Prior to JDK 15, you need to explicitly add JDK's "bin" into the PATH. Starting from
JDK 15, the installation process adds the directory "C:\Program Files\Common Files\
Oracle\Java\javapath" to the PATH. The "javapath" directory is a link to
"javapath_target_xxxxxx", which contains a copy of the following JDK programs:

 [Link]: Java Runtime

 [Link]: Java Compiler

 [Link]: Java Runtime for Windows Console-less

 [Link]: Java Command-line Shell (since JDK 10) - a Read-Evaluate-Print


Loop (REPL) which evaluates declarations, statements, and expressions as they
are entered and immediately shows the results.

Link is used so that you can keep multiple copies (versions) of JDK.

To edit the PATH environment variable in Windows 10:

1. Launch "Control Panel" ⇒ (Optional) "System and Security" ⇒ "System" ⇒


Click "Advanced system settings" on the left pane.

2. Switch to "Advanced" tab ⇒ Click "Environment Variables" button.

3. Under "System Variables" (the bottom pane), scroll down to select variable
"Path" ⇒ Click "Edit...".
4. For Newer Windows 10:
You shall see a TABLE listing all the existing PATH entries (if not, goto next
step). Click "New" ⇒ Click "Browse" and navigate to your JDK's "bin"
directory, i.e., "c:\Program Files\Java\jdk-15.0.{x}\bin", where {x} is your
installation update number ⇒ Select "Move Up" to move this entry all the way
to the TOP.

5. For Older Windows 10 (Time to change your computer!):


(CAUTION: Read this paragraph 3 times before doing this step! Don't
push "Apply" or "OK" until you are 101% sure. There is no UNDO!!!)
(To be SAFE, copy the content of the "Variable value" to Notepad before
changing it!!!)
In "Variable value" field, APPEND "c:\Program Files\Java\jdk-15.0.{x}\bin"
(where {x} is your installation update number) IN FRONT of all the existing
directories, followed by a semi-colon (;) to separate the JDK's bin directory
from the rest of the existing directories. DO NOT DELETE any existing entries;
otherwise, some existing applications may not run.

6. Variable name : PATH

Variable value : c:\Program Files\Java\jdk-15.0.{x}\bin;[do not delete exiting


entries...]

You need to re-started CMD for the new environment settings to take effect.

Step 4: Verify the JDK Installation

Launch a CMD via one of the following means:

1. Click "Search" button ⇒ Type "cmd" ⇒ Choose "Command Prompt", or

2. Right-click "Start" button ⇒ run... ⇒ enter "cmd", or

3. Click "Start" button ⇒ Windows System ⇒ Command Prompt


Issue the following commands to verify your JDK installation:

1. (Skip for JDK 15 onwards) Issue "path" command to list the contents of
the PATH environment variable. Check to make sure that your JDK's "bin" is
listed in the PATH.

2. path

PATH=c:\Program Files\Java\jdk-{xx.y.z}\bin;other entries...

3. Issue the following commands to verify that JDK/JRE are properly installed and
display their version:

4. // Display the JDK version

5. javac -version

6. javac 21.0.1

7.

8. // Display the JRE version

9. java -version

[Link] version "21.0.1" 2023-10-17 LTS

[Link](TM) SE Runtime Environment (build 21.0.1+12-LTS-29)

Java HotSpot(TM) 64-Bit Server VM (build 21.0.1+12-LTS-29, mixed mode, sharing)

Step 5: Write a Hello-World Java Program

1. Create a directory to keep your works, e.g., "d:\myProject" or "c:\myProject".


Do NOT save your works in "Desktop" or "Documents" as their directory path
are hard to locate. Your directory name should not contain blank or special
characters. Use meaningful but short name as it is easier to type.
2. Launch a programming text editor (such as Sublime Text, Atom). Begin with
a new file and enter the following source code. Save the file as "[Link]",
under your work directory (e.g., d:\myProject).

3. /*

4. * First Java program to say Hello

5. */

6. public class Hello { // Save as "[Link]" under "d:\myProject"

7. public static void main(String[] args) {

8. [Link]("Hello, world!");

9. }

Step 6: Compile and Run the Hello-World Java Program

To compile the source code "[Link]":

1. Start a CMD Shell (Search ⇒ enter "cmd" ⇒ select "Command Prompt").


2. Set the Current Drive to the drive where you saved your source file
"[Link]".
If you use drive "c", skip this step.
Else if you use drive "d", enter "d:" as follow:

3. d:

D:\xxx>

4. Set the Current Working Directory to the directory that you saved your source
file via the cd (Change Directory) command. For example, suppose that your
source file is saved in directory "myProject".

5. cd \myProject

D:\myProject>

6. Issue a dir (List Directory) command to confirm that your source file is present
in the current directory.

7. dir

8. ......

9. xx-xxx-xx xx:xx PM 277 [Link]

......

[Link] the JDK compiler "javac" to compile the source code "[Link]".

[Link] [Link]

// If error message appears, correct your source code and re-compile

The compilation is successful if the command prompt returns. Otherwise, error


messages would be shown. Correct the errors in your source file and re-compile.
Check "Common JDK Installation Errors", if you encounter problem compiling your
program.

[Link] output of the compilation is a Java class called "[Link]". Issue


a dir (List Directory) command again to check for the output.

[Link]

14.......

[Link]-xxx-xx xx:xx PM 416 [Link]

[Link]-xxx-xx xx:xx PM 277 [Link]

......

To run the program, invoke the Java Runtime "java":

java Hello

Hello, world!

Everything that can possibly go wrong will go wrong: Read "JDK Installation
Common Errors".

Step 7: (For Advanced Users Only) JDK's Source Code

Source code for JDK is provided and kept in "<JAVA_HOME>\lib\[Link]" (or


"<JAVA_HOME>\[Link]" prior to JDK 9). I strongly recommend that you to go
through some of the source files such as "[Link]", "[Link]", and "[Link]",
under "java\lang", to learn how experts program.
OR

Install Java

Step 1: Verify that it is already installed or not

Check whether Java is already installed on the system or not. In my case, it is not
installed therefore I need to install JDK 1.8 on my computer.

Step 2: Download JDK

There are available releases for Linux and mac operating systems. You can visit the
official link for JDK distributions i.e.

JDK Downloads

Step 3: Install JDK

Open the executable file which you have just downloaded and follow the steps.
Click Next to continue

Just Choose Development Tools and click Next.


Set up is being ready.
Choose the Destination folder in which you want to install JDK. Click Next to
continue with the installation.

Set up is installing Java to the computer.


We have successfully installed Java SE development kit 8. Close the installation set
up.

Step 4 : Set the Permanent Path

To execute Java applications from command line, we need to set Java Path. To set the
path, follow the following steps.
Right click on "this PC". It can be named as "My Computer" in some systems. Choose
"properties" from the options.

The screen look alike the above image will open. Click on "Advanced system settings"
to continue.
Above window will open. Click on "Environment Variables" to continue.

Enter "path" in variable name and enter the path to the bin folder inside your JDK in
the variable value. Click OK.
Now Java Path has been set up. Open the Command prompt and type "javac" In case
you have already open up the command prompt, I suggest you to close the existing
window and reopen it again.

We will get javac executed as shown in the image below.

The Java has been installed on our system. Now, we need to configure IDEs like
NetBeans or Eclipse in order to execute JavaFX applications.

You might also like