0% found this document useful (0 votes)
11 views18 pages

Java Example Programs for Beginners

The document contains a series of practical Java programming exercises, each demonstrating different concepts such as command line arguments, variable manipulation, input handling, and exception management. Each practical includes a code snippet that illustrates the specific task to be accomplished, such as calculating averages, checking for palindromes, and demonstrating inheritance and interfaces. The exercises range from basic to more advanced topics, providing a comprehensive overview of Java programming techniques.

Uploaded by

keshavkarn173
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)
11 views18 pages

Java Example Programs for Beginners

The document contains a series of practical Java programming exercises, each demonstrating different concepts such as command line arguments, variable manipulation, input handling, and exception management. Each practical includes a code snippet that illustrates the specific task to be accomplished, such as calculating averages, checking for palindromes, and demonstrating inheritance and interfaces. The exercises range from basic to more advanced topics, providing a comprehensive overview of Java programming techniques.

Uploaded by

keshavkarn173
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

PRACTICAL - 01

1. Write a program in java which prints your name using command line arguments.

public class PrintName {

public static void main(String[] args) {

if ([Link] > 0) {

[Link](args[0]);

}
PRACTICAL - 02
2. Write a program in java which enters three number using command line arguments and print
average of the number

public class Threenumavg {

public static void main(String[] args) {

if ([Link] == 3) {

double first = [Link](args[0]);

double second = [Link](args[1]);

double third = [Link](args[2]);

double average = (first + second + third) / 3;

[Link](average);

}
PRACTICAL - 03
3. Write a program to swap the value of 2 variables without using 3rd variable

public class Swapping {

public static void main(String[] args) {

int first = 10;

int second = 20;

first = first + second;

second = first - second;

first = first - second;

[Link]("first = " + first);

[Link]("second = " + second);

}
PRACTICAL - 04
4. Write a program to calculate the sum of digits of a given integer no

import [Link];

public class DigitsSum {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int new_nums = [Link]();

int sum = 0;

while (new_nums != 0) {

sum += new_nums % 10;

new_nums /= 10;

[Link](sum);

}
PRACTICAL - 05
5. Write a program to compute the sum of the first and last digit of a given number.

import [Link];

public class SumDigits {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int nums = [Link]();

int last = nums % 10;

while (nums >= 10) {

nums /= 10;

int first = nums;

[Link](first + last);

}
PRACTICAL - 06
6. Write a program in java which enter the number using Data Input Stream and check entered
number is even or odd.

import [Link];

public class CheckOddEven {

public static void main(String[] args) throws Exception {

DataInputStream dis = new DataInputStream([Link]);

int number = [Link]([Link]());

if (number % 2 == 0) {

[Link]("Even");

} else {

[Link]("Odd");

}
PRACTICAL - 07
7. Write an application that reads a string and determines whether it is a palindrome.

import [Link];

public class CheckingPalindrome {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String str_name = [Link]();

String reversed_str = new StringBuilder(str_name).reverse().toString();

if (str_name.equals(reversed_str)) {

[Link]("Palindrome");

} else {

[Link]("Not a Palindrome");

}
PRACTICAL - 08
8. Write a program to enter a sentence form keyboard and also find all the words in that sent
starting character as vowel

import [Link];

public class VowelCheck {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String new_word = [Link]();

String[] vowel_words = new_word.split(" ");

for (String isword : vowel_words) {

char firstChar = [Link]([Link](0));

if (firstChar == 'a' || firstChar == 'e' || firstChar == 'i' || firstChar == 'o' || firstChar


== 'u') {

[Link](isword);

}
PRACTICAL - 09
9. Write a Program in java which creates the array of size 5; find the sum and average o numbers.

import [Link];

public class SumandAvg {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int[] nums = new int[5];

int sum = 0;

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

nums[i] = [Link]();

sum += nums[i];

double average = sum / 5.0;

[Link]("Sum: " + sum);

[Link]("Average: " + average);

}
PRACTICAL - 10
10. Create a java program that has three version of add method which can add two, three,
integers.

public class Adding {

public int add(int first, int second) {

return first + second;

public int add(int first, int second, int third) {

return first + second + third;

public static void main(String[] args) {

Adding obj = new Adding();

[Link]([Link](4, 16));

[Link]([Link](2,7,9));

}
PRACTICAL - 11
11. Program illustrating Classes and Objects.

class Pirate {

String Pirate_name;

int bounty;

void display() {

[Link]("Pirate: " + Pirate_name);

[Link]("Bounty: " + bounty);

public static void main(String[] args) {

Pirate New_gen = new Pirate();

New_gen.Pirate_name = "Monkey D. Luffy";

New_gen.bounty = 320;

[Link]();

}
PRACTICAL - 12
12. Program illustrating Method Overloading and Method Overriding.

class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat Meows");
}
void sound(String type) {
[Link]("Cat " + type + "s");
}
public static void main(String[] args) {
Animal a = new Animal();
[Link]();
Cat c = new Cat();
[Link]();
[Link]("meow meow");
}
}
PRACTICAL - 13
13. Program illustrating concept of Interface.

interface Anime {

void Anime_name();

class Newgen_Anime implements Anime {

public void Anime_name() {

[Link]("Demon Slayer");

public class InterfaceExample {

public static void main(String[] args) {

Anime new_name = new Newgen_Anime();

New_name.Anime_name();

}
PRACTICAL - 14
14. Program illustrating use of Final and Super keyword.

class Parent {

final int a = 26;

void display() {

[Link]("Parent class");

class Child extends Parent {

void display() {

[Link]();

[Link]("Child class");

public static void main(String[] args) {

Child new_obj = new Child();

New_obj.display();

// a = 35; // Error: You Cannot assign a value to final variable 'a'

}
PRACTICAL - 15
15. Program that illustrates the Creation of simple package.

package mypackage;

public class Sample_Package {

public void anime_name() {

[Link]("The famous anime name is Dragon Ball!");

}
PRACTICAL - 16
16. Program that illustrates the Accessing of a package.

import [Link];

public class AccessPackage {

public static void main(String[] args) {

Sample_Package new_name = new Sample_Package();

new_name.anime_name();

}
PRACTICAL - 17
17. Program that illustrates the Handling of predefined exceptions.

import [Link];

public class PreException_example {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

try {

int first = 24;

int second = [Link]();

[Link](first / second);

} catch (ArithmeticException e) {

[Link]("Error: Division by zero");

}
PRACTICAL - 18
18. Program that illustrates the Handling of user defined exceptions.

class InvalidAnimeException extends Exception {

public InvalidAnimeException(String message) {

super(message);

public class UserException_example {

public static void main(String[] args) {

try {

String name = "Haikyuu";

if (![Link]("Berserk")) {

throw new InvalidAnimeException("Invalid Anime Name");

catch (InvalidAnimeException e) {

[Link]([Link]());

Common questions

Powered by AI

Java packages offer significant organizational benefits by grouping related classes and interfaces into namespaces, reducing naming conflicts and enhancing manageability, as highlighted by creating and accessing simple packages. This modular structure enhances code maintenance, readability, and reusability, allowing developers to logically separate functionalities . However, packages can induce complexity by requiring additional steps and understanding to manage dependencies and hierarchies, possibly complicating the project structure for larger or unfamiliar projects. Access rights and package-private access levels can also limit visibility, impacting code sharing across packages unless explicitly managed. Thus, while packages introduce helpful structural organization, they necessitate additional considerations for effective use .

An interface in Java is a reference type that can contain abstract methods and static constants, serving as a contract that classes can implement. Interfaces support multiple inheritance by allowing a class to implement multiple interfaces. This Java feature is essential for abstraction and decoupling architecture, thereby promoting modularity and reducing dependency. The provided example demonstrates the 'Anime' interface with a method 'Anime_name.' The 'Newgen_Anime' class implements this interface by providing a specific implementation of 'Anime_name,' adhering to the contract set by the interface. Thus, interfaces let developers define capabilities a class must possess without dictating the class hierarchies, facilitating loose coupling and the implementation of design patterns .

Method overloading and method overriding are fundamental concepts in object-oriented programming that allow Java programs to achieve polymorphism. Method overloading occurs when multiple methods with the same name exist in a class but differ in parameters; it allows different uses of a method with varying inputs. In the Java example, the "Cat" class overloads the 'sound' method by providing two versions: one with no parameter and another with a String parameter . Method overriding, seen in inheritance scenarios, allows a subclass to provide a specific implementation of a method that is already defined in its parent class, thereby enabling dynamic polymorphism. In the same example, the 'Cat' class overrides the 'sound' method originally defined in the 'Animal' class, thus altering its behavior .

The Java program swaps the values of two variables by using arithmetic operations to manage the swap without needing a third variable. Initially, the sum of both original variable values is assigned to the first variable. Then, by subtracting the current value of the second variable from the updated first variable, the original value of the first variable is isolated and stored in the second variable. Lastly, subtracting the current second variable value from the updated first variable isolates the original value of the second variable and assigns it to the first variable. This approach effectively swaps the values without using a third temporary variable .

The 'final' and 'super' keywords in Java play critical roles in controlling inheritance and method behavior. The 'final' keyword, when applied to a variable or method, indicates that the variable cannot be reassigned or a method cannot be overridden, respectively, ensuring immutability and consistent behavior, as seen when declaring constant variables . The 'super' keyword is used within a subclass to invoke a method or constructor from its immediate superclass, facilitating reuse and extension of the existing functionality. In inheritance, 'super' helps to call the parent class's overridden method to retain original behavior while appending additional capabilities, promoting code reuse and reducing redundancy .

The provided Java program uses 'DataInputStream' to read data from the console, parsing the input into an integer to determine if it's even or odd by checking the remainder of division by two. Using 'DataInputStream' accesses low-level handling for directly reading bytes, subsequently interpreting them as needed . Alternatives like 'Scanner' or 'BufferedReader' provide higher-level abstractions, offering more flexibility and ease in parsing different data types or managing input errors, often considered more user-friendly for diverse input processing. These options inherently offer different efficiencies and error handling capabilities, with developers selecting based on specific requirements .

The program depicting object creation and manipulation underscores key object-oriented principles such as encapsulation, instantiation, and interaction between objects. Encapsulation is showcased by defining 'Pirate' with private fields and methods to govern access and modification, supporting data hiding. Instantiation, the creation of instances from a class, facilitates object-oriented interactions and is demonstrated when creating a 'Pirate' object instance with its attributes assigned values . Furthermore, by invoking methods on object instances to manipulate and display data, this program evidences the encapsulation of behavior with state. These aspects embody how classes and objects manifest modularity, data security, code reuse, and coherent interaction in an OOP system .

The Java program for calculating the average of three numbers uses command line arguments to receive the numbers as input. It first checks if exactly three arguments are passed to ensure proper input handling. Each string argument is parsed into a double using 'Double.parseDouble' for arithmetic operations. These numbers are then summed and the total is divided by three to compute the average, which is subsequently printed to the console. This approach exemplifies how command line arguments can be used for input during program execution .

Java provides mechanisms to handle both predefined and user-defined exceptions to ensure robust and error-free code. Predefined exceptions, such as 'ArithmeticException,' are caught using try-catch blocks to handle common runtime errors like division by zero gracefully, as illustrated when dividing an integer by zero generates a controlled error message rather than a crash . User-defined exceptions allow developers to create custom exception classes, thus making error handling specific to the application’s context. The example of 'InvalidAnimeException' shows how a custom exception class is defined by extending the 'Exception' class, allowing program-specific responses to unexpected states, and demonstrating more tailored error management .

The provided Java program determines whether a string is a palindrome by comparing the original string to its reversed version. It reads the input string and reverses it by utilizing the 'StringBuilder' class to reverse the sequence of characters. The original string and the reversed string are then compared using the 'String.equals' method. If both strings are identical, the input is a palindrome; otherwise, it is not. This method effectively leverages string manipulation to identify symmetrical patterns, demonstrating fundamental string operations in Java .

You might also like