Question
stringlengths
1
113
Answer
stringlengths
22
6.98k
What is Java Enum in Switch Statement?
Java allows us to use enum in switch statement. Java enum is a class that represent the group of constants. (immutable such as final variables). We use the keyword enum and put the constants in curly braces separated by comma. Example: JavaSwitchEnumExample.java //Java Program to demonstrate the use of Enum //in switch statement public class JavaSwitchEnumExample { public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat } public static void main(String args[]) { Day[] DayNow = Day.values(); for (Day Now : DayNow) { switch (Now) { case Sun: System.out.println("Sunday"); break; case Mon: System.out.println("Monday"); break; case Tue: System.out.println("Tuesday"); break; case Wed: System.out.println("Wednesday"); break; case Thu: System.out.println("Thursday"); break; case Fri: System.out.println("Friday"); break; case Sat: System.out.println("Saturday"); break; } } } } Output: Sunday Monday Twesday Wednesday Thursday Friday Saturday
What is Java Wrapper in Switch Statement?
Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement. Example: WrapperInSwitchCaseExample.java //Java Program to demonstrate the use of Wrapper class //in switch statement public class WrapperInSwitchCaseExample { public static void main(String args[]) { Integer age = 18; switch (age) { case (16): System.out.println("You are under 18."); break; case (18): System.out.println("You are eligible for vote."); break; case (65): System.out.println("You are senior citizen."); break; default: System.out.println("Please give the valid age."); break; } } } Output: You are eligible for vote.
What is Loops in Java?
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop. There are three types of for loops in Java. -Simple for Loop -For-each or Enhanced for Loop -Labeled for Loop
Can you provide an example of Java Simple for Loop?
A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts: Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition. Increment/Decrement: It increments or decrements the variable value. It is an optional condition. Statement: The statement of the loop is executed each time until the second condition is false. Syntax: for(initialization; condition; increment/decrement){ //statement or code to be executed } Example: ForExample.java //Java Program to demonstrate the example of for loop //which prints table of 1 public class ForExample { public static void main(String[] args) { //Code of Java for loop for(int i=1;i<=10;i++){ System.out.println(i); } } } Output: 1 2 3 4 5 6 7 8 9 10
What is Java Nested for Loop?
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes. Example: NestedForExample.java public class NestedForExample { public static void main(String[] args) { //loop of i for(int i=1;i<=3;i++){ //loop of j for(int j=1;j<=3;j++){ System.out.println(i+" "+j); }//end of i }//end of j } } Output: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Pyramid Example 1: PyramidExample.java public class PyramidExample { public static void main(String[] args) { for(int i=1;i<=5;i++){ for(int j=1;j<=i;j++){ System.out.print("* "); } System.out.println();//new line } } } Output: * * * * * * * * * * * * * * * Pyramid Example 2: PyramidExample2.java public class PyramidExample2 { public static void main(String[] args) { int term=6; for(int i=1;i<=term;i++){ for(int j=term;j>=i;j--){ System.out.print("* "); } System.out.println();//new line } } } Output: * * * * * * * * * * * * * * * * * * * * *
What is Java for-each Loop?
The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. It works on the basis of elements and not the index. It returns element one by one in the defined variable. Syntax: for(data_type variable : array_name){ //code to be executed } Example: ForEachExample.java //Java For-each loop example which prints the //elements of the array public class ForEachExample { public static void main(String[] args) { //Declaring an array int arr[]={12,23,44,56,78}; //Printing array using for-each loop for(int i:arr){ System.out.println(i); } } } Output: 12 23 44 56 78
What is Java Labeled For Loop?
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop. Syntax: labelname: for(initialization; condition; increment/decrement){ //code to be executed } Example: LabeledForExample.java //A Java program to demonstrate the use of labeled for loop public class LabeledForExample { public static void main(String[] args) { //Using Label for outer and for loop aa: for(int i=1;i<=3;i++){ bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break aa; } System.out.println(i+" "+j); } } } } Output: 1 1 1 2 1 3 2 1 If you use break bb;, it will break inner loop only which is the default behaviour of any loop. LabeledForExample2.java public class LabeledForExample2 { public static void main(String[] args) { aa: for(int i=1;i<=3;i++){ bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break bb; } System.out.println(i+" "+j); } } } } Output: 1 1 1 2 1 3 2 1 3 1 3 2 3 3
What is Java Infinitive for Loop?
If you use two semicolons ;; in the for loop, it will be infinitive for loop. Syntax: for(;;){ //code to be executed } Example: ForExample.java //Java program to demonstrate the use of infinite for loop //which prints an statement public class ForExample { public static void main(String[] args) { //Using no condition in for loop for(;;){ System.out.println("infinitive loop"); } } } Output: infinitive loop infinitive loop infinitive loop infinitive loop infinitive loop ctrl+c
Can you explain the differences between the Java for loop, while loop, and do-while loop?
Java for Loop vs while Loop vs do-while Loop For loop Introduction : The Java for loop is a control flow statement that iterates a part of the programs multiple times. When to use : If the number of iteration is fixed, it is recommended to use for loop. Syntax: for(init;condition;incr/decr){ // code to be executed } Example : //for loop for(int i=1;i<=10;i++){ System.out.println(i); } Syntax for infinitive loop : for(;;){ //code to be executed } while loop Introduction : The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition. When to use : If the number of iteration is not fixed, it is recommended to use while loop. Syntax: while(condition){ //code to be executed } Example : //while loop int i=1; while(i<=10){ System.out.println(i); i++; } Syntax for infinitive loop : while(true){ //code to be executed } do-while loop Introduction : The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition. When to use : If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop. Syntax: do{ //code to be executed }while(condition); Example : //do-while loop int i=1; do{ System.out.println(i); i++; }while(i<=10); Syntax for infinitive loop : do{ //code to be executed }while(true);
What is Java While Loop?
The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean condition is true. As soon as the Boolean condition becomes false, the loop automatically stops. The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is recommended to use the while loop. Syntax: while (condition){ //code to be executed I ncrement / decrement statement } The different parts of do-while loop: 1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. When the condition becomes false, we exit the while loop. Example: i <=100 2. Update expression: Every time the loop body is executed, this expression increments or decrements loop variable. Example: i++;
What is Java Infinitive While Loop?
If you pass true in the while loop, it will be infinitive while loop. Syntax: while(true){ //code to be executed } Example: WhileExample2.java public class WhileExample2 { public static void main(String[] args) { // setting the infinite while loop by passing true to the condition while(true){ System.out.println("infinitive while loop"); } } } Output: infinitive while loop infinitive while loop infinitive while loop infinitive while loop infinitive while loop ctrl+c
What is Java do-while loop?
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use a do-while loop. Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while check the condition at the end of loop body. The Java do-while loop is executed at least once because condition is checked after loop body. Syntax: do{ //code to be executed / loop body //update statement }while (condition); The different parts of do-while loop: 1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. As soon as the condition becomes false, loop breaks automatically. Example: i <=100 2. Update expression: Every time the loop body is executed, the this expression increments or decrements loop variable. Example: i++;
What is Java Infinitive do-while Loop?
If you pass true in the do-while loop, it will be infinitive do-while loop. Syntax: do{ //code to be executed }while(true); Example: DoWhileExample2.java public class DoWhileExample2 { public static void main(String[] args) { do{ System.out.println("infinitive do while loop"); }while(true); } } Output: infinitive do while loop infinitive do while loop infinitive do while loop ctrl+c
What is Java Break Statement?
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. We can use Java break statement in all types of loops such as for loop, while loop and do-while loop. Syntax: jump-statement; break;
Can you provide an example of Java Break Statement with Loop?
Example: BreakExample.java //Java Program to demonstrate the use of break statement //inside the for loop. public class BreakExample { public static void main(String[] args) { //using for loop for(int i=1;i<=10;i++){ if(i==5){ //breaking the loop break; } System.out.println(i); } } } Output: 1 2 3 4
What is Java Break Statement with Inner Loop?
It breaks inner loop only if you use break statement inside the inner loop. Example: BreakExample2.java //Java Program to illustrate the use of break statement //inside an inner loop public class BreakExample2 { public static void main(String[] args) { //outer loop for(int i=1;i<=3;i++){ //inner loop for(int j=1;j<=3;j++){ if(i==2&&j==2){ //using break statement inside the inner loop break; } System.out.println(i+" "+j); } } } } Output: 1 1 1 2 1 3 2 1 3 1 3 2 3 3
Can you provide an example of Java Break Statement with Labeled For Loop?
We can use break statement with a label. The feature is introduced since JDK 1.5. So, we can break any loop in Java now whether it is outer or inner loop. Example: BreakExample3.java //Java Program to illustrate the use of continue statement //with label inside an inner loop to break outer loop public class BreakExample3 { public static void main(String[] args) { aa: for(int i=1;i<=3;i++){ bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ //using break statement with label break aa; } System.out.println(i+" "+j); } } } } Output: 1 1 1 2 1 3 2 1
Can you provide an example of Java Break Statement in while loop?
BreakWhileExample.java //Java Program to demonstrate the use of break statement //inside the while loop. public class BreakWhileExample { public static void main(String[] args) { //while loop int i=1; while(i<=10){ if(i==5){ //using break statement i++; break;//it will break the loop } System.out.println(i); i++; } } } Output: 1 2 3 4
Can you provide an example of Java Break Statement in do-while loop?
BreakDoWhileExample.java //Java Program to demonstrate the use of break statement //inside the Java do-while loop. public class BreakDoWhileExample { public static void main(String[] args) { //declaring variable int i=1; //do-while loop do{ if(i==5){ //using break statement i++; break;//it will break the loop } System.out.println(i); i++; }while(i<=10); } } Output: 1 2 3 4
What is Java Continue Statement?
The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately. It can be used with for loop or while loop. The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop only. We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop. Syntax: jump-statement; continue;
Can you provide an example of Java Continue Statement Example?
ContinueExample.java //Java Program to demonstrate the use of continue statement //inside the for loop. public class ContinueExample { public static void main(String[] args) { //for loop for(int i=1;i<=10;i++){ if(i==5){ //using continue statement continue;//it will skip the rest statement } System.out.println(i); } } } Output: 1 2 3 4 6 7 8 9 10
Can you provide an example of Java Continue Statement with Inner Loop?
It continues inner loop only if you use the continue statement inside the inner loop. ContinueExample2.java //Java Program to illustrate the use of continue statement //inside an inner loop public class ContinueExample2 { public static void main(String[] args) { //outer loop for(int i=1;i<=3;i++){ //inner loop for(int j=1;j<=3;j++){ if(i==2&&j==2){ //using continue statement inside inner loop continue; } System.out.println(i+" "+j); } } } } Output: 1 1 1 2 1 3 2 1 2 3 3 1 3 2 3 3
Can you provide an example of Java Continue Statement with Labelled For Loop?
We can use continue statement with a label. This feature is introduced since JDK 1.5. So, we can continue any loop in Java now whether it is outer loop or inner. Example: ContinueExample3.java //Java Program to illustrate the use of continue statement //with label inside an inner loop to continue outer loop public class ContinueExample3 { public static void main(String[] args) { aa: for(int i=1;i<=3;i++){ bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ //using continue statement with label continue aa; } System.out.println(i+" "+j); } } } } Output: 1 1 1 2 1 3 2 1 3 1 3 2 3 3
Can you provide an example of Java Continue Statement in while loop?
ContinueWhileExample.java //Java Program to demonstrate the use of continue statement //inside the while loop. public class ContinueWhileExample { public static void main(String[] args) { //while loop int i=1; while(i<=10){ if(i==5){ //using continue statement i++; continue;//it will skip the rest statement } System.out.println(i); i++; } } } Output: 1 2 3 4 6 7 8 9 10
Can you provide an example of Java Continue Statement in do-while Loop?
ContinueDoWhileExample.java //Java Program to demonstrate the use of continue statement //inside the Java do-while loop. public class ContinueDoWhileExample { public static void main(String[] args) { //declaring variable int i=1; //do-while loop do{ if(i==5){ //using continue statement i++; continue;//it will skip the rest statement } System.out.println(i); i++; }while(i<=10); } } Output: 1 2 3 4 6 7 8 9 10
What is Java Comments?
The Java comments are the statements in a program that are not executed by the compiler and interpreter.
Why do we use comments in a code?
-Comments are used to make the program more readable by adding the details of the code. -It makes easy to maintain the code and to find the errors easily. -The comments can be used to provide information or explanation about the variable, method, class, or any statement. -It can also be used to prevent the execution of program code while testing the alternative code.
What are the Types of Java Comments?
There are three types of comments in Java. 1) Single Line Comment 2 ) Multi Line Comment 3) Documentation Comment
What is Java Single Line Comment?
The single-line comment is used to comment only one line of the code. It is the widely used and easiest way of commenting the statements. Single line comments starts with two forward slashes (//). Any text in front of // is not executed by Java. Syntax: //This is single line comment Let's use single line comment in a Java program. CommentExample1.java public class CommentExample1 { public static void main(String[] args) { int i=10; // i is a variable with value 10 System.out.println(i); //printing the variable i } } Output: 10
What is Java Multi Line Comment?
The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line comments there). Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java. Syntax: /* This is multi line comment */ Let's use multi-line comment in a Java program. CommentExample2.java public class CommentExample2 { public static void main(String[] args) { /* Let's declare and print variable in java. */ int i=10; System.out.println(i); /* float j = 5.9; float k = 4.4; System.out.println( j + k ); */ } } Output: 10
What is Java Documentation Comment?
Documentation comments are usually used to write large programs for a project or software application as it helps to create documentation API. These APIs are needed for reference, i.e., which classes, methods, arguments, etc., are used in the code. To create documentation API, we need to use the javadoc tool. The documentation comments are placed between /** and */. Syntax: /** * *We can use various tags to depict the parameter *or heading or author name *We can also use HTML tags * */
What is javadoc tags?
javadoc tags Some of the commonly used tags in documentation comments: Tag: {@docRoot} Syntax: {@docRoot} Description: to depict relative path to root directory of generated document from any page. Tag: @author Syntax: @author name - text Description: To add the author of the class Tag: @code Syntax: {@code text} Description: To show the text in code font without interpreting it as html markup or nested javadoc tag. Tag: @version Syntax: @version version-text Description: To specify "Version" subheading and version-text when -version option is used. Tag: @since Syntax: @since release Description: To add "Since" heading with since text to generated documentation. Tag: @param Syntax: @param parameter-name description Description: To add a parameter with given name and description to 'Parameters' section. Tag: @return Syntax: @return description Description: Required for every method that returns something (except void) Let's use the Javadoc tag in a Java program. Calculate.java import java.io.*; /** * <h2> Calculation of numbers </h2> * This program implements an application * to perform operation such as addition of numbers * and print the result * <p> * <b>Note:</b> Comments make the code readable and * easy to understand. * * @author Anurati * @version 16.0 * @since 2021-07-06 */ public class Calculate{ /** * This method calculates the summation of two integers. * @param input1 This is the first parameter to sum() method * @param input2 This is the second parameter to the sum() method. * @return int This returns the addition of input1 and input2 */ public int sum(int input1, int input2){ return input1 + input2; } /** * This is the main method uses of sum() method. * @param args Unused * @see IOException */ public static void main(String[] args) { Calculate obj = new Calculate(); int result = obj.sum(40, 20); System.out.println("Addition of numbers: " + result); } } Compile it by javac tool: Create Document Create documentation API by javadoc tool Now, the HTML files are created for the Calculate class in the current directory, i.e., abcDemo. Open the HTML files, and we can see the explanation of Calculate class provided through the documentation comment.
Are Java comments executable?
As we know, Java comments are not executed by the compiler or interpreter, however, before the lexical transformation of code in compiler, contents of the code are encoded into ASCII in order to make the processing easy. Test.java public class Test{ public static void main(String[] args) { //the below comment will be executed // \u000d System.out.println("Java comment is executed!!"); } } The above code generate the output because the compiler parses the Unicode character \u000d as a new line before the lexical transformation, and thus the code is transformed as shown below: Test.java public class Test{ public static void main(String[] args) { //the below comment will be executed // System.out.println("Java comment is executed!!"); } } Thus, the Unicode character shifts the print statement to next line and it is executed as a normal Java code.
Can you provide a list of Java Programs | Java Programming Examples?
Java programs are frequently asked in the interview. These programs can be asked from control statements, array, string, oops etc. Java basic programs like fibonacci series, prime numbers, factorial numbers and palindrome numbers are frequently asked in the interviews and exams. All these programs are given with the maximum examples and output. If you are new to Java programming, we will recommend you to read our Java tutorial first. Let's see the list of Java programs. -Java Basic Programs -Java Number Programs -Java Array Programs -Java Matrix Programs -Java String Programs -Java Searching and Sorting Programs -Java Conversion Programs -Pattern programs -Singly Linked List Programs -Circular Linked List Programs -Doubly Linked List Programs -Tree Programs
Can you provide a list of Java Basic Programs?
1) Fibonacci Series in Java 2) Prime Number Program in Java 3) Palindrome Program in Java 4) Factorial Program in Java 5) Armstrong Number in Java 6) How to Generate Random Number in Java 7) How to Print Pattern in Java 8) How to Compare Two Objects in Java 9) How to Create Object in Java 10) How to Print ASCII Value in Java
Can you provide a list of Java Number Programs?
1) How to Reverse a Number in Java 2) Java Program to convert Number to Word 3) Automorphic Number Program in Java 4) Peterson Number in Java 5) Sunny Number in Java 6) Tech Number in Java 7) Fascinating Number in Java 8) Keith Number in Java 9) Neon Number in Java 10) Spy Number in Java 11) ATM program Java 12) Autobiographical Number in Java 13) Emirp Number in Java 14) Sphenic Number in Java 15) Buzz Number Java 16) Duck Number Java 17) Evil Number Java 18) ISBN Number Java 19) Krishnamurthy Number Java 20) Bouncy Number in Java 21) Mystery Number in Java 22) Smith Number in Java 23) Strontio Number in Java 24) Xylem and Phloem Number in Java 25) nth Prime Number Java 26) Java Program to Display Alternate Prime Numbers 27) Java Program to Find Square Root of a Number Without sqrt Method 28) Java Program to Swap Two Numbers Using Bitwise Operator 29) Java Program to Find GCD of Two Numbers 30) Java Program to Find Largest of Three Numbers 31) Java Program to Find Smallest of Three Numbers Using Ternary Operator 32) Java Program to Check if a Number is Positive or Negative 33) Java Program to Check if a Given Number is Perfect Square 34) Java Program to Display Even Numbers From 1 to 100 35) Java Program to Display Odd Numbers From 1 to 100 36) Java Program to Find Sum of Natural Numbers
Can you provide a list of Java Array Programs?
1) Java Program to copy all elements of one array into another array 2) Java Program to find the frequency of each element in the array 3) Java Program to left rotate the elements of an array 4) Java Program to print the duplicate elements of an array 5) Java Program to print the elements of an array 6) Java Program to print the elements of an array in reverse order 7) Java Program to print the elements of an array present on even position 8) Java Program to print the elements of an array present on odd position 9) Java Program to print the largest element in an array 10) Java Program to print the smallest element in an array 11) Java Program to print the number of elements present in an array 12) Java Program to print the sum of all the items of the array 13) Java Program to right rotate the elements of an array 14) Java Program to sort the elements of an array in ascending order 15) Java Program to sort the elements of an array in descending order 16) Java Program to Find 3rd Largest Number in an array 17) Java Program to Find 2nd Largest Number in an array 18) Java Program to Find Largest Number in an array 19) Java to Program Find 2nd Smallest Number in an array 20) Java Program to Find Smallest Number in an array 21) Java Program to Remove Duplicate Element in an array 22) Java Program to Print Odd and Even Numbers from an array 23) How to Sort an Array in Java
Can you provided a list of Java Matrix Programs?
1) Java Matrix Programs 2) Java Program to Add Two Matrices 3) Java Program to Multiply Two Matrices 4) Java Program to subtract the two matrices 5) Java Program to determine whether two matrices are equal 6) Java Program to display the lower triangular matrix 7) Java Program to display the upper triangular matrix 8) Java Program to find the frequency of odd & even numbers in the given matrix 9) Java Program to find the product of two matrices 10) Java Program to find the sum of each row and each column of a matrix 11) Java Program to find the transpose of a given matrix 12) Java Program to determine whether a given matrix is an identity matrix 13) Java Program to determine whether a given matrix is a sparse matrix 14) Java Program to Transpose matrix
Can you provide a list of Java String Programs?
1) Java Program to count the total number of characters in a string 2) Java Program to count the total number of characters in a string 2 3) Java Program to count the total number of punctuation characters exists in a String 4) Java Program to count the total number of vowels and consonants in a string 5) Java Program to determine whether two strings are the anagram 6) Java Program to divide a string in 'N' equal parts. 7) Java Program to find all subsets of a string 8) Java Program to find the longest repeating sequence in a string 9) Java Program to find all the permutations of a string 10) Java Program to remove all the white spaces from a string 11) Java Program to replace lower-case characters with upper-case and vice-versa 12) Java Program to replace the spaces of a string with a specific character 13) Java Program to determine whether a given string is palindrome 14) Java Program to determine whether one string is a rotation of another 15) Java Program to find maximum and minimum occurring character in a string 16) Java Program to find Reverse of the string 17) Java program to find the duplicate characters in a string 18) Java program to find the duplicate words in a string 19) Java Program to find the frequency of characters 20) Java Program to find the largest and smallest word in a string 21) Java Program to find the most repeated word in a text file 22) Java Program to find the number of the words in the given text file 23) Java Program to separate the Individual Characters from a String 24) Java Program to swap two string variables without using third or temp variable. 25) Java Program to print smallest and biggest possible palindrome word in a given string 26) Reverse String in Java Word by Word 27) Reserve String without reverse() function
Can you provide a list of Java Searching and Sorting Programs?
1) Linear Search in Java 2) Binary Search in Java 3) Bubble Sort in Java 4) Selection Sort in Java 5) Insertion Sort in Java
Can you provide a list of Java Conversion Programs?
1) How to convert String to int in Java 2) How to convert int to String in Java 3) How to convert String to long in Java 4) How to convert long to String in Java 5) How to convert String to float in Java 6) How to convert float to String in Java 7) How to convert String to double in Java 8) How to convert double to String in Java 9) How to convert String to Date in Java 10) How to convert Date to String in Java 11) How to convert String to char in Java 12) How to convert char to String in Java 13) How to convert String to Object in Java 14) How to convert Object to String in Java 15) How to convert int to long in Java 16) How to convert long to int in Java 17) How to convert int to double in Java 18) How to convert double to int in Java 19) How to convert char to int in Java 20) How to convert int to char in Java 21) How to convert String to boolean in Java 22) How to convert boolean to String in Java 23) How to convert Date to Timestamp in Java 24) How to convert Timestamp to Date in Java 25) How to convert Binary to Decimal in Java 26) How to convert Decimal to Binary in Java 27) How to convert Hex to Decimal in Java 28) How to convert Decimal to Hex in Java 29) How to convert Octal to Decimal in Java 30) How to convert Decimal to Octal in Java
Can you provide a list of Java Pattern programs?
1) Java program to print the following spiral pattern on the console 2) Java program to print the following pattern 3) Java program to print the following pattern 2 4) Java program to print the following pattern 3 5) Java program to print the following pattern 4 6) Java program to print the following pattern 5 7) Java program to print the following pattern on the console 8) Java program to print the following pattern on the console 2 9) Java program to print the following pattern on the console 3 10) Java program to print the following pattern on the console 4 11) Java program to print the following pattern on the console 5 12) Java program to print the following pattern on the console 6 13) Java program to print the following pattern on the console 7 14) Java program to print the following pattern on the console 8 15) Java program to print the following pattern on the console 9 16) Java program to print the following pattern on the console 10 17) Java program to print the following pattern on the console 11 18) Java program to print the following pattern on the console 12
Can you provide a list of Java Singly Linked List Programs?
1) Singly linked list Examples in Java 2) Java Program to create and display a singly linked list 3) Java program to create a singly linked list of n nodes and count the number of nodes 4) Java program to create a singly linked list of n nodes and display it in reverse order 5) Java program to delete a node from the beginning of the singly linked list 6) Java program to delete a node from the middle of the singly linked list 7) Java program to delete a node from the end of the singly linked list 8) Java program to determine whether a singly linked list is the palindrome 9) Java program to find the maximum and minimum value node from a linked list 10) Java Program to insert a new node at the middle of the singly linked list 11) Java program to insert a new node at the beginning of the singly linked list 12) Java program to insert a new node at the end of the singly linked list 13) Java program to remove duplicate elements from a singly linked list 14) Java Program to search an element in a singly linked list
Can you provide a list of Java Circular Linked List Programs?
1) Java program to create and display a Circular Linked List 2) Java program to create a Circular Linked List of N nodes and count the number of nodes 3) Java program to create a Circular Linked List of n nodes and display it in reverse order 4) Java program to delete a node from the beginning of the Circular Linked List 5) Java program to delete a node from the end of the Circular Linked List 6) Java program to delete a node from the middle of the Circular Linked List 7) Java program to find the maximum and minimum value node from a circular linked list 8) Java program to insert a new node at the beginning of the Circular Linked List 9) Java program to insert a new node at the end of the Circular Linked List 10) Java program to insert a new node at the middle of the Circular Linked List 11) Java program to remove duplicate elements from a Circular Linked List 12) Java program to search an element in a Circular Linked List 13) Java program to sort the elements of the Circular Linked List
Can you provide a list of Java Doubly Linked List Programs?
1) Java program to convert a given binary tree to doubly linked list 2) Java program to create a doubly linked list from a ternary tree 3) Java program to create a doubly linked list of n nodes and count the number of nodes 4) Java program to create a doubly linked list of n nodes and display it in reverse order 5) Java program to create and display a doubly linked list 6) Java program to delete a new node from the beginning of the doubly linked list 7) Java program to delete a new node from the end of the doubly linked list 8) Java program to delete a new node from the middle of the doubly linked list 9) Java program to find the maximum and minimum value node from a doubly linked list 10) Java program to insert a new node at the beginning of the Doubly Linked list 10) Java program to insert a new node at the end of the Doubly Linked List 12) Java program to insert a new node at the middle of the Doubly Linked List 13) Java program to remove duplicate elements from a Doubly Linked List 14) Java program to rotate doubly linked list by N nodes 15) Java program to search an element in a doubly linked list 16) Java program to sort the elements of the doubly linked list
Can you provide a list of Java Tree Programs?
1) Java Program to calculate the Difference between the Sum of the Odd Level and the Even Level Nodes of a Binary Tree 2) Java program to construct a Binary Search Tree and perform deletion and In-order traversal 3) Java program to convert Binary Tree to Binary Search Tree 4) Java program to determine whether all leaves are at same level 5) Java program to determine whether two trees are identical 6) Java program to find maximum width of a binary tree 7) Java program to find the largest element in a Binary Tree 8) Java program to find the maximum depth or height of a tree 9) Java program to find the nodes which are at the maximum distance in a Binary Tree 10) Java program to find the smallest element in a tree 11) Java program to find the sum of all the nodes of a binary tree 12) Java program to find the total number of possible Binary Search Trees with N keys 13) Java program to implement Binary Tree using the Linked List 14) Java program to search a node in a Binary Tree
What is the difference between an object-oriented programming language and object-based programming language?
Object-based programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are examples of object-based programming languages.
What is Java Naming Convention?
Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc. But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape. All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.
What is the Advantage of Naming Conventions in Java?
By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.
What are the Naming Conventions of the Different Identifiers?
Naming Conventions of the Different Identifiers The following table shows the popular conventions used for the different identifiers. Identifiers Type: Class Naming Rules: It should start with the uppercase letter. It should be a noun such as Color, Button, System, Thread, etc. Use appropriate words, instead of acronyms. Examples: public class Employee { //code snippet } Identifiers Type: Interface Naming Rules: It should start with the uppercase letter. It should be an adjective such as Runnable, Remote, ActionListener. Use appropriate words, instead of acronyms. Examples: interface Printable { //code snippet } Identifiers Type: Method Naming Rules: It should start with lowercase letter. It should be a verb such as main(), print(), println(). If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed(). Examples: class Employee { // method void draw() { //code snippet } } Identifiers Type: Variable Naming Rules: It should start with a lowercase letter such as id, name. It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore). If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName. Avoid using one-character variables such as x, y, z. Examples: class Employee { // variable int id; //code snippet } Identifiers Type: Package Naming Rules: It should be a lowercase letter such as java, lang. If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang. Examples: //package package com.javatpoint; class Employee { //code snippet } Identifiers Type: Constant Naming Rules: It should be in uppercase letters such as RED, YELLOW. If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY. It may contain digits but not as the first letter. Examples: class Employee { //constant static final int MIN_AGE = 18; //code snippet }
What is CamelCase in Java naming conventions?
Java follows camel-case syntax for naming the class, interface, method, and variable. If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
What is Objects and Classes in Java?
In this page, we will learn about Java objects and classes. In object-oriented programming technique, we design a program using objects and classes. An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
What is an object in Java?
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system. An object has three characteristics: -State: represents the data (value) of an object. -Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc. -Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
What is a class in Java?
A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical. A class in Java can contain: -Fields -Methods -Constructors -Blocks -Nested class and interface
What is Instance variable in Java?
A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.
What is Method in Java?
In Java, a method is like a function which is used to expose the behavior of an object. Advantage of Method -Code Reusability -Code Optimization
What is new keyword in Java?
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
Can you provide an example of Object and Class Example: main within the class in Java?
In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value. Here, we are creating a main() method inside the class. //Java Program to illustrate how to define a class and fields //Defining a Student class. class Student{ //defining fields int id;//field or data member or instance variable String name; //creating main method inside the Student class public static void main(String args[]){ //Creating an object or instance Student s1=new Student();//creating an object of Student //Printing values of the object System.out.println(s1.id);//accessing member through reference variable System.out.println(s1.name); } } Output: 0 null
Can you provide an example of Object and Class Example: main outside the class in Java?
In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class. We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method. //Java Program to demonstrate having the main method in //another class //Creating Student class. class Student{ int id; String name; } //Creating another class TestStudent1 which contains the main method class TestStudent1{ public static void main(String args[]){ Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } } Output: 0 null
What are the 3 Ways to initialize object?
There are 3 ways to initialize object in Java. -By reference variable -By method -By constructor
Can you provide an example of Object and Class Example: Initialization through reference in Java?
1) Object and Class Example: Initialization through reference Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable. class Student{ int id; String name; } class TestStudent2{ public static void main(String args[]){ Student s1=new Student(); s1.id=101; s1.name="Sonoo"; System.out.println(s1.id+" "+s1.name);//printing members with a white space } } Output: 101 Sonoo
Can you provide an example of Object and Class Example: Initialization through method in Java?
2) Object and Class Example: Initialization through method In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method. class Student{ int rollno; String name; void insertRecord(int r, String n){ rollno=r; name=n; } void displayInformation(){System.out.println(rollno+" "+name);} } class TestStudent4{ public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); s1.insertRecord(111,"Karan"); s2.insertRecord(222,"Aryan"); s1.displayInformation(); s2.displayInformation(); } } Output: 111 Karan 222 Aryan
Can you provide an example of Object and Class Initialization through a constructor in Java?
We will learn about constructors in Java later. Let's see an example where we are maintaining records of employees. class Employee{ int id; String name; float salary; void insert(int i, String n, float s) { id=i; name=n; salary=s; } void display(){System.out.println(id+" "+name+" "+salary);} } public class TestEmployee { public static void main(String[] args) { Employee e1=new Employee(); Employee e2=new Employee(); Employee e3=new Employee(); e1.insert(101,"ajeet",45000); e2.insert(102,"irfan",25000); e3.insert(103,"nakul",55000); e1.display(); e2.display(); e3.display(); } } Output: 101 ajeet 45000.0 102 irfan 25000.0 103 nakul 55000.0
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are: -By new keyword -By newInstance() method -By clone() method -By deserialization -By factory method etc.
What is Anonymous object?
Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only. If you have to use an object only once, an anonymous object is a good approach. For example: new Calculation();//anonymous object Calling method through a reference: Calculation c=new Calculation(); c.fact(5); Calling method through an anonymous object new Calculation().fact(5); Let's see the full example of an anonymous object in Java. class Calculation{ void fact(int n){ int fact=1; for(int i=1;i<=n;i++){ fact=fact*i; } System.out.println("factorial is "+fact); } public static void main(String args[]){ new Calculation().fact(5);//calling method with anonymous object } } Output: Factorial is 120
How to create multiple objects by one type only in Java?
We can create multiple objects by one type only as we do in case of primitives. Initialization of primitive variables: int a=10, b=20; Initialization of refernce variables: Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects Let's see the example: //Java Program to illustrate the use of Rectangle class which //has length and width data members class Rectangle{ int length; int width; void insert(int l,int w){ length=l; width=w; } void calculateArea(){System.out.println(length*width);} } class TestRectangle2{ public static void main(String args[]){ Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects r1.insert(11,5); r2.insert(3,15); r1.calculateArea(); r2.calculateArea(); } } Output: 55 45
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the reusability of code. We write a method once and use it many times. We do not require to write code again and again. It also provides the easy modification and readability of code, just by adding or removing a chunk of code. The method is executed only when we call or invoke it. The most important method in Java is the main() method.
What is Method Declaration?
The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments. It has six components that are known as method header. Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list. Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier: -Public: The method is accessible by all classes when we use public specifier in our application. -Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined. -Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package. -Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only. Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword. Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name. Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank. Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces.
How to name a Method?
While defining a method, remember that the method name must be a verb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example: Single-word method name: sum(), area() Multi-word method name: areaOfCircle(), stringComparision() It is also possible that a method has the same name as another method name in the same class, it is known as method overloading.
What are the Types of Method?
There are two types of methods in Java: -Predefined Method -User-defined Method
What is Predefined Method?
In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. We can directly use these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related to the corresponding method runs in the background that is already stored in the library. Each and every predefined method is defined inside a class. Such as print() method is defined in the java.io.PrintStream class. It prints the statement that we write inside the method. For example, print("Java"), it prints Java on the console. Let's see an example of the predefined method. Demo.java public class Demo { public static void main(String[] args) { // using the max() method of Math class System.out.print("The maximum number is: " + Math.max(9,7)); } } Output: The maximum number is: 9 In the above example, we have used three predefined methods main(), print(), and max(). We have used these methods directly without declaration because they are predefined. The print() method is a method of PrintStream class that prints the result on the console. The max() method is a method of the Math class that returns the greater of two numbers. We can also see the method signature of any predefined method by using the link https://docs.oracle.com/. When we go through the link and see the max() method signature, we find the following: public static int max(int a, int b) returns the greater of two int values. same value. Parameters: a an argument. b another argument. Returns: the larger of a and b. In the above method signature, we see that the method signature has access specifier public, non-access modifier static, return type int, method name max(), parameter list (int a, int b). In the above example, instead of defining the method, we have just invoked the method. This is the advantage of a predefined method. It makes programming less complicated. Similarly, we can also see the method signature of the print() method.
What is User-defined Method?
The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement. How to Create a User-defined Method Let's create a user defined method that checks the number is even or odd. First, we will define the method. //user defined method public static void findEvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } We have defined the above method named findevenodd(). It has a parameter num of type int. The method does not return any value that's why we have used void. The method body contains the steps to check the number is even or odd. If the number is even, it prints the number is even, else prints the number is odd. How to Call or Invoke a User-defined Method Once we have defined a method, it should be called. The calling of a method in a program is simple. When we call or invoke a user-defined method, the program control transfer to the called method. import java.util.Scanner; public class EvenOdd { public static void main (String args[]) { //creating Scanner class object Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from the user int num=scan.nextInt(); //method calling findEvenOdd(num); } In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer to the method and gives the output accordingly. Let's combine both snippets of codes in a single program and execute it. EvenOdd.java import java.util.Scanner; public class EvenOdd { public static void main (String args[]) { //creating Scanner class object Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from user int num=scan.nextInt(); //method calling findEvenOdd(num); } //user defined method public static void findEvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } } Output 1: Enter the number: 12 12 is even Output 2: Enter the number: 99 99 is odd Let's see another program that return a value to the calling method. In the following program, we have defined a method named add() that sum up the two numbers. It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b, respectively. Therefore, the method adds the value of a and b and store it in the variable s and returns the sum. Addition.java public class Addition { public static void main(String[] args) { int a = 19; int b = 5; //method calling int c = add(a, b); //a and b are actual parameters System.out.println("The sum of a and b is= " + c); } //user defined method public static int add(int n1, int n2) //n1 and n2 are formal parameters { int s; s=n1+n2; return s; //returning the sum } } Output: The sum of a and b is= 24
What is Static Method?
A method that has static keyword is known as static method. In other words, a method that belongs to a class rather than an instance of a class is known as a static method. We can also create a static method by using the keyword static before the method name. The main advantage of a static method is that we can call it without creating an object. It can access static data members and also change the value of it. It is used to create an instance method. It is invoked by using the class name. The best example of a static method is the main() method. Example of static method Display.java public class Display { public static void main(String[] args) { show(); } static void show() { System.out.println("It is an example of static method."); } } Output: It is an example of a static method.
What is Instance Method?
The method of the class is known as an instance method. It is a non-static method defined in the class. Before calling or invoking the instance method, it is necessary to create an object of its class. Let's see an example of an instance method. InstanceMethodExample.java public class InstanceMethodExample { public static void main(String [] args) { //Creating an object of the class InstanceMethodExample obj = new InstanceMethodExample(); //invoking instance method System.out.println("The sum is: "+obj.add(12, 13)); } int s; //user-defined method because we have not used static keyword public int add(int a, int b) { s = a+b; //returning the sum return s; } } Output: The sum is: 25
There are two types of instance method?
There are two types of instance method: -Accessor Method -Mutator Method
What is Accessor Method in Java?
The method(s) that reads the instance variable(s) is known as the accessor method. We can easily identify it because the method is prefixed with the word get. It is also known as getters. It returns the value of the private field. It is used to get the value of the private field . Example: public int getId() { return Id; }
What is Mutator Method in Java?
The method(s) read the instance variable(s) and also modify the values. We can easily identify it because the method is prefixed with the word set. It is also known as setters or modifiers. It does not return anything. It accepts a parameter of the same data type that depends on the field. It is used to set the value of the private field. Example: public void setRoll(int roll) { this.roll = roll; }
Can you provide an Example of accessor and mutator method?
Student.java public class Student { private int roll; private String name; public int getRoll() //accessor method { return roll; } public void setRoll(int roll) //mutator method { this.roll = roll; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void display() { System.out.println("Roll no.: "+roll); System.out.println("Student name: "+name); } }
What is Abstract Method in Java?
The method that does not has method body is known as abstract method. In other words, without an implementation is known as abstract method. It always declares in the abstract class. It means the class itself must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract. Syntax abstract void method_name();
Can you provide an Example of abstract method?
Demo.java abstract class Demo //abstract class { //abstract method declaration abstract void display(); } public class MyClass extends Demo { //method impelmentation void display() { System.out.println("Abstract method?"); } public static void main(String args[]) { //creating object of abstract class Demo obj = new MyClass(); //invoking abstract method obj.display(); } } Output: Abstract method...
What is Factory method in Java?
It is a method that returns an object to the class to which it belongs. All static methods are factory methods. For example, NumberFormat obj = NumberFormat.getNumberInstance();
What is Constructors in Java?
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. There are two types of constructors in Java: no-arg constructor, and parameterized constructor. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
What are the Rules for creating Java constructor?
There are two rules defined for the constructor. 1) Constructor name must be the same as its class name 2) A Constructor must have no explicit return type 3) A Java constructor cannot be abstract, static, final, and synchronized
What are theTypes of Java constructors?
There are two types of constructors in Java: 1) Default constructor (no-arg constructor) 2) Parameterized constructor
What is the Java Default Constructor?
A constructor is called "Default Constructor" when it doesn't have any parameter. Syntax of default constructor: <class_name>(){}
Can you provide an Example of default constructor?
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. //Java Program to create and call a default constructor class Bike1{ //creating a default constructor Bike1(){System.out.println("Bike is created");} //main method public static void main(String args[]){ //calling a default constructor Bike1 b=new Bike1(); } } Output: Bike is create
Can you provide an Example of default constructor that displays the default values?
//Let us see another example of default constructor //which displays the default values class Student3{ int id; String name; //method to display the value of id and name void display(){System.out.println(id+" "+name);} public static void main(String args[]){ //creating objects Student3 s1=new Student3(); Student3 s2=new Student3(); //displaying values of the object s1.display(); s2.display(); } } Output: 0 null 0 null
What is Java Parameterized Constructor?
A constructor which has a specific number of parameters is called a parameterized constructor. Why use the parameterized constructor? The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.
Can you provide an Example of parameterized constructor in Java?
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. //Java Program to demonstrate the use of the parameterized constructor. class Student4{ int id; String name; //creating a parameterized constructor Student4(int i,String n){ id = i; name = n; } //method to display the values void display(){System.out.println(id+" "+name);} public static void main(String args[]){ //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of object s1.display(); s2.display(); } } Output: 111 Karan 222 Aryan
What is Constructor Overloading in Java?
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
Can you provide an Example of Constructor Overloading?
//Java program to overload constructors class Student5{ int id; String name; int age; //creating two arg constructor Student5(int i,String n){ id = i; name = n; } //creating three arg constructor Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } } Output: 111 Karan 0 222 Aryan 25
What is Java Copy Constructor?
There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in Java. They are: -By constructor -By assigning the values of one object into another -By clone() method of Object class In this example, we are going to copy the values of one object into another using Java constructor. //Java program to initialize the values from one object to another object. class Student6{ int id; String name; //constructor to initialize integer and string Student6(int i,String n){ id = i; name = n; } //constructor to initialize another object Student6(Student6 s){ id = s.id; name =s.name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student6 s1 = new Student6(111,"Karan"); Student6 s2 = new Student6(s1); s1.display(); s2.display(); } } Output: 111 Karan 111 Karan
How to copy values without constructor in Java?
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor. class Student7{ int id; String name; Student7(int i,String n){ id = i; name = n; } Student7(){} void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student7 s1 = new Student7(111,"Karan"); Student7 s2 = new Student7(); s2.id=s1.id; s2.name=s1.name; s1.display(); s2.display(); } } Output: 111 Karan 111 Karan
What is Java static keyword?
The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class. The static can be: 1) Variable (also known as a class variable) 2) Method (also known as a class method) 3) Block 4) Nested class
What is Java static variable?
If you declare any variable as static, it is known as a static variable. -The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. -The static variable gets memory only once in the class area at the time of class loading. Advantages of static variable It makes your program memory efficient (i.e., it saves memory). Understanding the problem without static variable class Student{ int rollno; String name; String college="ITS"; } Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the memory only once.
Can you provide an Example of static variable in Java?
//Java Program to demonstrate the use of static variable class Student{ int rollno;//instance variable String name; static String college ="ITS";//static variable //constructor Student(int r, String n){ rollno = r; name = n; } //method to display the values void display (){System.out.println(rollno+" "+name+" "+college);} } //Test class to show the values of objects public class TestStaticVariable1{ public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //we can change the college of all objects by the single line of code //Student.college="BBDIT"; s1.display(); s2.display(); } } Output: 111 Karan ITS 222 Aryan ITS
Can you provide an example Program of the counter without static variable in Java?
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in the count variable. //Java Program to demonstrate the use of an instance variable //which get memory each time when we create an object of the class. class Counter{ int count=0;//will get memory each time when the instance is created Counter(){ count++;//incrementing value System.out.println(count); } public static void main(String args[]){ //Creating objects Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } Output: 1 1 1
Can you provid an example Program of counter by static variable in Java?
static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value. //Java Program to illustrate the use of static variable which //is shared with all objects. class Counter2{ static int count=0;//will get memory only once and retain its value Counter2(){ count++;//incrementing the value of static variable System.out.println(count); } public static void main(String args[]){ //creating objects Counter2 c1=new Counter2(); Counter2 c2=new Counter2(); Counter2 c3=new Counter2(); } } Output: 1 2 3
What is Java static method?
If you apply static keyword with any method, it is known as static method. -A static method belongs to the class rather than the object of a class. -A static method can be invoked without the need for creating an instance of a class. -A static method can access static data member and can change the value of it.
Can you provide an Example of static method in Java?
//Java Program to demonstrate the use of a static method. class Student{ int rollno; String name; static String college = "ITS"; //static method to change the value of static variable static void change(){ college = "BBDIT"; } //constructor to initialize the variable Student(int r, String n){ rollno = r; name = n; } //method to display values void display(){System.out.println(rollno+" "+name+" "+college);} } //Test class to create and display the values of object public class TestStaticMethod{ public static void main(String args[]){ Student.change();//calling change method //creating objects Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); Student s3 = new Student(333,"Sonoo"); //calling display method s1.display(); s2.display(); s3.display(); } } Output: 111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT