Java Basics 62 Pages
Java Basics 62 Pages
INDEX
class Main
{
public static void main(String args[])
{
System.out.println(“Hello World!”); // String should be enclosed in double quotations.
}
}
Output: Hello World!
Sample’s:
System.out.println(1);
Output: 1
System.out.println(2+1);
Output: 3
System.out.println(2+”+3i”); //concat
Output:2+3i
System.out.println(‘A’); //Char should be enclosed in double quotations.
Output: A
Topic: User Inputs
In Java, the Scanner class is part of the java.util package and is used for taking input
from the user through various sources such as the keyboard. It provides methods to
parse and read primitive data types.
Program 2: Write a program to take the input from the user and print it?
Sample’s:
INTEGER → nextInt(): Reads the next integer input from the user.
STRING → next() or nextLine(): Reads the next word (using next()) or the entire line
(using nextLine()) of user input as a string.
DOUBLE → nextDouble(): Reads the next double-precision floating-point number
entered by the user.
FLOAT → nextFloat(): Reads the next single-precision floating-point number entered
by the user.
import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x=10;
String y="GMS";
char z='A';
Double a=9.9;
System.out.println(((Object)x).getClass().getSimpleName());
System.out.println(((Object)y).getClass().getSimpleName());
System.out.println(((Object)z).getClass().getSimpleName());
System.out.println(((Object)a).getClass().getSimpleName());
}
}
Output:
Integer
String
Character
Double
In the above Java program initializes variables of different data types (int, String,
char, and Double) and uses the getClass().getSimpleName() method to obtain and
print the simple class names of their corresponding wrapper classes. The output
displays the class names for each variable.
Topic: Conditional If
Program 4: Write a program to print “Eligible for Voting” if the number is greater
than 18?
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Int age=sc.nextInt();
If (age>18)
{
System.out.println(“Eligible for Voting”);
}
}
}
Input:20
Output: Eligible for Voting
Input: 17
Output: no output.
You can also use the else statement to provide an alternative code block to be
executed when the condition in the if statement is false.
Program 5: write a program that prints “Eligible for Voting” if the age is greater than
18, else print “Not Eligible for Voting”.
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Int age=sc.nextInt();
If (age>18)
{
System.out.println(“Eligible for Voting”);
}
else
{
System.out.println(“Not Eligible for Voting”);
}
}
}
Input: 22
Output: Eligible for Voting
Program 6: write a program that prints “Divisible by 5” if the number is divisible by 5
else print “Not Divisible by 5”.
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Int n=sc.nextInt();
If (n%5==0)
{
System.out.println(“Divisible by 5”);
}
else
{
System.out.println(“Not Divisible by 5”);
}
}
}
Input: 25
Output: Divisible by 5
Topic: Conditional else if
Additionally, you can chain multiple if and else if statements for more complex
decision-making.
Program 7: write a program that prints the grade based upon there marks out of 100.
Below table shows the grade values.
Marks Grade
100 to 85 marks A
84 to 75 marks B
74 to 65 marks C
64 to 50 marks D
import java.util.*;
public class Main {
Program 8: write a program to print the name of the maximum scorer between 3
people.
import java.util.*;
public class Main {
}
}
Input:
Enter the score of person A: 20
Enter the score of person B: 30
Enter the score of person S: 15
Output:
The maximum score name: B
Score:30
The switch statement in Java is a way to make decisions based on different possible
values of an expression. It's like having a menu with various options, and you choose
what to do based on the option you select.
Here's how it works:
You have an expression, which is like the thing you want to check (e.g., a variable).
You have different cases, each representing a possible value of the expression. It's like
saying, "If the expression is this, do something."
When the program runs, it checks the value of the expression and goes to the case
that matches. It then executes the code inside that case.
If there's no match, there's a default case (optional), which is like a backup plan. If
none of the cases match, the code inside the default case gets executed.
Program 9: Write a program to print the name of the month based on the month
number?
Month Number
January 1
February 2
March 3
April 4
May 5
June 6
July 7
August 8
September 9
October 10
November 11
December 12
import java.util.*;
public class Mani {
}
}
Input: 6
Output: June
Input: 11
Output: November
Program 10: Write a program that applies the operation between two variables and
print the values using switch cases.
import java.util.*;
public class Mani {
}
}
Input:
Enter 2 number:
10
20
Enter the below number to apply for the operation:
1 for the Addition
2 for Substraction
3 for the Multiplication
4 for Division
1
Output:
Addition of 2 number:30
Input:
Enter 2 number:
20
10
Enter the below number to apply for the operation:
1 for the Addition
2 for Substraction
3 for the Multiplication
4 for Division
4
Output:
Division of 2 numbers:2
Topic: For Loop
A for loop in programming is like a repetitive task that you want to automate. It's a
way to execute a block of code repeatedly for a specific number of times.
Program 11: Write a program to print the natural number up to the n value?
import java.util.*;
public class Mani {
Input:
Enter a number:
10
Output:
1
2
3
4
5
6
7
8
9
import java.util.*;
public class Mani {
Input:
Enter a number:
10
Output:
The factors of the number 10 is:
1
2
5
10
A while loop in programming is another way to repeat a block of code, but it keeps
running as long as a specified condition is true. Here's a simple breakdown:
Condition: You start with a condition that needs to be true for the loop to run. If the
condition is false from the beginning, the loop won't run at all.
Code Block: Inside the loop, you put the code that you want to be repeated.
Iteration: After each iteration (execution of the code block within the loop), the
program goes back to the condition. If the condition is still true, the loop runs again; if
it's false, the loop stops.
import java.util.*;
public class Mani {
Program 13: Write a program to print the square values of the numbers up to n?
import java.util.*;
public class Mani {
Input:
Enter a number:
10
Output:
The square values up to 10 is:
0
1
4
9
16
25
36
49
64
81
Program 14: Write a program to print the star pattern in the following image
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
for(int j=0;j<n;j++)
{
for(int i=0;i<j;i++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Input:
5
Output:
It reads an integer n from the user, indicating the number of rows for the pattern.
The outer loop (for(int j=0; j<n; j++)) iterates from 0 to n-1, controlling the number of
rows.
Inside the outer loop, there's another loop (for(int i=0; i<j; i++)) that iterates from 0 to
j-1. This loop is responsible for printing the stars in each row.
It prints a "* " (star followed by a space) in each iteration of the inner loop.
After printing stars for a particular row, it moves to the next line (System.out.println())
to start a new line for the next row.
Program 15: Write a program to print the star pattern as show in the below image?
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("* ".repeat(n-i));
}
}
}
Input:5
Output:
It uses the Scanner class to read an integer n representing the number of rows for the
pattern.
It enters a loop that iterates from 0 to n-1.
In each iteration, it prints a row of stars using the repeat method: "* ".repeat(n-i).
This prints stars with a space in between, and the number of stars decreases in each
row as i increases.
The result is an inverted right-angled triangle pattern, where the first row has the
maximum number of stars (n), and the number of stars decreases by 1 in each
subsequent row.
Program 16: Write a program to print the star pattern in the following image?
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
for(int j=0;j<n;j++)
{
for(int i=0;i<n;i++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Input: 5
Output:
This Java program takes an integer n as input and prints a square pattern of stars
with n rows and n columns. The outer loop controls the number of rows, and the inner
loop prints n stars in each row, separated by a space. After printing stars for a row, it
moves to the next line to start a new row. The result is a square of stars with each row
having n stars.
Program 17: Write a program to print the star pattern as below given image?
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int x=n;
for(int i=0;i<n;i++)
{
System.out.println(" ".repeat(x)+"* ".repeat(i));
x--;
}
}
}
Input: 5
Output:
The program uses the Scanner class to read an integer n from the user, indicating the
number of rows for the pattern.
It initializes a variable x with the value of n.
The program then enters a loop that iterates n times, representing each row of the
pattern.
In each iteration, it prints a combination of spaces and stars using the repeat method:
" ".repeat(x) prints spaces based on the value of x (initially set to n) to create an
indentation.
"* ".repeat(i) prints stars with a space in between, creating the star pattern for the
current row.
After printing a row, it decrements the value of x to adjust the indentation for the next
row.
Program 18: Write a program to print the star pattern as below in the image?
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int x=n;
for(int i=0;i<n;i++)
{
if(i==0 || i==n-1)
{
System.out.println("* ".repeat(n));
}
else
{
System.out.println("* "+" ".repeat(n)+" *");
}
}
}
}
Input: 5
Ouput:
It uses the Scanner class to read an integer n representing the number of rows for the
pattern.
It initializes a variable x with the value of n.
The program enters a loop that iterates n times, representing each row of the pattern.
Inside the loop, it checks if the current row is the first or last (i==0 or i==n-1). If true, it
prints a row of stars ("* ".repeat(n)).
If the current row is not the first or last, it prints a row with a star at the beginning,
spaces in the middle (" ".repeat(n)), and a star at the end ("* ").
Program 19: Write a program to print the star pattern as shown in the below image?
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int x=n;
for(int i=0;i<n;i++)
{
System.out.println(" ".repeat(x)+"* ".repeat(i));
x--;
}
for(int j=n;j>0;j--)
{
System.out.println(" ".repeat(n-j)+"* ".repeat(j));
}
}
}
It uses the Scanner class to read an integer n representing the number of rows for the
pattern.
The first loop iterates from 0 to n-1 and prints a triangle pattern with spaces and
stars, decreasing the indentation (" ".repeat(x)) for each row.
After the first loop, it enters a second loop that iterates from n to 1. This loop prints
an inverted triangle pattern with spaces and stars, increasing the indentation ("
".repeat(n-j)) for each row.
Input: 5
Output:
Input: 5
Output:
It uses the Scanner class to read an integer n representing the number of rows for the
pattern.
It initializes a variable x with the value of n.
The first loop iterates from n to 1 and prints an triangle pattern with spaces and stars,
increasing the indentation (" ".repeat(n-j)) for each row.
After the first loop, it prints a vertical bar ("| ") at the center of the diamond.
The second loop iterates from 0 to n and prints a triangle pattern with spaces and
stars, decreasing the indentation (" ".repeat(x)) for each row.
Topic: Arrays
In Java, an array is a data structure that allows you to store multiple values of the
same type under a single name. Each element in the array is identified by an index,
and you can access elements using this index.
To declare an array, you specify the type of its elements, followed by square brackets
[] and the array name.
Program 21: Write a program to read the values from the user to assign the values
for the array elements.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int n=sc.nextInt();
int a[]= new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Elements of Array:");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
Input:
Enter the size of the array: 5
12345
Output:
Elements of Array:
1
2
3
4
5
It uses the Scanner class to take input from the user.
The user is prompted to enter the size of the array.
An array a of size n is declared and initialized based on the user's input.
The program then uses a loop to get integer values from the user and stores them in
the array.
Finally, it prints the elements of the array using another loop.
Program 22: Write to find the maximum element in the array?
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int n=sc.nextInt();
int a[]= new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int max=Integer.MIN_VALUE; // it assigns the minimum integer value to
the max variable.
for(int i=0;i<n;i++)
{
if(max<a[i])
{
max=a[i];
}
}
System.out.println("Maximum elemnet in the array is:"+max);
}
}
Program 23: Write a program to find the element k in the array. (using Linear search)
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int n=sc.nextInt();
int a[]= new int[n];
System.out.println("Enter the elements:");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Enter the Search key:");
int k=sc.nextInt();
boolean flag=false;
for(int i=0;i<n;i++)
{
if(k==a[i])
{
flag=true;
break;
}
}
if(flag){
System.out.println("Element found");
}
else{
System.out.println("Element not found!");
}
}
}
Input:
Enter the size of the array:
5
Enter the elements:
12345
Enter the Search key:
2
Output:
Element found
Array Input:
The user is asked to input the size of the array.
Based on the size, an integer array is initialized, and the user is prompted to input the
elements of the array.
Search Key Input:
The user is prompted to enter a search key, which is the value the program will look
for in the array.
Linear Search:
The program performs a linear search through the array elements to find the search
key.
It uses a boolean flag to indicate whether the search key is found during the iteration.
If the search key is found, the flag is set to true, and the loop breaks.
Output:
The program prints whether the search key was found in the array or not based on
the value of the flag.
If the flag is true, it prints "Element found"; otherwise, it prints "Element not found!".
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int n=sc.nextInt();
int a[]= new int[n];
System.out.println("Enter the elements:");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int temp;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("Sorted array:");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
Input:
Enter the size of the array:
5
Enter the elements:
9 4 2 10 1
Output:
Sorted array:
1
2
4
9
10
Input:
The program takes the size of the array (n) as input from the user.
The user is then prompted to enter the elements of the array.
Bubble Sort:
The program uses a sorting algorithm called Bubble Sort to arrange the elements of
the array in ascending order.
It involves comparing adjacent elements in the array and swapping them if they are in
the wrong order.
The process is repeated for each element in the array until the entire array is sorted.
Sorting Process:
The outer loop iterates over each element in the array.
The inner loop compares the current element with the next one (i with j), and if the
current element is greater than the next one, they are swapped.
This process is repeated for each pair of adjacent elements in the array.
Sorted Array Output:
After the sorting process is complete, the program prints the sorted array.
Program 25: Write a program to count the elements that are divisible by 5 In the
array?
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int n=sc.nextInt();
int a[]= new int[n];
System.out.println("Enter the elements:");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int count=0;
for(int i=0;i<n;i++)
{
if(a[i]%5==0)
{
count++;
}
}
System.out.println("No of elements in the array that divisible by 5
is:"+count);
}
}
Input:
Enter the size of the array:
5
Enter the elements:
10 12 30 45 11
Output:
No of elements in the array that divisible by 5 is:3
Input:
The user is prompted to enter the size of an array (n).
The program then asks the user to input the elements of the array.
Counting Elements Divisible by 5:
The program uses a loop to iterate through each element of the array.
For each element, it checks if the element is divisible by 5.
If the condition is met, a counter (count) is incremented.
Output:
After scanning the entire array, the program prints the total count of elements that
are divisible by 5.
Topic: Functions
A function is a block of code that performs a specific task or set of tasks. It is designed
to be reusable, allowing you to call it from different parts of your program. Functions
help in organizing code, making it more modular and easier to understand. In many
programming languages, functions can have parameters (input values) and can
return a value.
When a method is declared with the void keyword, it means that the method does not
return any value. In other words, it performs a certain action but does not produce a
result that needs to be used elsewhere in the program.
Ex:
public static void percentage(int sum) //we used void
{
float per=(float)((sum*100/300));
System.out.println("Percentage :"+per); //we can directly use print statement
because of void.
}
The return statement is used in functions to send a value back to the caller. When a
function is called, it may perform some operations and then use the return statement
to provide a result. The calling code can capture this result and use it as needed.
Ex:
public static int Add(int a,int b) //here we used int so we need to return the value.
{
return a+b; //return statement.
}
Program 26: Abhiram asked Koushik to do some calculations, but Koushik do not have
the calculator. Your task is to create some functions to perform the operations like
Addition, Subtraction, Multiplication and Division to help Koushik and Abhiram.
import java.util.*;
public class Main
{
public static int Add(int a,int b) //here we used int so we need to return the value.
{
return a+b; //return statement.
}
public static int Sub(int a,int b)
{
return a-b;
}
public static int Mul(int a,int b)
{
return a*b;
}
public static int Div(int a,int b)
{
return a/b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Two number to perform the Operation:");
int a=sc.nextInt();
int b=sc.nextInt();
System.out.println("Enter the requried number to perform the
operation:");
System.out.println("1 for the Addition \n 2 for the Subtraction \n 3 for
the Multiplication \n 4 for the Division");
int x=sc.nextInt();
int res;
switch(x)
{
case 1:
res=Main.Add(a,b);
System.out.println(res);
break;
case 2:
res=Main.Sub(a,b);
System.out.println(res);
break;
case 3:
res=Main.Mul(a,b);
System.out.println(res);
break;
case 4:
res=Main.Div(a,b);
System.out.println(res);
break;
default:
System.out.println("Select the correct Number for the operation!");
break;
}
}
}
Input:
Enter the Two number to perform the Operation:
10
20
Enter the required number to perform the operation:
1 for the Addition
2 for the Subtraction
3 for the Multiplication
4 for the Division
1
Output:
30
This Java program is a basic calculator that performs four operations: addition,
subtraction, multiplication, and division. It takes two numbers as input and asks the
user to select the operation they want to perform using a menu. The program then
uses a switch statement to execute the chosen operation and displays the result. If an
invalid option is selected, it prompts the user to choose a correct operation. The
calculator functions (Add, Sub, Mul, Div) are defined as static methods within the
Main class. The program utilizes the Scanner class to take input from the user.
Program 27: Navy school had released the 3 subjects marks list of class 9th. Abhiram
is belongs to class 9th and he want to know the total marks and his percentage. Your
task is to create 2 functions that calculate the total marks and percentage of
Abhiram’s. let the names of the two methods are totalmarks and percentage. Call the
percentage method from the totalmarks method.
import java.util.*;
public class Main
{
public static void percentage(int sum) //we used void
{
float per=(float)((sum*100/300));
System.out.println("Percentage :"+per); //we can directly use print statement
because of void.
}
public static void totalmarks(int a,int b,int c)
{
int sum=a+b+c;
System.out.println("Total marks are:"+sum);
Main.percentage(sum); //calling percentage method from totalmarks.
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the three subjects marks:");
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
Main.totalmarks(a,b,c);
}
}
Input:
Enter the three subjects marks:
89
76
98
Output:
Total marks are:263
Percentage :87.0
This Java program calculates the total marks and percentage of a student in three
subjects. It consists of three main methods:s
totalmarks(int a, int b, int c):
Takes three subject marks as parameters.
Calculates the total marks by adding the marks of the three subjects.
Calls the percentage method, passing the total marks as an argument.
Prints the total marks.
percentage(int sum):
Takes the total marks as a parameter.
Calculates the percentage by dividing the total marks by 300 and multiplying by 100.
Prints the calculated percentage.
main(String[] args):
Takes input for the marks of three subjects from the user.
Calls the totalmarks method with the entered marks.
Program 28: Raji needs a versatile addition calculator that can add two values,
regardless of whether they are integers, floats, or strings. Your task is to construct a
Java code that utilizes the concept of method overloading to achieve this. The code
should be able to handle different types of inputs and return the result.
import java.util.*;
class Main
{
public static int add(int a,int b)
{
return a+b;
}
public static float add(float x,float y)
{
return x+y;
}
public static String add(String p,String q)
{
return p+q;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
}
}
Input:
Enter the option for selecting below operation:
Enter 1 for the Integer Addition:
Enter 2 for the float Addition:
Enter 3 for the String Addition(Cancat):
3
Enter 2 Strings:
aa
bb
Output:
Addition of two strings:aabb
Method Definitions:
The code defines a class named Main.
Inside the class, there are three overloaded add methods:
public static int add(int a, int b) for integer addition.
public static float add(float x, float y) for float addition.
public static String add(String p, String q) for string concatenation.
Main Method:
The main method is the entry point of the program.
It starts by creating a Scanner object (sc) to take user input.
The user is prompted to enter an option for selecting the type of operation (integer
addition, float addition, or string concatenation).
Switch Statement:
The program uses a switch statement based on the user's input (n).
Depending on the selected option, the program executes the corresponding case.
User Input and Method Invocation:
If the user chooses option 1, they are prompted to enter two integers (a and b), and
the add(int a, int b) method is invoked with these values. The result is then printed.
If the user chooses option 2, they are prompted to enter two floats (x and y), and the
add(float x, float y) method is invoked with these values. The result is then printed.
If the user chooses option 3, they are prompted to enter two strings (p and q), and the
add(String p, String q) method is invoked with these values. The result is then printed.
Default Case:
If the user enters an option other than 1, 2, or 3, the program prints a message asking
the user to enter the correct option.
Topic: Class Object
Parameterized Constructor:
A constructor with parameters that allows you to initialize the object with specific
values.
Example:
public class MyClass {
// Parameterized constructor
public MyClass(int value1, String value2) {
// Initialization code using parameters
}
}
Object Creation:
The new keyword is used to create objects by calling the class's constructor.
Each object has its own set of data, independent of other instances.
Program 29:
Create a Java class named Student with the following attributes:
id (integer)
name (String)
grade (char)
Implement a parameterized constructor in the Student class that initializes these
attributes. Additionally, include a method named displayDetails that prints the details
of the student.
import java.util.*;
public class Main
{
private int id;
private String name;
private char grade;
public Main(int id,String name,char grade) // Parameterized Constructor
{
this.id=id;
this.name=name;
this.grade=grade;
}
public void display()
{
System.out.println("Student id:"+id);
System.out.println("Student name:"+name);
System.out.println("Student grade:"+grade);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter details:");
Main obj = new Main(sc.nextInt(),sc.next(),sc.next().charAt(0));
obj.display();
}
}
Input:
Enter details:
31545
Manisai
O
Output:
Student id:31545
Student name:Manisai
Student grade:O
The Main class has three private attributes: id (integer), name (String), and grade
(char).
There is a parameterized constructor public Main(int id, String name, char grade) that
initializes the attributes with the values passed as parameters.
The display method is used to print the details of the student object.
In the main method:
An instance of the Scanner class is created to read input from the user.
The user is prompted to enter details.
The details are read using sc.nextInt(), sc.next(), and sc.next().charAt(0), and a Main
object (obj) is created with these details.
The display method is called on the obj to print the student details.
Program: Write a Java program that defines a class called Main with two
constructors. The class should have two private instance variables: id, an integer, and
name, a string. The first constructor should initialize id to 0 and name to "No name",
while the second constructor should take two parameters to initialize id and name
based on user input. In the main method, prompt the user to decide if they want to
provide input. If the user chooses to provide input, prompt them for an ID and a
name, and create an object of the Main class using the parameterized constructor. If
the user chooses not to provide input, create an object using the default constructor.
Finally, print the values of the id and name instance variables.
import java.util.Scanner;
// Default constructor
public Main() {
this.id = 0;
this.name = "No name";
}
// Parameterized constructor
public Main(int id, String name) {
this.id = id;
this.name = name;
}
Main obj;
if (inputChoice.equals("yes")) {
System.out.println("Enter an Id:");
int id = sc.nextInt();
System.out.println("Enter a Name:");
sc.nextLine(); // Consume newline
String name = sc.nextLine();
obj = new Main(id, name);
} else {
obj = new Main();
}
sc.close();
// Display values
System.out.println("ID: " + obj.id);
System.out.println("Name: " + obj.name);
}
}
Input:
Do you want to provide input? (yes/no)
No
Output:
ID: 0
Name: No name
Input:
Do you want to provide input? (yes/no)
yes
Enter an Id:
12
Enter a Name:
Bala Krishna
Output:
ID: 12
Name: Bala Krishna
Class Definition:
The Main class is defined with two private instance variables: id (an integer) and
name (a string).
Default Constructor:
There's a default constructor (Main()) that initializes id to 0 and name to "No name".
Parameterized Constructor:
Another constructor (Main(int id, String name)) is provided, which initializes id and
name based on the values provided as parameters.
Main Method:
The main method is the entry point of the program.
User Input Handling:
The program prompts the user to decide whether they want to provide input or not.
If the user chooses to provide input ("yes"), the program asks for an ID and a name,
and then uses these values to create an object of the Main class using the
parameterized constructor.
sc.nextLine().trim().toLowerCase().equals("yes"):
sc.nextLine(): This part of the expression reads a line of input from the Scanner object
sc. It waits for the user to input a line of text and then returns that input as a String.
trim(): The trim() method removes any leading or trailing whitespace from the String
returned by nextLine(). This is helpful to ensure that the input is clean and does not
contain any unnecessary spaces.
toLowerCase(): The toLowerCase() method converts all characters in the String to
lowercase. This is useful for case-insensitive comparison, ensuring that the user's
input can be compared accurately regardless of whether they type "yes", "YES", "Yes",
or "YeS".
equals("yes"): This method compares the resulting String with the string "yes". It
returns true if the two strings are equal, meaning that the user input matches "yes"
(ignoring case), and false otherwise.
If the user chooses not to provide input, the default constructor is used to create an
object of the Main class with default values.
Displaying Values:
After creating the object, the program prints the values of the id and name instance
variables of the object.
Resource Management:
The Scanner object used for user input (sc) is closed to release system resources after
input processing is complete.