Java Programs for City Sorting & Vowel Count
Java Programs for City Sorting & Vowel Count
length(); i++) {
cities from users and display them in ascending char ch = [Link](i);
and descending order. // Check if the character is a letter and NOT a
import [Link]; vowel
import [Link]; if ([Link](ch) && ch != 'a' && ch
import [Link]; != 'e' && ch != 'i' && ch != 'o' && ch != 'u') {
public class CitySorter { nonVowelCount++;
public static void main(String[] args) { }
Scanner scanner = new Scanner([Link]); }
[Link]("Enter the number o [Link]("The number of non-vowel
f cities (N): "); letters in \"" + word + "\" is: " + nonVowelCount);
int n = [Link](); [Link]();
[Link](); // Consume the newline }
character }
String[] cities = new String[n];
// Accepting city names from the user 5. Explain [Link] package and [Link]
[Link]("Enter the names of " + n + package.
" cities:"); • [Link] Package: This is the most fundamental
for (int i = 0; i < n; i++) { package in Java. It is automatically imported into
cities[i] = [Link](); every Java program without the need for an
} explicit import statement. It contains core classes
// Displaying cities in Ascending Order (A-Z) and interfaces that are essential for the language,
[Link](cities); such as:
[Link]("\nCities in Ascending o Object (the root class of all Java classes),
Order:"); o Wrapper classes (Integer, Double, Boolean),
for (String city : cities) { o String classes
[Link](city); (String, StringBuilder, StringBuffer),
} o Basic exception classes
// Displaying cities in Descending Order (Z-A) (Exception, Error, RuntimeException),
[Link](cities, [Link]()); o Math class (Math),
[Link]("\nCities in Descending o System class for standard I/O operations.
Order:");
for (String city : cities) { • [Link] Package: This is the utility
[Link](city); package and is one of the most widely used
} packages. It contains a collection of utility classes
[Link](); and interfaces that provide powerful data
} structures and helpful functions. It must be
} explicitly imported. Key components include:
o Collection Framework: Interfaces
like Collection, List, Set, Map and their
2. Write a java program that displays the number implementations
of non-vowels in the given words. (ArrayList, LinkedList, HashSet, HashMap).
import [Link]; o Date and Time Classes: Legacy classes
public class NonVowelCounter { like Date, Calendar, and modern API introduced
public static void main(String[] args) { in Java 8 (LocalDate, LocalTime).
Scanner scanner = new Scanner([Link]); o Utility Classes: Scanner (for input), Arrays (for
[Link]("Enter a word: "); array manipulation), Collections (for collection
String word = manipulation), Random (for generating random
[Link]().toLowerCase(); // Convert to numbers).
lower case for easy comparison
int nonVowelCount = 0;
1. Write a java program to access N number of for (int i = 0; i < [Link](); i++) {
cities from users and display them in ascending char ch = [Link](i);
and descending order. // Check if the character is a letter and NOT a
import [Link]; vowel
import [Link]; if ([Link](ch) && ch != 'a' && ch
import [Link]; != 'e' && ch != 'i' && ch != 'o' && ch != 'u') {
public class CitySorter { nonVowelCount++;
public static void main(String[] args) { }
Scanner scanner = new Scanner([Link]); }
[Link]("Enter the number o [Link]("The number of non-vowel
f cities (N): "); letters in \"" + word + "\" is: " + nonVowelCount);
int n = [Link](); [Link]();
[Link](); // Consume the newline }
character }
String[] cities = new String[n];
// Accepting city names from the user 5. Explain [Link] package and [Link]
[Link]("Enter the names of " + n + package.
" cities:"); • [Link] Package: This is the most fundamental
for (int i = 0; i < n; i++) { package in Java. It is automatically imported into
cities[i] = [Link](); every Java program without the need for an
} explicit import statement. It contains core classes
// Displaying cities in Ascending Order (A-Z) and interfaces that are essential for the language,
[Link](cities); such as:
[Link]("\nCities in Ascending o Object (the root class of all Java classes),
Order:"); o Wrapper classes (Integer, Double, Boolean),
for (String city : cities) { o String classes
[Link](city); (String, StringBuilder, StringBuffer),
} o Basic exception classes
// Displaying cities in Descending Order (Z-A) (Exception, Error, RuntimeException),
[Link](cities, [Link]()); o Math class (Math),
[Link]("\nCities in Descending o System class for standard I/O operations.
Order:");
for (String city : cities) { • [Link] Package: This is the utility
[Link](city); package and is one of the most widely used
} packages. It contains a collection of utility classes
[Link](); and interfaces that provide powerful data
} structures and helpful functions. It must be
} explicitly imported. Key components include:
o Collection Framework: Interfaces
like Collection, List, Set, Map and their
2. Write a java program that displays the number implementations
of non-vowels in the given words. (ArrayList, LinkedList, HashSet, HashMap).
import [Link]; o Date and Time Classes: Legacy classes
public class NonVowelCounter { like Date, Calendar, and modern API introduced
public static void main(String[] args) { in Java 8 (LocalDate, LocalTime).
Scanner scanner = new Scanner([Link]); o Utility Classes: Scanner (for input), Arrays (for
[Link]("Enter a word: "); array manipulation), Collections (for collection
String word = manipulation), Random (for generating random
[Link]().toLowerCase(); // Convert to numbers).
lower case for easy comparison
int nonVowelCount = 0;
3. Write a java program store/accept n number • Scanner ([Link]): A simple text
through command line and store all prime scanner used to parse primitive types and strings
numbers into an array and display elements of from input streams (like [Link]), files, or
array. strings. It uses delimiters (default is whitespace)
public class PrimeFromCLI { to break input into tokens.
public static void main(String[] args) { o Example: Scanner sc = new
// Check if command line arguments are Scanner([Link]); int x = [Link]();
provided • Math ([Link]): A utility class
if ([Link] == 0) { providing static methods for common
[Link]("Please provide numbers mathematical operations
as command line arguments."); (e.g., sqrt(), pow(), sin(), cos()), as well as
return; constants like PI and E. Its methods can be called
} directly using the class name ([Link](25)).
int[] numbers = new int[[Link]]; • Date ([Link]): A legacy class that
int[] primeArray = new int[[Link]]; // Max represents a specific instant in time, with
possible size millisecond precision. While still used, it's largely
int primeCount = 0; superseded by the more
modern [Link] package
// Parse command line arguments to integers (e.g., LocalDate, ZonedDateTime) introduced in
for (int i = 0; i < [Link]; i++) { Java 8 for better design and functionality.
numbers[i] = [Link](args[i]); • Class ([Link]): Instances of
} the Class class represent classes and interfaces in
// Find prime numbers a running Java application. It is the entry point for
for (int num : numbers) { all of the Reflection API, which allows a program
if (isPrime(num)) { to inspect and manipulate itself. You can get
primeArray[primeCount] = num; a Class object
primeCount++; using [Link](), .class syntax,
} or [Link]().
} 7. What is data type and list primitive and non-
// Display the prime numbers array primitive data type.
[Link]("Prime numbers from the A data type defines the type of value a variable can
given list:"); hold, the operations that can be performed on it, and
for (int i = 0; i < primeCount; i++) { the amount of memory it occupies.
[Link](primeArray[i] + " "); • Primitive Data Types: These are the basic
} building blocks of the Java language. They are
} predefined by the language and named by a
// Method to check if a number is prime reserved keyword. They hold a single value of
private static boolean isPrime(int num) { their type.
if (num <= 1) { o Numeric:
return false; ▪ byte, short, int, long (for integers)
} ▪ float, double (for floating-point numbers)
for (int i = 2; i <= [Link](num); i++) { o Non-Numeric:
if (num % i == 0) { ▪ char (for single characters)
return false; ▪ boolean (for true/false values)
} • Non-Primitive Data Types (Reference
} Types): These are created by the programmer.
return true; They do not store the value directly; instead, they
} store the memory address (reference) of the
} object. The size is not fixed.
To Run: java PrimeFromCLI 7 12 19 23 45 53 o String *) Arrays
6. Explain Scanner, Math, Date, Class in Java. o Classes (e.g., Scanner, ArrayList)
3. Write a java program store/accept n number • Scanner ([Link]): A simple text
through command line and store all prime scanner used to parse primitive types and strings
numbers into an array and display elements of from input streams (like [Link]), files, or
array. strings. It uses delimiters (default is whitespace)
public class PrimeFromCLI { to break input into tokens.
public static void main(String[] args) { o Example: Scanner sc = new
// Check if command line arguments are Scanner([Link]); int x = [Link]();
provided • Math ([Link]): A utility class
if ([Link] == 0) { providing static methods for common
[Link]("Please provide numbers mathematical operations
as command line arguments."); (e.g., sqrt(), pow(), sin(), cos()), as well as
return; constants like PI and E. Its methods can be called
} directly using the class name ([Link](25)).
int[] numbers = new int[[Link]]; • Date ([Link]): A legacy class that
int[] primeArray = new int[[Link]]; // Max represents a specific instant in time, with
possible size millisecond precision. While still used, it's largely
int primeCount = 0; superseded by the more
modern [Link] package
// Parse command line arguments to integers (e.g., LocalDate, ZonedDateTime) introduced in
for (int i = 0; i < [Link]; i++) { Java 8 for better design and functionality.
numbers[i] = [Link](args[i]); • Class ([Link]): Instances of
} the Class class represent classes and interfaces in
// Find prime numbers a running Java application. It is the entry point for
for (int num : numbers) { all of the Reflection API, which allows a program
if (isPrime(num)) { to inspect and manipulate itself. You can get
primeArray[primeCount] = num; a Class object
primeCount++; using [Link](), .class syntax,
} or [Link]().
} 7. What is data type and list primitive and non-
// Display the prime numbers array primitive data type.
[Link]("Prime numbers from the A data type defines the type of value a variable can
given list:"); hold, the operations that can be performed on it, and
for (int i = 0; i < primeCount; i++) { the amount of memory it occupies.
[Link](primeArray[i] + " "); • Primitive Data Types: These are the basic
} building blocks of the Java language. They are
} predefined by the language and named by a
// Method to check if a number is prime reserved keyword. They hold a single value of
private static boolean isPrime(int num) { their type.
if (num <= 1) { o Numeric:
return false; ▪ byte, short, int, long (for integers)
} ▪ float, double (for floating-point numbers)
for (int i = 2; i <= [Link](num); i++) { o Non-Numeric:
if (num % i == 0) { ▪ char (for single characters)
return false; ▪ boolean (for true/false values)
} • Non-Primitive Data Types (Reference
} Types): These are created by the programmer.
return true; They do not store the value directly; instead, they
} store the memory address (reference) of the
} object. The size is not fixed.
To Run: java PrimeFromCLI 7 12 19 23 45 53 o String *) Arrays
6. Explain Scanner, Math, Date, Class in Java. o Classes (e.g., Scanner, ArrayList)
4. What is Java? Explain at least 5 features in 2. Instance Variable (Non-Static Field): A
Java. variable declared inside a class but outside any
Java is a high-level, robust, object-oriented, and method. It is bound to an object (instance) of the
platform-independent programming language class. Each object has its own copy.
developed by Sun Microsystems (now owned by o Example: class Student { String name; //
Oracle). It follows the principle of "Write Once, Run instance variable }
Anywhere" (WORA), meaning compiled Java code 3. Static Variable (Class Variable): A variable
can run on all platforms that support Java without the declared with the static keyword. It is associated
need for recompilation. with the class itself, not with any object. Only
Five Key Features of Java: one copy exists and is shared among all instances
1. Platform Independent: Java code is compiled of the class.
into bytecode, which is executed by the Java o Example: class Student { static String
Virtual Machine (JVM). This allows Java schoolName = "ABC School"; }
programs to run on any device equipped with a
JVM, making it highly portable.
2. Object-Oriented: Java is built around the 9. What is method of overloading and overriding
concepts of objects and classes. It supports with example.
fundamental OOP principles like encapsulation, • Method Overloading (Compile-time
inheritance, polymorphism, and abstraction, Polymorphism): This occurs when multiple
which help in creating modular and reusable methods in the same class have the same
code. name but different parameters (different type,
3. Simple and Familiar: Java's syntax is similar to number, or order of parameters). Return type
C and C++, but it eliminates complex and error- alone is not sufficient to overload a method.
prone features like explicit pointers, operator class MathOps {
overloading, and multiple inheritance, making it // Overloaded add methods
easier to learn and use. int add(int a, int b) { return a + b; }
4. Secure: Java provides a secure execution double add(double a, double b) { return a + b; } //
environment. Features like the bytecode verifier, Different parameter type
lack of explicit pointers, and a security manager int add(int a, int b, int c) { return a + b + c; } //
that defines access rules for classes make it Different number of parameters
suitable for developing tamper-free and virus-free }
systems.
5. Multithreading: Java has built-in support for • Method Overriding (Run-time
multithreaded programming, allowing concurrent Polymorphism): This occurs when
execution of two or more parts of a program to a subclass provides a specific implementation
maximize CPU utilization and performance. for a method that is already defined in
its superclass. The method must have the same
name, return type, and parameters.
8. What is variable and types of variable with class Animal {
example. void makeSound() { [Link]("Animal
A variable is a named memory location used to store makes a sound"); }
data values that can be changed during program }
execution. class Dog extends Animal {
Types of Variables in Java: @Override
1. Local Variable: A variable declared inside a void makeSound() { [Link]("Dog
method, constructor, or block. It must be barks"); } // Overridden method
initialized before use and is only accessible }
within its scope.
o Example: void myMethod() { int localVar =
10; }
4. What is Java? Explain at least 5 features in 5. Instance Variable (Non-Static Field): A
Java. variable declared inside a class but outside any
Java is a high-level, robust, object-oriented, and method. It is bound to an object (instance) of the
platform-independent programming language class. Each object has its own copy.
developed by Sun Microsystems (now owned by o Example: class Student { String name; //
Oracle). It follows the principle of "Write Once, Run instance variable }
Anywhere" (WORA), meaning compiled Java code 6. Static Variable (Class Variable): A variable
can run on all platforms that support Java without the declared with the static keyword. It is associated
need for recompilation. with the class itself, not with any object. Only
Five Key Features of Java: one copy exists and is shared among all instances
6. Platform Independent: Java code is compiled of the class.
into bytecode, which is executed by the Java o Example: class Student { static String
Virtual Machine (JVM). This allows Java schoolName = "ABC School"; }
programs to run on any device equipped with a
JVM, making it highly portable.
7. Object-Oriented: Java is built around the 9. What is method of overloading and overriding
concepts of objects and classes. It supports with example.
fundamental OOP principles like encapsulation, • Method Overloading (Compile-time
inheritance, polymorphism, and abstraction, Polymorphism): This occurs when multiple
which help in creating modular and reusable methods in the same class have the same
code. name but different parameters (different type,
8. Simple and Familiar: Java's syntax is similar to number, or order of parameters). Return type
C and C++, but it eliminates complex and error- alone is not sufficient to overload a method.
prone features like explicit pointers, operator class MathOps {
overloading, and multiple inheritance, making it // Overloaded add methods
easier to learn and use. int add(int a, int b) { return a + b; }
9. Secure: Java provides a secure execution double add(double a, double b) { return a + b; } //
environment. Features like the bytecode verifier, Different parameter type
lack of explicit pointers, and a security manager int add(int a, int b, int c) { return a + b + c; } //
that defines access rules for classes make it Different number of parameters
suitable for developing tamper-free and virus-free }
systems.
10. Multithreading: Java has built-in support for • Method Overriding (Run-time
multithreaded programming, allowing concurrent Polymorphism): This occurs when
execution of two or more parts of a program to a subclass provides a specific implementation
maximize CPU utilization and performance. for a method that is already defined in
its superclass. The method must have the same
name, return type, and parameters.
8. What is variable and types of variable with class Animal {
example. void makeSound() { [Link]("Animal
A variable is a named memory location used to store makes a sound"); }
data values that can be changed during program }
execution. class Dog extends Animal {
Types of Variables in Java: @Override
4. Local Variable: A variable declared inside a void makeSound() { [Link]("Dog
method, constructor, or block. It must be barks"); } // Overridden method
initialized before use and is only accessible }
within its scope.
o Example: void myMethod() { int localVar =
10; }
11. Short note on class and object with an example. 2. Multi-Dimensional Array: An array of arrays.
• Class: A class is a blueprint or a template from The most common is the two-dimensional
which individual objects are created. It defines array, which can be thought of as a table with
the properties (attributes as variables) and rows and columns.
behaviors (actions as methods) that the objects o Declaration: int[][] matrix;
created from it will have. It is a logical entity. o Instantiation: matrix = new int[3][3]; // A 3x3
• Object: An object is a real-world entity that matrix
has state and behavior. It is an instance of a o Initialization: int[][] matrix = { {1, 2, 3}, {4,
class. When a class is defined, no memory is 5, 6} };
allocated until an object of that class is created. 10. Difference Between Constructor and Method
Example: 1. **Purpose**
// Class (Blueprint) Constructor:** Used to **initialize the state** of a
class Car { newly created object. Its primary role is to assign
// Attributes (State) initial values to the object's attributes.
String color; Method:** Used to **expose the behavior** of an
String model; object. It defines the operations or actions that the
object can perform.
// Method (Behavior) 2. Invocation
void drive() { Constructor: Invoked implicitly by the Java Virtual
[Link](model + " is driving."); Machine (JVM) when the `new` keyword is used to
} instantiate an object.
} Method: Invoked explicitly by the programmer using
public class Main { an object reference and the dot (`.`) operator (e.g.,
public static void main(String[] args) { `[Link]()`).
// Creating Objects (Instances of the Car class) 3. Return Type
Car car1 = new Car(); Constructor: Has no return type, not even `void`.
[Link] = "Red"; Method: Must have a return type. If it does not return
[Link] = "Toyota"; a value, the return type must be declared as `void`.
[Link](); // Output: Toyota is driving. 4. Name
Constructor: Must have the exact same name as the
Car car2 = new Car(); class it belongs to (case-sensitive).
[Link] = "Blue"; Method: Can have any valid identifier name (usually
[Link] = "Honda"; a verb) and follows standard naming conventions like
[Link](); // Output: Honda is driving. camelCase.
} 5. Inheritance
} Constructor: Cannot be inherited by a subclass. A
subclass constructor can, however, call a superclass
12. What is array explain its types. constructor using the `super()` keyword.
An array is a container object that holds a fixed Method: Can be inherited by a subclass and can also
number of values of a single type. The length of an be overridden to provide a specific implementation.
array is established when the array is created and 6. Default Availability
cannot be changed. Each item in an array is called Constructor: If no constructor is defined in a class, the
an element, and each element is accessed by its Java compiler automatically provides a default no-
numerical index. argument constructor.
Types of Arrays: Method: The compiler does not provide any default
1. Single-Dimensional Array: A linear array that methods. All methods must be explicitly defined by
stores elements in a single row. the programmer.
o Declaration: int[] arr; or int arr[];
o Instantiation: arr = new int[5]; // Array of 5
integers
11. Short note on class and object with an example. 4. Multi-Dimensional Array: An array of arrays.
• Class: A class is a blueprint or a template from The most common is the two-dimensional
which individual objects are created. It defines array, which can be thought of as a table with
the properties (attributes as variables) and rows and columns.
behaviors (actions as methods) that the objects o Declaration: int[][] matrix;
created from it will have. It is a logical entity. o Instantiation: matrix = new int[3][3]; // A 3x3
• Object: An object is a real-world entity that matrix
has state and behavior. It is an instance of a o Initialization: int[][] matrix = { {1, 2, 3}, {4,
class. When a class is defined, no memory is 5, 6} };
allocated until an object of that class is created. 10. Difference Between Constructor and Method
Example: 1. **Purpose**
// Class (Blueprint) Constructor:** Used to **initialize the state** of a
class Car { newly created object. Its primary role is to assign
// Attributes (State) initial values to the object's attributes.
String color; Method:** Used to **expose the behavior** of an
String model; object. It defines the operations or actions that the
object can perform.
// Method (Behavior) 2. Invocation
void drive() { Constructor: Invoked implicitly by the Java Virtual
[Link](model + " is driving."); Machine (JVM) when the `new` keyword is used to
} instantiate an object.
} Method: Invoked explicitly by the programmer using
public class Main { an object reference and the dot (`.`) operator (e.g.,
public static void main(String[] args) { `[Link]()`).
// Creating Objects (Instances of the Car class) 3. Return Type
Car car1 = new Car(); Constructor: Has no return type, not even `void`.
[Link] = "Red"; Method: Must have a return type. If it does not return
[Link] = "Toyota"; a value, the return type must be declared as `void`.
[Link](); // Output: Toyota is driving. 4. Name
Constructor: Must have the exact same name as the
Car car2 = new Car(); class it belongs to (case-sensitive).
[Link] = "Blue"; Method: Can have any valid identifier name (usually
[Link] = "Honda"; a verb) and follows standard naming conventions like
[Link](); // Output: Honda is driving. camelCase.
} 5. Inheritance
} Constructor: Cannot be inherited by a subclass. A
subclass constructor can, however, call a superclass
12. What is array explain its types. constructor using the `super()` keyword.
An array is a container object that holds a fixed Method: Can be inherited by a subclass and can also
number of values of a single type. The length of an be overridden to provide a specific implementation.
array is established when the array is created and 6. Default Availability
cannot be changed. Each item in an array is called Constructor: If no constructor is defined in a class, the
an element, and each element is accessed by its Java compiler automatically provides a default no-
numerical index. argument constructor.
Types of Arrays: Method: The compiler does not provide any default
3. Single-Dimensional Array: A linear array that methods. All methods must be explicitly defined by
stores elements in a single row. the programmer.
o Declaration: int[] arr; or int arr[];
o Instantiation: arr = new int[5]; // Array of 5
integers