0% found this document useful (0 votes)
36 views11 pages

Java Practical

The document provides a comprehensive guide on installing the Java Development Kit (JDK), compiling a simple Java program, and exercises on control flow, user input, arrays, and classes in Java. It includes step-by-step instructions for installation on Windows and Linux/macOS, as well as practical programming exercises demonstrating key Java concepts. Key topics covered include control flow statements, user input handling with the Scanner class, array manipulation, and the use of access specifiers in classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views11 pages

Java Practical

The document provides a comprehensive guide on installing the Java Development Kit (JDK), compiling a simple Java program, and exercises on control flow, user input, arrays, and classes in Java. It includes step-by-step instructions for installation on Windows and Linux/macOS, as well as practical programming exercises demonstrating key Java concepts. Key topics covered include control flow statements, user input handling with the Scanner class, array manipulation, and the use of access specifiers in classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] of JDK and compiling a simple Java program.

Installing JDK and Compiling a Simple Java Program

Java Development Kit (JDK) is essential for compiling and running Java programs. Follow
these steps for installation and compilation:

1. Installing JDK

Steps for Windows:

1. Download JDK:

o Visit Oracle JDK or OpenJDK and download the latest version.

2. Install JDK:

o Run the downloaded installer and follow on-screen instructions.

o Install it in the default directory: C:\Program Files\Java\jdk-VERSION.

3. Set Environment Variables (Optional for manual setup):

o Open System Properties > Advanced System Settings > Environment


Variables.

o Under System Variables, find Path and add:

o C:\Program Files\Java\jdk-VERSION\bin

o Set JAVA_HOME:

o C:\Program Files\Java\jdk-VERSION

4. Verify Installation:

o Open Command Prompt and type:

o java -version

o You should see the installed JDK version.

Steps for Linux/macOS:

1. Open Terminal and install OpenJDK using:

2. sudo apt install openjdk-17-jdk # For Ubuntu/Debian

3. sudo yum install java-17-openjdk # For CentOS/Fedora

4. brew install OpenJDK # For macOS


5. Verify installation:

6. java -version

2. Writing & Compiling a Simple Java Program

Step 1: Create a Java File

1. Open a text editor (Notepad, VS Code, IntelliJ, etc.).

2. Write a simple program and save it as [Link]:

3. public class HelloWorld {

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

5. [Link]("Hello, World!");

6. }

7. }

Step 2: Compile the Java Program

1. Open Command Prompt (Windows) or Terminal (Linux/macOS).

2. Navigate to the file's location using cd command:

3. cd path/to/file

4. Compile the program:

5. javac [Link]

(This creates [Link].)

Step 3: Run the Java Program

1. Execute the compiled program:

2. java HelloWorld

3. Output:

4. Hello, World!
2. Programming exercise on control flow statement,operators
and looping statements in Java.
Java Programming Exercise: Control Flow, Operators & Looping Statements.

Here's an exercise to practice control flow statements, operators, and loops in Java.

Exercise Objective:

Write a Java program that takes user input (a number) and performs the following
operations:

1. Checks if the number is even or odd using an if-else statement.

2. Uses a switch-case to determine if the number is positive, negative, or zero.

3. Performs basic arithmetic operations using operators.

4. Uses a loop (for, while, or do-while) to print a sequence of numbers up to the


entered number.

Java Program Implementation

import [Link];

public class ControlFlowDemo {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Taking user input

[Link]("Enter a number: ");

int num = [Link]();

// 1. Check if the number is even or odd

if (num % 2 == 0) {

[Link](num + " is an Even number.");

} else {
[Link](num + " is an Odd number.");

// 2. Use switch-case to determine positivity

switch ([Link](num)) {

case 1:

[Link](num + " is Positive.");

break;

case -1:

[Link](num + " is Negative.");

break;

case 0:

[Link](num + " is Zero.");

break;

default:

[Link]("Invalid input.");

// 3. Perform basic arithmetic operations

[Link]("Addition: " + (num + 5));

[Link]("Multiplication: " + (num * 2));

[Link]("Division by 2: " + (num / 2));

// 4. Loop to print numbers up to the entered number

[Link]("Numbers from 1 to " + num + ":");

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

[Link](i + " ");

}
[Link]();

What This Program Demonstrates

Control Flow: Uses if-else and switch-case to make decisions.


Operators: Uses arithmetic operators (+, *, /).
Loops: Uses a for loop to print numbers.
User Input Handling: Uses Scanner to read input from the user.
[Link] to scan the input using input scanner class.
Here's a simple Java program that demonstrates how to scan user input using the Scanner
class.

Java Program Using Scanner Class

import [Link]; // Import Scanner class

public class InputScannerExample {

public static void main(String[] args) {

// Create a Scanner object

Scanner scanner = new Scanner([Link]);

// Prompt user for input

[Link]("Enter your name: ");

String name = [Link](); // Read a string input

[Link]("Enter your age: ");

int age = [Link](); // Read an integer input

[Link]("Enter your height (in cm): ");

double height = [Link](); // Read a decimal (double) input

// Display user input

[Link]("\nUser Details:");

[Link]("Name: " + name);

[Link]("Age: " + age);

[Link]("Height: " + height + " cm");


// Close the scanner

[Link]();

Explanation

Scanner scanner = new Scanner([Link]); – Creates an object to read input from the
keyboard.
[Link](); – Reads a full line of text (for names or sentences).
[Link](); – Reads an integer input (for age).
[Link](); – Reads a floating-point number (for height).
[Link](); – Always close the Scanner to avoid resource leaks.

Example User Input & Output

Enter your name: John

Enter your age: 25

Enter your height (in cm): 175.5

User Details:

Name: John

Age: 25

Height: 175.5 cm
[Link] exercise on arrays and functions in Java
Java Programming Exercise: Arrays & Functions
Here's a fun exercise to practice arrays and functions in Java.
Exercise Objective:
Create a Java program that:
1. Defines an array of numbers.
2. Uses functions to:
o Find the sum of all elements.
o Find the maximum and minimum values in the array.
o Sort the array in ascending order.

Java Program Implementation


import [Link];

public class ArrayFunctionsExample {

// Function to calculate the sum of array elements


public static int calculateSum(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}

// Function to find the maximum value in the array


public static int findMax(int[] arr) {
int max = arr[0];
for (int num : arr) {
if (num > max) {
max = num;
}
}
return max;
}

// Function to find the minimum value in the array


public static int findMin(int[] arr) {
int min = arr[0];
for (int num : arr) {
if (num < min) {
min = num;
}
}
return min;
}

// Function to sort the array in ascending order


public static void sortArray(int[] arr) {
[Link](arr);
}

public static void main(String[] args) {


// Initialize an array with numbers
int[] numbers = {45, 12, 78, 34, 89, 23};

// Call functions and display results


[Link]("Original Array: " + [Link](numbers));
[Link]("Sum of Elements: " + calculateSum(numbers));
[Link]("Maximum Value: " + findMax(numbers));
[Link]("Minimum Value: " + findMin(numbers));

// Sorting the array


sortArray(numbers);
[Link]("Sorted Array: " + [Link](numbers));
}
}

What This Program Demonstrates


Arrays: Stores multiple elements of the same type.
Functions: Helps organize logic into reusable methods.
Loops & Conditions: Used inside functions for calculations.
Sorting: Uses [Link]() to order elements efficiently.

Example Output
Original Array: [45, 12, 78, 34, 89, 23]
Sum of Elements: 281
Maximum Value: 89
Minimum Value: 12
Sorted Array: [12, 23, 34, 45, 78, 89]
5. Program to demonstrate the concept of classes and
objects using access specifiers.
Java Program: Demonstrating Classes, Objects & Access Specifiers
Access specifiers in Java control the visibility of variables, methods, and classes.
Here's a program to showcase public, private, protected, and default access
specifiers using classes and objects.

Java Code Implementation


// Define a class with different access specifiers
class Person {
// Private variable (Accessible only inside this class)
private String name;

// Protected variable (Accessible within the package & subclasses)


protected int age;

// Default variable (Accessible within the same package)


String city;

// Public variable (Accessible from anywhere)


public String country;

// Constructor to initialize values


public Person(String name, int age, String city, String country) {
[Link] = name;
[Link] = age;
[Link] = city;
[Link] = country;
}

// Public method to display information


public void displayInfo() {
[Link]("Name: " + name); // Accessing private variable within the
class
[Link]("Age: " + age);
[Link]("City: " + city);
[Link]("Country: " + country);
}
}

public class AccessSpecifiersExample {


public static void main(String[] args) {
// Create an object of the Person class
Person person1 = new Person("Alice", 25, "Mumbai", "India");

// Accessing public variable directly


[Link]("Country: " + [Link]);

// Accessing default and protected variables (Allowed within the same package)
[Link]("City: " + [Link]);
[Link]("Age: " + [Link]);

// Private variable cannot be accessed directly -> Uncommenting the line below
will cause an error
// [Link]([Link]); // Not Allowed

// Using a public method to access the private variable


[Link]();
}
}

Key Concepts Demonstrated


Classes & Objects – Person is a class, person1 is an object.
Access Specifiers:
• private → Accessible only within the class.
• protected → Accessible within the package & subclasses.
• default (no specifier) → Accessible within the same package.
• public → Accessible from anywhere.
Encapsulation – Private variables are accessed via public methods.

Example Output
Country: India
City: Mumbai
Age: 25
Name: Alice
Age: 25
City: Mumbai
Country: India
This program follows data encapsulation while controlling access levels via access
specifiers.

You might also like