[Go to site: main page, start]

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

Java Programming Basics and Exercises

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)
24 views11 pages

Java Programming Basics and Exercises

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.

Common questions

Powered by AI

An array of numbers is initialized, and functions are used to encapsulate logic for computing the sum, finding maximum and minimum values, and sorting. 'calculateSum' iterates through the array elements to sum them. 'findMax' and 'findMin' each iterate to compare elements against a stored value to find the maximum or minimum, respectively. 'sortArray' uses Arrays.sort() to sort elements in ascending order .

On Windows, setting environment variables involves accessing System Properties, navigating to Advanced System Settings, and editing the Path under System Variables to include the JDK's bin directory. JAVA_HOME is also set to the JDK installation path . On Linux/macOS, setting environment variables is typically not necessary if JDK is installed using package managers, as these systems automatically manage paths during installation .

Closing the Scanner object is important to avoid resource leaks, particularly when it's associated with a finite resource like System.in. Not closing it can lead to memory leaks and unexpected behavior in file-based Scanners, as open resources might still be considered in use by the JVM or underlying operating system, preventing further operations or leading to application errors .

Access specifiers such as private, protected, and public control visibility of class members, thereby supporting encapsulation by hiding internal states and functionalities. Private restricts access to within the class, protecting data by preventing external access. Protected allows access within packages and subclasses, and public permits access from anywhere. This structure helps safeguard against unauthorized access, preserving data integrity and enabling controlled interaction through public methods .

The 'switch-case' construct is significant for tasks involving multiple discrete conditions that must be checked against the same variable. It provides clearer syntax and potentially improves performance by reducing the overhead associated with multiple 'if-else' comparisons. The fall-through behavior of switch cases is another feature that can be useful in specific scenarios, simplifying code and improving readability by grouping cases with shared logic .

Initially, open Command Prompt and navigate to the directory containing the .java file using the 'cd' command. Compile the program using the 'javac' command followed by the filename, e.g., 'javac HelloWorld.java'. This generates a .class file. To execute, use the 'java' command followed by the class name without the .class extension, e.g., 'java HelloWorld' .

Loops, such as 'for', 'while', or 'do-while', execute a block of code repeatedly, a set number of times or until a condition is met, reducing redundancy and manual effort. In a program that generates a sequence of numbers, a 'for' loop can efficiently iterate from 1 to the specified upper limit, incrementing automatically and executing the contained statements in each iteration .

The Scanner class can read input types such as strings, integers, and doubles using methods like nextLine(), nextInt(), and nextDouble(). Potential pitfalls include input mismatch exceptions if user input doesn't match the expected type and resource leaks if the Scanner is not closed after use. Care must be taken to handle exceptions and ensure the correct sequence of input operations, particularly when mixing different types .

User input is handled using the Scanner class to read an integer. An if-else statement checks if the number is even or odd. A switch-case determines if it's positive, negative, or zero. Arithmetic operations like addition, multiplication, and division are performed directly on the input. A for loop is used to print numbers from 1 to the entered number .

Organizing code into functions encapsulates the logic for operations like summing elements, finding extrema, or sorting, improving readability and reusability. It allows separate testing and debugging of each function, simplifies the main code body, and enables easy updates and extensions to individual operations without affecting others. This modular approach enhances clarity, aids maintenance, and encourages best practices in code development .

You might also like