0% found this document useful (0 votes)
41 views7 pages

Java Programming Concepts and Examples

The document provides a comprehensive overview of Java programming concepts, including code examples for factorial calculation, loops, arrays, and string manipulation. It also covers basic Java questions about features, JVM, data types, control statements, and exception handling. Additionally, it includes programming exercises for tasks like checking prime numbers, printing Fibonacci series, and handling file operations.

Uploaded by

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

Java Programming Concepts and Examples

The document provides a comprehensive overview of Java programming concepts, including code examples for factorial calculation, loops, arrays, and string manipulation. It also covers basic Java questions about features, JVM, data types, control statements, and exception handling. Additionally, it includes programming exercises for tasks like checking prime numbers, printing Fibonacci series, and handling file operations.

Uploaded by

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

Unit 3 – Java Programming

1. Give the output of the following Java code segment (Factorial code).
int Num=4;
int Fact=1;
for (int i=1;i<=Num;i++)
{
Fact*=i;
[Link](Fact);
}

Answer:The program calculates the factorial of a number using a loop. If input n = 5, the
output will be 120.
Explanation:
1 × 2 × 3 × 4 × 5 = 120.

[Link] the syntax errors in the given Java code (while loop example). Rewrite the
following code after correcting the syntax errors, underline each correction made:
int number= = 1;
while (number c = 5 );
{
[Link]("Square of " + number);
[Link]("=", number* number);
Number += 1 ;
}
[Link] the following for loop to an equivalent while loop.
int x = 4 , Y = 3;
int pow = 1;
for (int i = 1, i<=Y;i++)
Pow* = X ;
[Link](Pow);

[Link] x = 4, Y = 3;

int pow = 1;

int i = 1; // Initialization of loop counter

while (i <= Y) { // Loop condition

pow *= x; // Loop body

i++; // Update statement

[Link](pow);

4. Give the output of following code:String myString = "Welcome to Java";


a)[Link] ([Link]("Session"));
b)[Link] ([Link]());
c)[Link] ([Link]("to","2"));
d) Expand the term OOP.

Answer.a)Welcome to JavaSession

b)15

c)Welcome 2 Java

d) object oriented programming

[Link] the following code and answer the following questions:


static int MyMethod(int N)
{
return (N * N);
}
public static void main(String[] args)
{
[Link](MyMethod(7));
}
i) Name the user-defined method.
ii) What will be the output on executing the above code?
iii) Explain exception handling.

Answer.a)The user-defined method is MyMethod.

b)The method MyMethod calculates the square of its input. When called with the argument
7, it returns 7 * 7, which is 49.

c) Learn from book

6.a)What is an array in Java? Write a short code example.


b)Write Java code to do the following:
i) Create an array Marks that stores values 78,65,85,91,82
ii) Display the average stored in the array Marks.
iii) To print all the values of the array Marks using a loop.

Answer:
An array is a collection of elements of the same data type stored in contiguous memory.
Example:
int arr[] = {1,2,3,4,5};
for(int i : arr)
[Link](i + ' ');

ii)public class ArrayOperations {

public static void main(String[] args) {

// i) Create an array Marks that stores values 78, 65, 85, 91, 82

int[] marks = {78, 65, 85, 91, 82};

// ii) To print all the values of the array Marks using a loop
[Link]("Marks in the array:");

for (int i = 0; i < [Link]; i++) {

[Link](marks[i]);

// iii) Display the average stored in the array Marks.

double sum = 0;

for (int mark : marks) {

sum += mark;

double average = sum / [Link];

[Link]("Average of the marks: " + average);

[Link] a Java program to find factorial of a number using loop.


class Factorial {
public static void main(String args[]) {
int n = 5, fact = 1;
for(int i = 1; i <= n; i++) {
fact = fact * i;
}
[Link]("Factorial of " + n + " is: " + fact);
}
}
[Link] a Java program to check whether a number is prime or not.
class PrimeCheck {
public static void main(String args[]) {
int num = 7;
boolean isPrime = true;
for(int i = 2; i <= num/2; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}
if(isPrime)
[Link](num + " is a Prime Number");
else
[Link](num + " is not a Prime Number");
}
}
[Link] a Java program to print Fibonacci series.
// Program to print Fibonacci Series
class FibonacciSeries {
public static void main(String args[]) {
int n1 = 0, n2 = 1, n3, i, count = 10;

[Link]("Fibonacci Series: " + n1 + " " + n2);

for (i = 2; i < count; i++) {


n3 = n1 + n2;
[Link](" " + n3);
n1 = n2;
n2 = n3;
}
}
}
[Link] a Java program to check whether a string is palindrome or not.
class Palindrome {
public static void main(String args[]) {
String str = "MADAM";
String rev = "";
for(int i = [Link]() - 1; i >= 0; i--) {
rev = rev + [Link](i);
}
if([Link](rev))
[Link](str + " is Palindrome");
else
[Link](str + " is not Palindrome");
}
}
[Link] a Java program to find the largest of three numbers.
class Largest {
public static void main(String args[]) {
int a = 10, b = 25, c = 15;
if(a > b && a > c)
[Link](a + " is largest");
else if(b > c)
[Link](b + " is largest");
else
[Link](c + " is largest");
}
}
[Link] a Java program to calculate sum of digits of a number.
class SumOfDigits {
public static void main(String args[]) {
int num = 1234, sum = 0;

while(num != 0) {
sum = sum + num % 10;
num = num / 10;
}

[Link]("Sum of digits = " + sum);


}
}
[Link] a Java program to swap two numbers without using a third variable.
class SwapNumbers {
public static void main(String args[]) {
int a = 5, b = 10;
[Link]("Before swap: a = " + a + ", b = " + b);

a = a + b;
b = a - b;
a = a - b;

[Link]("After swap: a = " + a + ", b = " + b);


}
}
Basic Questions
14. What is Java?
15.. Write any five features of Java.
16. What is JVM, JRE, and JDK?
17. What is the difference between compiler and interpreter?
18. What do you mean by platform independence in Java?
19. What is bytecode?
20. What are variables and data types in Java?
21. What is the difference between primitive and non-primitive data types?
22. What are operators in Java? List types of operators with examples.
23. Define identifier and literals.
Control Statements**
1. What are conditional statements in Java?
2. Explain `if`, `if-else`, and `nested if` statements with examples.
3. What is a `switch` statement? Write its syntax.
4. What are loops? Explain `for`, `while`, and `do-while` loops.
5. What is the difference between `break` and `continue` statements?
6. What is the difference between entry-controlled and exit-controlled loops?
**3. Arrays and Strings**
1. What is an array?
2. How do you declare and initialize an array in Java?
3. What is the difference between one-dimensional and two-dimensional arrays?
4. What is a string in Java?
5. Differentiate between `String` and `StringBuffer` class.
6. Write two methods of `String` class with their uses.
*4. Functions / Methods**
1. What is a method in Java?
2. What is the difference between call by value and call by reference?
3. What is method overloading?
4. Why do we use `return` statement?
5. What is recursion? Give an example.
5. Classes and Objects**
1. Define class and object.
2. What is the difference between class and object?
3. What is a constructor?
4. Differentiate between default constructor and parameterized constructor.
5. What is the use of the `this` keyword?
6. What is encapsulation?
7. What is inheritance? List its types.
8. What is polymorphism?
9. Explain the concept of data abstraction.
10. What are access specifiers? List them.
*6. Exception Handling**
1. What is exception handling?
2. What is an exception?
3. List and explain any two types of exceptions.
4. What is the difference between checked and unchecked exceptions?
5. Explain the use of `try`, `catch`, `finally`, `throw`, and `throws`.
6. Write a short note on runtime errors in Java.
7. File Handling (if included in syllabus)**
1. What is file handling?
2. How to open and close a file in Java?
3. What are input and output streams?
4. What is the difference between `FileReader` and `BufferedReader`?
5. Write a Java statement to read a line from a text file.
*8. General / Short Questions**
1. Who developed Java and in which year?
2. What is the extension of Java source code file?
3. What is the purpose of `main()` method?
4. What is the default value of `int` and `boolean` in Java?
5. Define keywords and identifiers with examples.

Common questions

Powered by AI

The implementation of the factorial function using loops illustrates the iterative process by multiplying a sequence of numbers incrementally from 1 up to the specified number. This ensures that each multiplication step depends on the result of the previous one, representing a step-by-step approach to problem-solving. The loop continues until it reaches the terminating condition, demonstrating iteration clearly where each step, i.e., 'fact *= i', builds upon the last .

The 'concat' method in Java is used to join two strings, essentially appending the second string to the first. In contrast, the 'replace' method creates a new string where all instances of a specified substring are replaced with a new specified substring. These methods differ in that 'concat' operates similarly to the '+' operator for strings, while 'replace' allows modification of existing substrings within the original string, which is useful for transformation tasks .

Arrays and strings in Java are distinct in that arrays can hold any data type, forming a collection of elements with a fixed size, while strings are sequences of characters with dynamic handling properties. However, both are indexes-based and support iterating over elements via loops. Strings are implemented as objects of the 'String' class, inherently immutable, and offer built-in methods, whereas arrays are primitive and lack out-of-the-box methods, requiring utility classes for complex manipulations .

Generating a Fibonacci series in Java demonstrates mathematical sequences by calculating each number as the sum of the two preceding ones, reflecting the real-world Fibonacci sequence. Iterative programming is showcased as the algorithm uses a loop to repeatedly apply this calculation, updating current and next numbers through assignments, effectively iterating until the desired count is reached. This demonstrates both mathematical and programming principles of recursion and loop-based iteration .

Distinguishing between 'checked' and 'unchecked' exceptions in Java is crucial due to their impact on runtime behavior and error management. Checked exceptions are required to be declared or handled in the method, ensuring that JVM can't bypass them, thus promoting error handling at compile-time. Unchecked exceptions don't have this restriction, often leading to runtime errors if not managed properly. This distinction ensures that developers must handle foreseeable issues at compile time, reducing runtime failures .

'Break' and 'continue' statements in Java affect loop control flow differently; 'break' immediately terminates the loop, exiting it entirely, thus stopping further iterations. Conversely, 'continue' skips the current iteration's remainder and moves to the next cycle, affecting only a single loop iteration. These differences are pivotal for controlling algorithm flow, enabling designers to precisely manage when loops repeat or terminate .

Exception handling in Java plays a crucial role in building robust programs by providing a mechanism to manage errors gracefully without abrupt termination. Through constructs like 'try', 'catch', 'finally', and 'throw', developers can detect problems and determine how to handle them, ensuring that the program can continue or fail gracefully, if necessary. This separation of error-handling logic allows for cleaner code and can prevent programs from crashing unexpectedly due to unhandled errors .

Constructing a palindrome checker program in Java demonstrates important concepts in string manipulation and conditional logic. The program reverses the original string and checks equality with the initial one using conditions. This showcases essential operations like character iteration, reverse construction using loops, and conditional checks, illustrating how strings can be manipulated effectively to solve complex conditional problems .

Correcting syntax errors in a 'while' loop is crucial to maintain logical consistency and avoid issues like infinite loops. For example, ensuring the correct comparison operators and proper update conditions of loop variables prevents conditions from being perpetually true. Incorrect initialization or missing update statements can lead to infinite loops, as the loop condition may never become false. Logical coherence must be maintained by double-checking that the loop's condition, body, and updates align with the intended algorithmic flow .

The conversion from a 'for' loop to a 'while' loop does not change the functionality but can affect readability depending on the programmer's familiarity with loop constructs. In converting a loop to calculate powers of a number from 'for' to 'while', the initialization, condition checking, and increment must be explicitly defined within the while loop, as demonstrated with 'int i = 1; while (i <= Y) { pow *= x; i++; }'. This explicit separation can sometimes clarify the loop's structure and flow, especially when complex initializations or increments are involved .

You might also like