0% found this document useful (0 votes)
12 views5 pages

Java Basic Programs for Beginners

The document contains multiple Java programs demonstrating various programming concepts including conditional statements, loops, array manipulation, and the use of the 'this' keyword. Each program serves a specific function, such as calculating the GCD of two numbers, copying elements from one array to another, and printing elements of an array. Additionally, it showcases object-oriented programming principles through class definitions and constructors.

Uploaded by

saradha.r
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)
12 views5 pages

Java Basic Programs for Beginners

The document contains multiple Java programs demonstrating various programming concepts including conditional statements, loops, array manipulation, and the use of the 'this' keyword. Each program serves a specific function, such as calculating the GCD of two numbers, copying elements from one array to another, and printing elements of an array. Additionally, it showcases object-oriented programming principles through class definitions and constructors.

Uploaded by

saradha.r
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

1.

public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. [Link]("x + y is less than 10");
7. } else {
8. [Link]("x + y is greater than 20");
9. }
10. }
11. }

1. public class Student {


2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
9. [Link]("city is agra");
10. }else {
11. [Link](city);
12. }
13. }
14. }

1. public class Student {


2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if([Link]("India")) {
6. if([Link]("Meerut")) {
7. [Link]("Your city is Meerut");
8. }else if([Link]("Noida")) {
9. [Link]("Your city is Noida");
10. }else {
11. [Link]([Link](",")[0]);
12. }
13. }else {
14. [Link]("You are not living in India");
15. }
16. }
17. }

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. [Link]("number is 0");
7. break;
8. case 1:
9. [Link]("number is 1");
10. break;
11. default:
12. [Link](num);
13. }
14. }
15. }

1. public class Calculation {


2. public static void main(String[] args) {
3. int i = 0;
4. [Link]("Printing the list of first 10 even numbers \n");
5. do {
6. [Link](i);
7. i = i + 2;
8. }while(i<=10);
9. }
10. }
GCD of Numbers
1. public class FindGCD
2. {
3. public static void main(String[] args)
4. {
5. //x and y are the numbers to find the GCF
6. int x = 12, y = 8, gcd = 1;
7. //running loop form 1 to the smallest of both numbers
8. for(int i = 1; i <= x && i <= y; i++)
9. {
10. //returns true if both conditions are satisfied
11. if(x%i==0 && y%i==0)
12. //storing the variable i in the variable gcd
13. gcd = i;
14. }
15. //prints the gcd
16. [Link]("GCD of %d and %d is: %d", x, y, gcd);
17. }
18. }

copy all elements of one array into another array


1. public class CopyArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr1 = new int [] {1, 2, 3, 4, 5};
5. //Create another array arr2 with size of arr1
6. int arr2[] = new int[[Link]];
7. //Copying all elements of one array into another
8. for (int i = 0; i < [Link]; i++) {
9. arr2[i] = arr1[i];
10. }
11. //Displaying elements of array arr1
12. [Link]("Elements of original array: ");
13. for (int i = 0; i < [Link]; i++) {
14. [Link](arr1[i] + " ");
15. }
16.
17. [Link]();
18.
19. //Displaying elements of array arr2
20. [Link]("Elements of new array: ");
21. for (int i = 0; i < [Link]; i++) {
22. [Link](arr2[i] + " ");
23. }
24. }
25. }

Program to print the elements of an array


1. public class PrintArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. [Link]("Elements of given array: ");
6. //Loop through the array by incrementing value of i
7. for (int i = 0; i < [Link]; i++) {
8. [Link](arr[i] + " ");
9. }
10. }
11. }

This keyword
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){[Link](rollno+" "+name+"
"+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. [Link]();
17. [Link]();
18. }}

Common questions

Powered by AI

To extract city information from an address string in the Java program, a combination of 'endsWith' and 'contains' methods is utilized. It checks if the address ends with "India" and then performs nested checks using 'contains' to determine if the address includes specific city names like "Meerut" or "Noida". If not found, it defaults to splitting the address string by "," and printing the first element, assumed to be the city. Importance lies in the systematic order: it first confirms the country before checking specific cities, ensuring relevant logic execution only when appropriate, thus preventing unnecessary operations or incorrect outputs for non-Indian addresses .

The Java program copies an array by first initializing the original array 'arr1', and then creating a new array 'arr2' with the same length. A loop iterates over 'arr1', and each element is copied to 'arr2' using 'arr2[i] = arr1[i]'. This method is straightforward and ensures each element is accurately transferred from the original to the new array. The primary advantage is its simplicity and clarity, making it immediately understandable for anyone reviewing the code. It effectively duplicates arrays with ease, though for very large arrays and increased efficiency, methods like 'System.arraycopy()' could be considered .

The Greatest Common Divisor (GCD) in the given Java program is calculated using an iterative approach. The program iterates from 1 to the smallest of the two numbers, 'x' and 'y', with a loop. For each iteration, it checks if the current loop variable 'i' is a divisor of both 'x' and 'y'. If both 'x % i == 0' and 'y % i == 0' are true, the current value of 'i' is stored as the GCD. This method effectively finds the highest number that divides both 'x' and 'y' exactly, which is printed as the GCD at the end of the loop using 'System.out.printf' .

In the provided Java program making use of the "Cloneable" interface, the switch mechanism is implemented to print different outputs based on the value of the integer 'num'. The switch statement evaluates 'num' and compares it with case 0 and case 1. If 'num' is 0, it prints "number is 0" and if 'num' is 1, it prints "number is 1". If 'num' does not match these cases, the default case is executed, printing the value of 'num'. In the given code, 'num' is initialized with a value of 2, so the default case is executed, printing "2". This demonstrates the switch mechanism's function in executing the block of code corresponding to the case that matches the operand .

In the "Student" class, the constructor directly assigns the parameter variables to the class-level fields with the same names without using the 'this' keyword, leading to members not being initialized correctly. For instance, 'rollno=rollno' results in the local variable shadowing the instance variable, leaving instance variables with default values. To resolve this, the 'this' keyword should be employed to differentiate the instance variables from the parameters. The corrected assignment would be 'this.rollno = rollno;' and similarly for 'name' and 'fee' at lines 6 to 8 .

The Java program uses a "do-while" loop to print the first 10 even numbers. It initializes an integer 'i' to 0 and repeatedly prints 'i' before incrementing it by 2 until 'i' exceeds 10. This method is effective because it ensures that the code block inside the loop is executed at least once, making it a suitable choice for scenarios where the loop body has to execute initially regardless of condition. Starting from 0 and incrementing by 2 each time, the loop ensures the continuous sequence of even numbers printed as '0 2 4 6 8 10' .

The Java program uses a "for" loop construct to print the elements of an array. It initializes a loop counter, 'i', at 0 and traverses the array until 'i' is less than the length of the array 'arr' by incrementing 'i' in each iteration. This loop ensures precision in accessing each array element as it uses 'arr[i]' to get the element in the current iteration. This is effective because the loop's increment condition aligns with array indexing, reducing off-by-one errors and ensuring each element is accessed exactly once without exceeding bounds .

The program implementing 'Cloneable' interface does not actually demonstrate cloning behavior typical in Java because it merely includes the interface without implementing the necessary method or logic associated with cloning. Typically, a class implementing 'Cloneable' should override the 'clone()' method and handle the 'CloneNotSupportedException' to create a field-for-field copy. In this case, these steps are absent, so no actual cloning process occurs. The presence of the interface alone, without associated method implementations, results in no impact on program execution, thus providing no example of object duplication as intended for 'Cloneable' .

Using '==' for string comparison in Java can lead to incorrect results because '==' compares object references, not string values. In the program examples provided, such comparisons are used in conditional statements like 'if(city == "Meerut")', which checks whether 'city' refers to the same object in memory as the literal "Meerut", likely leading to false returns even when contents match. To compare string values correctly in Java, 'equals()' or 'equalsIgnoreCase()' methods should be used, like 'if(city.equals("Meerut"))' .

The logical error in the if-else structure of the Java program calculating sums is that if the sum of 'x' and 'y' is not less than 10, it automatically assumes it must be greater than 20. The condition checked is 'if(x+y < 10)', and if false, it executes 'else{ System.out.println("x + y is greater than 20");}'. However, sums such as x=10 and y=12 result in x+y=22, which indeed outputs the correct message here, but for values, e.g., x=5, y=4, which sum to 9, the program would incorrectly proceed to print it's greater than 20. To correct this, a specific condition should be added to ensure correct evaluation, such as adding an else-if for 'else if(x+y >= 10 && x+y <= 20){ System.out.println("x + y is between 10 and 20");}' .

You might also like