by Debasis Samnata
Java provides us to write Java programs in two flavors : applets and Applications. These two kind of programs are differ by the way how a browser and Java interpreter will deal them. Simply speaking, a Java applet is a program that appears embedded in a web document, whereas, a Java Application (it is expressed with capital letters to differentiate from all programs as applications) is the term applied to all other kind of Java programs. There is however number of technical differences between applet and Application. Before gong to discuss about their differences, let us see how these two kind of programs can be developed.
Consider the following few codes as the first Java Application for you :
Illustration 2.1 // Hello Java Application // class helloworld{ public static void main(String args[]){ System.out.println("Hello, World!"); System.out.println("Hi...."+" Debasis"); } }
These lines comprise the minimum components necessary to print Hello Java ! onto the screen .
NOTE: |
1. How to edit this Program: Java program Can be written with any text editor. In Windows or System 7.5 we can use Notepad or EDIT, in Unix vi or emacs can be used. Save this file having name HelloJavaAppln.Java. The name of the Java source file is not arbitrary; it must be the same as the name of the public class (here it is HelloJavaAppln) and extension must be java. 2. How to compile this Program : The Java compiler converts the Java programs into Java byte codes. For Window 95 and NT users, you will need to open a DOS Shell window make sure that you are in the directory you are using to store your Java classes, then enter the following command : javac helloworld.java 3.How to run the Java Application: To run the Application, you have to type the command java ( from the commend prompt ). For example, our helloworld Application can be run as: java helloworld 4. Basic structure of any Application : An Application must contain at least one class which include the main function. It may contain more than one class also. In any case, the name of the Application (program file ) will be according to the name of the class which contains main (…) function. |
Illustration 2.2 // TestArray.java class TestArray{ public static void main(String args[]){ int b[]= {10, 20, 30, 40, 50}; //Initialization //Traversing array for (int i=0; i < a.length; i++){ //length is the property of array System.out.print(a[i]+" "); } System.out.println(); // Average calculation float sum = 0, avg; for(int i=0; i < a.length;i++) //Calculating the sum of the numbers sum += a[i]; avg = sum/a.length; System.out.println("Average = " + avg); } }
Type following two commands :
javac TestArray.java // To compile the source code java TestArray // To run the Application
OUTPUT: |
10 20 30 40 50 |
Illustration 2.3 // a3DArray.java class a3DArray { public static void main(String args[]) { int my3DArray [ ][ ][ ] = new int [3][4][5]; int i, j, k; for(i=0; i<3; i++) for(j=0; j<4; j++) for(k=0; k<5; k++) my3DArray[i][j][k] = i * j * k; for(i=0; i<3; i++) { for(j=0; j<4; j++) { for(k=0; k<5; k++) System.out.print(my3DArray[i][j][k] + " "); System.out.println(); } System.out.println(); } } }
OUTPUT: |
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 0 0 0 0 0 2 4 6 8 0 4 8 12 16 0 6 12 18 24 |
Note: |
The source code stored in a program file whose extension is java; the compiled version of the program file is stored in a file having same name as the source program file but having extension class. These class files are containing java byte code and can be interpreted by Java run time environment i.e. Java interpreter. |
Illustration 2.4 // A Java program to demonstrate working of print() and println() together // Edit Demonstration_41.java class Demonstration_41 { public static void main(String[] args) { int x=555; System.out.println("1. println "); System.out.println("2. println "); System.out.print("1. print "); System.out.print("\n"); System.out.print("2. print "+ "3. Print "+ " " +x); } }
OUTPUT: |
1. println 2. println 1. print 2. print 3. Print 555 |
Illustration 2.5 // A Java program to demonstrate working of printf() in Java // Edit Demonstration_42.java class Demonstration_42 { public static void main(String args[]) { int x = 100; System.out.printf("Printing simple integer: x = %d\n", x); // this will print it upto 2 decimal places System.out.printf("Formatted with precison: PI = %.2f\n", Math.PI); float n = 5.2f; // automatically appends zero to the rightmost part of decimal System.out.printf("Formatted to specific width: n = %2.1f\n", n); n = 2324435.3f; // here number is formatted from right margin and occupies a // width of 20 characters System.out.printf("Formatted to right margin: n = %6.2f\n", n); } }
OUTPUT: |
Printing simple integer: x = 100 Formatted with precison: PI = 3.14 Formatted to specific width: n = 5.2 Formatted to right margin: n = 2324435.25 |
Illustration 2.6 /* Command line input in Java */ // Edit Demonstration_43.java public class Demonstration_43{ public static void main(String args[]){ int i=0; i=Integer.parseInt(args[0]); System.out.println("The value of i in Integer is "+ i); //} //System.out.print(args[i]+" "); //System.exit(0); } }
Illustration 2.7 // Program to check for command line arguments class Demonstration_44 { public static void main(String[] args) { // check if length of args array is // greater than 0 if (args.length > 0) { System.out.println("The command line"+ " arguments are:"); // iterating the args array and printing // the command line arguments for (String val:args) System.out.println(val); } else System.out.println("No command line "+ "arguments found."); } }
OUTPUT: |
No command line arguments found. |
Illustration 2.8 /*The program demonstrates how to take Input using scanner class*/ //Edit Demonstration_45.java import java.util.Scanner; public class Demonstration_45 { public static void main(String args[]) { Scanner scnr = new Scanner(System.in); // Calculating the maximum two numbers in Java System.out.println("Please enter two numbers to find maximum of two"); int a = scnr.nextInt(); int b = scnr.nextInt(); if (a > b) { System.out.printf("Between %d and %d, maximum is %d \n", a, b, a); } else { System.out.printf("Between %d and %d, maximum number is %d \n", a, b, b); } } }
Illustration 2.9 /*The following program snippet shows how to read and write to the console.*/ //Edit Demonstration_46.java import java.util.*; public class Demonstration_46 { public static void main ( String args[] ) { System.out.print ( "Enter the radius: " ); Scanner sc = new Scanner (System.in); double radius = sc.nextDouble(); double area = 3.14159 * radius * radius; System.out.println ( "Area is: " + area ); } }
Illustration 2.10 /*Input with DataInputStream InterestCalculator Program */ //Edit Demonstration_47.java import java.io.*; class Demonstration_47{ public static void main(String args[ ] ) throws Exception { // throws Exception Float principalAmount = new Float(0); Float rateOfInterest = new Float(0); int numberOfYears = 0; //try{ DataInputStream in = new DataInputStream(System.in); String tempString; System.out.print("Enter Principal Amount: "); System.out.flush(); tempString = in.readLine(); principalAmount = Float.valueOf(tempString); System.out.print("Enter Rate of Interest: "); System.out.flush(); tempString = in.readLine(); rateOfInterest = Float.valueOf(tempString); System.out.print("Enter Number of Years: "); System.out.flush(); tempString = in.readLine(); numberOfYears = Integer.parseInt(tempString); // Input is over: calculate the interest float interestTotal = principalAmount*rateOfInterest*numberOfYears; System.out.println("Total Interest = " + interestTotal); // } // catch (Exception ex) // {} } }
Applets are the most effective Java programs is shown in Illustration 2.11 :
Illustration 2.11 : // An applet version of HelloHavaAppln // /* create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file. */ import java.awt.Graphics; import java.applet.Applet; public class HelloJava extends Applet { public void paint (Graphics g ) { g.drawString ( “ Hello Java !” 50, 25 ); } } // Html code < html> < body> < applet code=" HelloJava.class" width="200" height="100"> < / applet> < / body> < / html>
These are the essential code to display the message Hello Java ! onto the screen. Novice programmer may be puzzled with so many new lines, but this is just for an adventure, actual understanding will take place in due time. This applet will be edited in the same fashion as Application. The name of the applets will be same as the public class ( here HelloJava.java ). The program then can be compiled using javac in the same manner as an Application is compiled. The Java compiler produces a file named HelloJava.class .
How to run the Java applet : Before going to run the Java applet, we have to create an HTML document to host it. In HTML, type this few line through any editor (don’t worry, everything will be discussed in detail).
< applet code = HelloJava.class width =200 height =100> < / applet >
This is the minimum HTML Page for running the Java Applet HelloJava. Save this file by giving a name HelloJava.html (the name of the file should be same as the name of the class and extension must be html ).
Afte the HTML page is prepared, the applet is ready for execution.If you have any browser ( like HotJava or Netscape), invoke this browser, open the HTML file and click then RUN button on it. Other way, the JDK includes a program appletviewer which also can be used to run the applet. Type the following command on command line:
NOTE: |
Figure 2.1 represents the basic components in any Java applet : Let us explain the various parts in context of the applet HelloJava : Part 1: HelloJava imports two classes, namely : Part 2:Name of the applet HelloJava is placed in place of NewAppletName. Part 3 : There are no variable declared and used in this applet . This part is hence, optional. Part 4:Only one method vide public void paint( Graphics g ) is declared in this applet which is defined with a function drawString (……) ; this function is defined in Graphics.class. Here, Part 4 is the main component in any applet. This includes the various method(s) which actually defines the applet. These methods are responsible for interacting between the browser and applet. In fact, no user defined routines are required to define an applet. There are number of routines available in the class Applet. Programmer can use these or can override these function. Following Section 2.2.1 gives an idea about these methods |
Figure 2.1 Basic Structure of an applet |
Illustration 2.12 : /* A "Hello, World" Applet*/ // Demonstration_22.java import java.applet.*; import java.awt.*; public class Demonstration_22 extends Applet { public void paint (Graphics g) { g.drawString ("Hello World", 25, 50); } } } // Html code < html> < title>The Hello, World Applet< / title> < hr> < applet code = "Demonstration_22.class" width = "320" height = "120"> If your browser was Java-enabled, a "Hello, World" message would appear here. < / applet> < hr> < / html>
There is a number of applet member functions are define in java.applet.Applet class. These applet methods are very much useful to define any applet. During the building of an applet, a programmer can override them, of course, some methods can not be allowed for overriding. Another point is there, these method be called in an applet in a given order. These methods are briefly discussed in the order in which they should be placed in an applet.
Illustration 2.13 /* Resize Applet Window Example*/ // Demonstration_23.java import java.applet.Applet; import java.awt.Graphics; public class Demonstration_23 extends Applet{ public void paint(Graphics g){ /* * To resize an applet window use, * void resize(int x, int y) method of an applet class. */ resize(300,300); g.drawString("Window has been resized to 300,300", 50, 50); } } // Html code < html> < title>The Hello, World Applet< / title> < hr> < applet code = "Demonstration_23.class" width = "200" height = "200"> < / applet> < hr> < / html>One can pass number of information to an applet through HTML document by init( ) method. Illustration 2.14 is such an attempt.
Illustration 2.14 // Use of init( ) to pass value through HTML to applet // import java .awt . *; import java.applet. * ; public class RectangleTest extends applet { int x, y, w, h; public void init ( ) { x = Integer.parseInt(get Parameter (“ xValue” )); y = Integer.parseInt(get Parameter (“ yValue” )); w = Integer.parseInt(get Parameter (“ wValue” )); h = Integer.parseInt(get Parameter (“ hValue” )); } public void paint ( Graphics g ) { g.drawRect (x, y, w, h ); } }
Corresponding HTML document containing this applet and providing parameter values is mentioned as below :
< applet code = ” RectangleTest” width = 150 height = 100 >
< param name = xValue value = 20 >
< param name = yValue value = 40 >
< param name = wValue value = 100>
< param name = hValue value = 50 >
Observe, how < param ….> tag and getParameter (String S ) ( defined in Applet Class ) can be used. It is not necessary that getParameter(..) should be in the same order as parameter values passed in HTML; also if some parameter is not available, getParameter(..) will return a default value which is null.
Public void start()
The start() method called after the init() method; it starts the applet. Suppose this method is overriden in an applet MusicApp. class :
public void start ( ) { is Stopped = false ; // Start the music //. MusicClip.play ( ); // This is defined in some where. }
Suppose, this applet is loaded in an HTML file, and that HTML document is displayed on the screen; there is a link point on the document for the applet. If we click this link point ( by mouse ) then this applet will start its working. With the help of this function, then an applet can be called multiple times if the user keeps leaving and returning to the HTML document. It can be noted that, init() is called once - the first time an applet is loaded, start() is called each time the applet’s link is activated. Actual illustration of start() method will take place after discussing Thread and Event.
Public void stop()
The stop() method stops the applet running. This method is called when the browser wishes to stop executing the document or whenever the user leaves the applet. This method can be overriden in an applet, an example includes as below :
public void stop ( ) { is Stopped = true; if ( / * music is playing ? */) { // Stop the music MusicClip.stop ( ) // This should be define in some where } }
Public void paint(Graphics g)
This method can be overriden in applet. Whenever browser needs to redraw the applet. A number of graphics methods are defined in java.awt.Graphics which can be included in this method to define it. What are the different graphics drawing method is available will be discussed during the discussion of Graphics in Java (Chapter 7, Part II and Chapter 4, Part III).
Illustration 2.15 import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class Demonstration_24 extends Applet { public void init() { // Here we change the default grey color background of an // applet to yellow background. setBackground(Color.YELLOW); } public void paint(Graphics g) { g.setColor(Color.BLACK); g.drawString("Applet background example", 0, 50); } } // Html code < html> < title>The Hello, World Applet< / title> < hr> < applet code = "Demonstration_24.class" width = "200" height = "200"> < / applet> < hr> < / html>
Illustration 2.16 /* Specifying Applet Parameters*/ public void init () { String squareSizeParam = getParameter ("squareSize"); parseSquareSize (squareSizeParam); String colorParam = getParameter ("color"); Color fg = parseColor (colorParam); setBackground (Color.black); setForeground (fg); } private void Demonstration_25 (String param) { if (param == null) return; try { squareSize = Integer.parseInt (param); } catch (Exception e) { // Let default value remain } } // Html code < html> < title> The Hello, World Applet < / title> < hr> < applet code = " Demonstration_25.class" width = "480" height = "320"> < param name = "color" value = "blue"> < param name = "squaresize" value = "30"> < / applet> < hr> < / html>
Illustration 2.17 /* Simple example of Applet by appletviewer tool:*/ import java.applet.Applet; import java.awt.Graphics; public class Demonstration_26 extends Applet{ public void paint(Graphics g){ g.drawString("welcome to applet",150,150); } } /* < applet code="Demonstration_26.class" width="300" height="300"> < / applet> */ To execute the applet by appletviewer tool, write in command prompt: c:\>javac Demonstration_21.java c:\>appletviewer Demonstration_21.java
In ths Section, we will find the technical differences between applet and Application. As we illustrated earlier, a Java interpreter is a class that the Java Application is a class that the Java interpreter knows is going to have a specific method in it called main( ), which it looks for when it tries to run the Application. On the other hand, a Java applet is a specific kind of application that is run from the browser (like HotJava, Netscape, appletviewer (known also as a mini browser )), rather than having a single main( ) method, a Java applet instead implements a set of methods that deal with of how to interact with the browser and applet.
Another technical difference between applet and Application stem from the context in which they run. A Java Application runs in the simplest possible environment - its only input from the outside world is a list of command line parameters. On the other hand, a Java applet needs a lot of information from environment; it needs to know when it is initialized, when and where to draw itself in the browser window, and when it is activated or deactivated. As a consequence of these two very different execution environments, applet and Application have different minimum requirement.
The major technical differences are summarized in Table 2.1.
Table 2.1
Technical Point |
Java Application |
Java applet |
Method expected by the JVM |
main ( ) - start up routine |
No main ( ) but some methods |
|
|
|
Environment Inputs |
Only command line parameters |
Parameters are embedded in the host HTML document |
|
|
|
Distribution |
Loaded from the file system or by a custom class loading process |
Java application and transported via HTTP |
|
|
|
Memory requirement |
Minimal Java application requirement |
Java application plus browser memory requirement |
|
|
|
User Graphics |
It is optional |
It is inherently graphical |
Now, here the question that arises is to decide whether we write an applet or an Application to develop an application in Java. Java applets are preferred when graphical user interface is desirable, Java Applications are preferred over applets when graphical displays are undesirable. Java Applications are found in building applications for network servers, consumer electronic etc. (when no graphical displays is involved ). On the other hand to prepare Web document, where huge graphical display may involved, and which are to be transported through the Internet, applets are the good solutions.
So for size and complexity are concerned, there is no limit to the size or complexity of the both kind of applications, however, with the Internet where communication speed is limited and down load times are long, most Java applets are small by necessity.
Practice 2.1 /* One more simple Java Application. This application computes square root */ //Edit SquareRoot.java import java.lang.Math; class SquareRoot{ public static void main (String args[ ]) { double x = 45; // Variable declaration and initialization double y; // Declaration of another variable y = Math.sqrt(x); System.out.println("Square root of "+ x +"=" + y); } } Is the compilation successful? What is the output?
Practice 2.2 /* Example java program without any class */ // Edit HelloNoClass.java public static void main (String args[ ] ) { System.out.println( "Hello Classless Java!]); } Type following two commands to run the HelloNoClass.java Application: javac HelloNoClass.java // To compile java HelloNoClass // To run the program Is the compilation successful? What is about the execution?
Practice 2.3 /* Application with more than one classes within same java file */ //Edit PeopleApp.java class FirstClass { int idNo; idNo = 555; public static void print( ) { System.out.println ( " First Class citizen" + idNo ); } } class SecondClass { int idNo; idNo = 111; public static void print( ) { System.out.println ( " Second Class citizen " + idNo) ; } } public class PeopleApp { FirstClass female; SecondClass male; public static void main( String args[ ] ) { System.out.print("People from Java World"); female.print( ); male.print( ); } } (This problem has a minor mistake. Identify the mistake and then write the correct code.)
Practice 2.4 /* Application with more than one class in separate java file */ //Edit AnotherFirstClass.java class AnotherFirstClass { static int idNo = 777; public static void print( ) { System.out.println ( " First Class citizen" + idNo ); } } //Edit AnotherSecondClass.java class AnotherSecondClass { static int idNo = 888; public static void print( ) { System.out.println ( " Second Class citizen " + idNo) ; } } //Edit AnotherPeopleApp.java public class AnotherPeopleApp { public static void main( String args[ ] ) { AnotherFirstClass female = new AnotherFirstClass(); AnotherSecondClass male = new AnotherSecondClass(); System.out.print("People from Java World"); female.print( ); male.print( ); } } What is the output?
Practice 2.5 /* This program passes inputs to the Application through command line arguments */ // CommnadLineInputTest.java class CommnadLineInputTest{ public static void main(String args[ ] ) { int count; String aString; count = args.length; System.out.println( "Number of arguments ="+ count); for(int i = 0; i < count; i++) { aString = args[0]; System.out.println( "args["+i+"]"+"="+ aString); } } } Type following two commands to run the CommandLineInputTest.java Application : javac CommandLineInputTest.java java CommandLineInputTest Kolkata Chennai Mumbai Delhi Goa What is the output?
Practice 2.6 /* This is a Java Application to read a number from the standard input * and display the number. */ // ReadNumber.java import java.io.*; class ReadNumber{ public static void main(String args[ ] ) { Float number1 = new Float(0); Float number2 = new Float(0); DataInputStream in = new DataInputStream(System.in); String tempString; System.out.print("Enter a number: "); System.out.flush(); tempString = in.readLine(); number1 = Float.valueOf(tempString); System.out.print("Enter another number: "); System.out.flush(); tempString = in.readLine(); number2 = Float.valueOf(tempString); System.out.println("Number 1: "+number1); System.out.println("Number 2: "+number2); } What is the output?
Practice 2.7 /* while loop example */ class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } What is the output?
Practice 2.8 /* DoWhile loop example */ class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } } What is the output?
Practice 2.9 /* while loop example */ class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } What is the output?
Practice 2.10 /* For loop example */ class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } } What is the output?
Practice 2.9 /* Loop example with continue */ class Continue { public static void main(String args[]) { for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0) continue; System.out.println(""); } } } What is the output?
Practice 2.11 /* Loop example with break*/ class BreakLoop { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } } what is the output?
Practice 2.12 /* Test for primes */ class FindPrime { public static void main(String args[]) { int num; boolean isPrime = true; num = 14; for(int i=2; i <= num/2; i++) { if((num % i) == 0) { isPrime = false; break; } } if(isPrime) System.out.println("Prime"); else System.out.println("Not Prime"); } } what is the output?
Practice 2.13 /* Menu selection using do-while and switch-case */ class Menu { public static void main(String args[]) throws java.io.IOException { char choice; do { System.out.println("Help on:"); System.out.println(" 1. if"); System.out.println(" 2. switch"); System.out.println(" 3. while"); System.out.println(" 4. do-while"); System.out.println(" 5. for\n"); System.out.println("Choose one:"); choice = (char) System.in.read(); } while( choice < '1' || choice > '5'); System.out.println("\n"); switch(choice) { case '1': System.out.println("The if:\n"); System.out.println("if(condition) statement;"); System.out.println("else statement;"); break; case '2': System.out.println("The switch:\n"); System.out.println("switch(expression) {"); System.out.println(" case constant:"); System.out.println(" statement sequence"); System.out.println(" break;"); System.out.println(" // ..."); System.out.println("}"); break; case '3': System.out.println("The while:\n"); System.out.println("while(condition) statement;"); break; case '4': System.out.println("The do-while:\n"); System.out.println("do {"); System.out.println(" statement;"); System.out.println("} while (condition);"); break; case '5': System.out.println("The for:\n"); System.out.print("for(init; condition; iteration)"); System.out.println(" statement;"); break; } } } what is the output?
Practice 2.14 /* Example of recursion */ class Recursion { public static void main(String args[]) { myMethod(10); // pass positive integer } void myMethod( int counter) { if(counter == 0) return; else { System.out.println("hello" + counter); myMethod(--counter); System.out.println(""+counter); return; } } } what is the output?
Write java program to calculate the Square of a number. | |
Write java program to add two numbers, take input as command line argument. | |
Write java program to multiply two numbers, numbers should be taken from standard input. | |
Write Java program to read the three integers a, b and c from the keyboard and then print the largest value read. | |
Write a Java Application to read the name of a student (studentName), roll Number (rollNo) and marks (totalMarks) obtained. rollNo may be an alphanumeric string. Display the data as read.. | |
Write Java program to calculate the perimeter and the area of the circle. The radius of the circle is taken as user input. Use to different functions to calculate the perimeter and area. Define the value of PI as class constant. | |
Write a program to check the number is even or odd. Input is taken from keyboard. | |
Write a program to find out the number of days in a month using switch-case. Month number and year is taken as input through keyboard. | |
Write java program to calculate the Sum of the square of first 10 integers. | |
Write java program to calculate the Factorial of a 10 (iteratively and recursively). | |
Write a program to calculate the grade of a student. There are five subjects. Marks in each subject are entered from keyboard. Assign grade based on the following rule:
Total Marks >= 90 Grade: Ex 90 > Total Marks >= 80 Grade: A 80 > Total Marks >= 70 Grade: B 70 > Total Marks >= 60 Grade: C 60 > Total Marks Grade: F |
Why are there no global variables in java? | |
Global variables are considered bad form for a variety of reasons: adding state variables breaks referential transparency, state variables lessen the cohesion of a program. | |
What is Dynamic Method Dispatch? | |
Dynamic method dispatch is the mechanism by which a call to an overridden function is resolved at run time, rather than at compile time. | |
What is the use of bin and lib in JDK? | |
Bin contains all tools such as javac, appletviewer, awt tool etc. whereas lib contains API and all packages. | |
What are the different types of casting? | |
There are two types of casting Casting between numeric types is used to convert larger values into smaller values. For e.g. double values to byte values. Casting between object references helps you refer to an object by a compatible class, interface, or array type reference. | |
What is heap in Java? | |
Java is fully Object oriented language. It has two phases first one is Compilation phase and second one is interpretation phase. The Compilation phase convert the java file to class file (byte code is only readable format of JVM) than interpretation phase interoperate the class file line by line and give the proper result. | |
What type of parameter passing does Java support? | |
In Java the arguments are always passed by value. | |
What is garbage collection? | |
If no reference to an object, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.This is known as garbage collection | |
Describe the Garbage Collection process in Java? | |
The JVM spec mandates automatic garbage collection outside of the programmer’s control. The System.gc() or Runtime.gc() is merely a suggestion to the JVM to run the GC process but is NOT guaranteed. | |
How do you traverse through a collection using its Iterator? | |
To use an iterator to traverse through the contents of a collection, follow these steps:
| |
What are the main implementations of the List interface ? | |
The main implementations of the List interface are as follows :
| |
What are the advantages of ArrayList over arrays ? | |
Some of the advantages ArrayList has over arrays are:
| |
Why insertion and deletion in ArrayList is slow compared to LinkedList ? | |
| |
How do you decide when to use ArrayList and When to use LinkedList? | |
If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation. | |
What are the main Implementations of the Set interface ? | |
The main implementations of the List interface are as follows:
HashSet TreeSet LinkedHashSet EnumSet | |
What Are the different Collection Views That Maps Provide? | |
Maps Provide Three Collection Views.
Key Set - allow a map's contents to be viewed as a set of keys. Values Collection - allow a map's contents to be viewed as a set of values. Entry Set - allow a map's contents to be viewed as a set of key-value mappings. | |
What is String subsequence method? | |
Java 1.4 introduced Char Sequence interface and String implements this interface, this is the only reason for the implementation of sub Sequence method in String class. Internally it invokes the String substring method. | |
What are different ways to create String Object? | |
We can create String Object using new operators like any normal java class or we can use double quotes to create a String object. There are several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilder. | |
Can we use String in switch case? | |
Java 7 extended the capability of switch case to use Strings also, earlier versions doesn't support this. | |
How to convert String to byte array and vice versa? | |
We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String. | |
How do you check if two Strings are equal in Java? | |
There are two ways to check if two Strings are equal or not – using "==" operator or using equals method. When we use "==" operator, it checks for value of Strings as well as reference but in our programming, most of the time we are checking equality of String for value only. So we should use equal method to check if two Strings are equal or not. | |
Difference between String, StringBuffer and StringBuilder? | |
When the intern method is invoked, if the pool already contains a string equal to this string object as determined by the equal (Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. These method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings. |