import java.util.Scanner;
class SecondLargest {
public static void main(String[] args) {
int secondlargest = Integer.MIN_VALUE;
int largest = Integer.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++)
{
arr[i] = input.nextInt();
if (largest < arr[i])
{
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}
Showing posts with label Common Sol. Show all posts
Showing posts with label Common Sol. Show all posts
Friday, 3 May 2013
Find Second Largest Number In Array Without Sorting
Thursday, 24 January 2013
What is Dynamic Language
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system,
all during program execution. These behaviors can be emulated in nearly
any language of sufficient complexity, but dynamic languages provide
direct tools to make use of them. Many of these features were first
implemented as native features in the Lisp programming language.
Closures[6] are one of the core tools of functional programming, and many languages support at least this degree of functional programming.
Assembly, C, C++, early Java, and FORTRAN do not generally fit into this category.
Examples
The following are generally considered dynamic languages:- ActionScript
- BASIC
- BeanShell[3]
- Clojure
- ColdFusion
- Common Lisp and most other Lisps
- Dylan
- Groovy[4]
- E programming language
- Fancy
- Java programming language
- JavaScript
- VBScript
- MATLAB / Octave
- Lua
- Objective-C
- Perl
- PHP
- Powershell
- Python
- Ruby
- Smalltalk
- Tcl
- R
- Julia
Eval
Some dynamic languages offer an eval function. This function takes a string parameter containing code in the language, and executes it. If this code stands for an expression, the resulting value is returned. However, Erik Meijer and Peter Drayton suggest that programmers "use eval as a poor man's substitute for higher-order functions."[5]Object runtime alteration
A type or object system can typically be modified during runtime in a dynamic language. This can mean generating new objects from a runtime definition or based on mixins of existing types or objects. This can also refer to changing the inheritance or type tree, and thus altering the way that existing types behave (especially with respect to the invocation of methods).Functional programming
Functional programming concepts are a feature of many dynamic languages, and also derive from Lisp.Closures
One of the most widely used aspects of functional programming in dynamic languages is the closure, which allows creating a new instance of a function which retains access to the context in which it was created. A simple example of this is generating a function for scanning text for a word:function new_scanner (word)
temp_function = function (input)
scan_for_text (input, word)
end function
return temp_function
end function
Note that the inner function has no name, and is instead stored in the variable temp_function. Each time new_scanner is executed, it will return a new function which remembers the value of the word parameter that was passed in when it was defined.Closures[6] are one of the core tools of functional programming, and many languages support at least this degree of functional programming.
Continuations
Another feature of some dynamic languages is the continuation. Continuations represent execution state that can be re-invoked. For example, a parser might return an intermediate result and a continuation that, when invoked, will continue to parse the input. Continuations interact in very complex ways with scoping, especially with respect to closures. For this reason, many dynamic languages do not provide continuations.Reflection
Reflection is common in many dynamic languages, and typically involves analysis of the types and metadata of generic or polymorphic data. It can, however, also include full evaluation and modification of a program's code as data, such as the features that Lisp provides in analyzing S-expressions.Macros
A limited number of dynamic programming languages provide features which combine code introspection and eval in a feature called macros. Most programmers today who are aware of the term macro have encountered them in C or C++, where they are a static feature which are built in a small subset of the language, and are capable only of string substitutions on the text of the program. In dynamic languages, however, they provide access to the inner workings of the compiler, and full access to the interpreter, virtual machine, or runtime, allowing the definition of language-like constructs which can optimize code or modify the syntax or grammar of the language.Assembly, C, C++, early Java, and FORTRAN do not generally fit into this category.
Make a desktop icon for a web page shortcut?
Sure! For the most part the desktop just holds shortcuts, and pretty much any shortcut will do.
And there's several ways to create them.
And there's several ways to create them.
•
Right click on your desktop, and select "New Shortcut". Enter http://hotmail.com as the location of the item, hit next, give it a reasonable name (like "Hotmail"), and you're done.
It's just that easy.
If you like, you can then add that shortcut to your start menu as well. Click and hold on the desktop icon. Now drag it over the Start button. Don't let go, wait and the start menu will pop up. Drag the icon to a position on the menu and release. You could also hold it over a sub menu, wait for that to pop out, and then release in the position you would like it to live on that sub menu.
The reverse works as well... click and hold on a start menu item, drag it to your desktop and release. The shortcut will be removed from the menu and appear on your desktop. If you want the shortcut to remain in both places, hold down the CTRL key before you drop the icon on the desktop.
Shortcuts can be created for programs, as you probably already know, and URLs, as we just showed. You can also create shortcuts for any document or file that Windows knows how to handle: for example ".doc" files, ".mp3" files and others.
It's just that easy.
If you like, you can then add that shortcut to your start menu as well. Click and hold on the desktop icon. Now drag it over the Start button. Don't let go, wait and the start menu will pop up. Drag the icon to a position on the menu and release. You could also hold it over a sub menu, wait for that to pop out, and then release in the position you would like it to live on that sub menu.
The reverse works as well... click and hold on a start menu item, drag it to your desktop and release. The shortcut will be removed from the menu and appear on your desktop. If you want the shortcut to remain in both places, hold down the CTRL key before you drop the icon on the desktop.
Shortcuts can be created for programs, as you probably already know, and URLs, as we just showed. You can also create shortcuts for any document or file that Windows knows how to handle: for example ".doc" files, ".mp3" files and others.
Wednesday, 23 January 2013
24 Hour Clock Time Conversion Table
1:00 AM equals 01:00
|
2:00 AM equals 02:00
|
3:00 AM equals 03:00
|
4:00 AM equals 04:00
|
5:00 AM equals 05:00
|
6:00 AM equals 06:00
|
7:00 AM equals 07:00
|
8:00 AM equals 08:00
|
9:00 AM equals 09:00
|
10:00 AM equals 10:00
|
11:00 AM equals 11:00
|
12:00 PM equals 12:00
|
1:00 PM equals 13:00
|
2:00 PM equals 14:00
|
3:00 PM equals 15:00
|
4:00 PM equals 16:00
|
5:00 PM equals 17:00
|
6:00 PM equals 18:00
|
7:00 PM equals 19:00
|
8:00 PM equals 20:00
|
9:00 PM equals 21:00
|
10:00 PM equals 22:00
|
11:00 PM equals 23:00
|
12:00 AM equals 00:00
|
(UTC/GMT) Coordinated Universal Time
See GMT Time Here: http://www.worldtimeserver.com/current_time_in_UTC.aspx
Coordinated Universal Time (UTC) is the primary time standard by which the world regulates clocks and time. It is one of several closely related successors to Greenwich Mean Time (GMT). For most purposes, UTC is synonymous with GMT, but GMT is no longer precisely defined by the scientific community.
Coordinated Universal Time (UTC) is the primary time standard by which the world regulates clocks and time. It is one of several closely related successors to Greenwich Mean Time (GMT). For most purposes, UTC is synonymous with GMT, but GMT is no longer precisely defined by the scientific community.
Time zones around the world are expressed as positive or negative offsets from UTC, as in the list of time zones by UTC offset.
UTC is the time standard used for many internet and World Wide Web standards. The Network Time Protocol, designed to synchronise the clocks of computers over the Internet, encodes times using the UTC system.[4]
Computer servers, online services and other entities that rely on having a universally accepted time use UTC as it is more specific than GMT. If only limited precision is needed, clients can obtain the current UTC time from a number of official Internet UTC servers. For sub-microsecond precision, clients can obtain the time from satellite signals.
UTC is also the time standard used in aviation[5], e.g., for flight plans and air traffic control clearances. Weather forecasts and maps all use UTC to avoid confusion about time zones and daylight saving time.
Thursday, 3 January 2013
Get first and last date of the previous month in java
Calendar aCalendar = Calendar.getInstance();
aCalendar.set(Calendar.DATE, 1);
aCalendar.add(Calendar.DAY_OF_MONTH, -1);
Date lastDateOfPreviousMonth = aCalendar.getTime();
aCalendar.set(Calendar.DATE, 1);
Date firstDateOfPreviousMonth = aCalendar.getTime();
Wednesday, 26 December 2012
Why wait(), notify() and notifyAll() methods have been defined in the Object class?
Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.
wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.
As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.
Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.
The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.
Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).
Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.
Read More...
wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.
As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.
Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.
The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.
Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).
Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.
Thursday, 20 December 2012
Can a class (whether an inner or outer class) be declared static?
In order to understand the use of the
A top-level class is by definition already top-level, so there is no point in declaring it static; it is an error to do so. The compiler will detect and report this error.
1. Anonymous. Anonymous classes are declared and instantiated within the same statement. They do not have names, and they can be instantiated only once.
The following is an example of an anonymous class:
Because an anonymous class doesn't have a normal class declaration where it's possible to use
2. Local. Local classes are the same as local variables, in the sense that they're created and used inside a block. Once you declare a class within a block, it can be instantiated as many times as you wish within that block. Like local variables, local classes aren't allowed to be declared public, protected, private, or static.
Here's a code example:
3. Member. Member classes are defined within the body of a class. You can use member classes anywhere within the body of the containing class. You declare member classes when you want to use variables and methods of the containing class without explicit delegation.
The member class is the only class that you can declare static. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared. If you want to remove this restriction, you declare the member class a static class.
When you declare a member class with a
4. Nested top-level. A nested top-level class is a member classes with a
Read More...
static keyword in class declaration, we need to understand the class declaration itself. You can declare two kinds of classes: top-level classes and inner classes. Top-level classes
You declare a top-level class at the top level as a member of a package. Each top-level class corresponds to its own java file sporting the same name as the class name.A top-level class is by definition already top-level, so there is no point in declaring it static; it is an error to do so. The compiler will detect and report this error.
Inner classes
You define an inner class within a top-level class. Depending on how it is defined, an inner class can be one of the following four types:1. Anonymous. Anonymous classes are declared and instantiated within the same statement. They do not have names, and they can be instantiated only once.
The following is an example of an anonymous class:
okButton.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
Because an anonymous class doesn't have a normal class declaration where it's possible to use
static, it cannot be declared static. 2. Local. Local classes are the same as local variables, in the sense that they're created and used inside a block. Once you declare a class within a block, it can be instantiated as many times as you wish within that block. Like local variables, local classes aren't allowed to be declared public, protected, private, or static.
Here's a code example:
//some code block .......{
class ListListener implements ItemListener {
List list;
public ListListener(List l) {
list = l;
}
public void itemStateChanged(ItemEvent e) {
String s = l.getItemSelected();
doSomething(s);
}
}
List list1 = new List();
list list2 = new List();
list1.addItemListener(new ListListener(list1));
list2.addItemListener(new ListListener(list2));
}
3. Member. Member classes are defined within the body of a class. You can use member classes anywhere within the body of the containing class. You declare member classes when you want to use variables and methods of the containing class without explicit delegation.
The member class is the only class that you can declare static. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared. If you want to remove this restriction, you declare the member class a static class.
When you declare a member class with a
static modifier, it becomes a nested top-level class and can be used as a normal top-level class as explained above. 4. Nested top-level. A nested top-level class is a member classes with a
static modifier. A nested top-level class is just like any other top-level class except that it is declared within another class or interface. Nested top-level classes are typically used as a convenient way to group related classes without creating a new package.
Monday, 17 December 2012
Password At Command Prompt - console.readPassword()
import java.io.*;
class Abc
{
public static void main(String args[])
{
System.out.println("hello");
Console console=System.console();
console.printf("Enter Password\n");
char a[]=console.readPassword();
for(int i=0;i<a.length;i++)
{
console.printf("%c",a[i]);
}
}
}
class Abc
{
public static void main(String args[])
{
System.out.println("hello");
Console console=System.console();
console.printf("Enter Password\n");
char a[]=console.readPassword();
for(int i=0;i<a.length;i++)
{
console.printf("%c",a[i]);
}
}
}
Saturday, 15 December 2012
Does 'static' cause Memory Leak in Java?
Does 'static' cause Memory Leak in Java?
What's memory leak? In simple terms, it's unused but referenced (somehow because the programmer probably unintentionally forgot to remove the references once the use of the object was over) part of the memory. Before we start discussing if 'static' can cause memory leak in Java, let me assure you that whatever you've read about Garbage Collectors in Java, is still valid and it certainly takes care of most (almost all) of the memory allocation/reclaimation of Java objects. But, that alone doesn't remove the possibility of the presence of memory leak in a Java program - just for example, you might not only be using only Java objects in your Java program. Putting it differently, what if you have used some native objects and forgot to reclaim the memory explicitly because that's anyway not going to be taken care by the GC (which takes care of heap memory management only)... right?
Now that we agree with the possibility of a Java program having potential memory leaks, let's see if using 'static' can also be one of the potential reasons for memory leaks in Java.
How to find if your Java program contains Memory Leaks?
Well... the programmer should have kept their eyes open while development itself. Once the app is ready, one may like to use Profilers (available from many vendors) to analyze the object graphs.
If your Java app is usually crashing with 'OutOfMemoryError' after executing for a while then it should ring an alarm for the possibility of memory leaks in your app. Though, this doesn't necessarily mean your app is having memory leaks, it might be possible that the allocated heap space is not enough for the proper functioning of your app.
Does 'static' cause memory leak in Java?
'static' can't straightway be blamed for causing memory leaks. But, if the programmer has not well thought the usage and has not taken care of the setting the references to 'null' explicitly after using the static objects then they can definitely cause memory leaks. Let's see how.
As you know 'static' members will by default live for the entire life of an app unless they are explicitly set to 'null'. So, always make it a point to nullify the references as soon as you reach at a point in your code where the use of the static member is over. For example: suppose you have created a 'Statement' object from a DB Connection and the connection is a pooled one. Now as you know calling close()method on a pooled connection will not actually close the connection instead it will return the Connection object to the pool to be re-used. So, in such a case unless you explicitly close the 'Statement' object, it would keep consuming precious memory space for no real use. Just think the scenario where you have declared the 'Statement' object as a static member, it'll be maintained in the memory for the entire life time of the app even when the control is out of the scope. It's just a sample scenario and many of you might never have used 'Statement' object in such an irresponsible manner. It's just an attempt to show how the 'static' can be misused to cause memory leaks in Java.
Not that if your Statement object is non-static you should reply on the out-of-scope nullification (i.e., as soon as control is out of scope the local objects would be marked for re-claimation) as in case you still have a significant amount of code (in terms of time/space) after using the Statement last and before reaching the end of the local scope, it would be a sheer wastage of memory if you don't explicitly nullify the 'Statement' after its use is over. Such a scenario should also be thought of as memory leaks only and one should always make sure the nullification of resources is as close to their last usage as possible.
Therefore, in summary we can say that one should/must :-
What's memory leak? In simple terms, it's unused but referenced (somehow because the programmer probably unintentionally forgot to remove the references once the use of the object was over) part of the memory. Before we start discussing if 'static' can cause memory leak in Java, let me assure you that whatever you've read about Garbage Collectors in Java, is still valid and it certainly takes care of most (almost all) of the memory allocation/reclaimation of Java objects. But, that alone doesn't remove the possibility of the presence of memory leak in a Java program - just for example, you might not only be using only Java objects in your Java program. Putting it differently, what if you have used some native objects and forgot to reclaim the memory explicitly because that's anyway not going to be taken care by the GC (which takes care of heap memory management only)... right?
Now that we agree with the possibility of a Java program having potential memory leaks, let's see if using 'static' can also be one of the potential reasons for memory leaks in Java.
How to find if your Java program contains Memory Leaks?
Well... the programmer should have kept their eyes open while development itself. Once the app is ready, one may like to use Profilers (available from many vendors) to analyze the object graphs.
If your Java app is usually crashing with 'OutOfMemoryError' after executing for a while then it should ring an alarm for the possibility of memory leaks in your app. Though, this doesn't necessarily mean your app is having memory leaks, it might be possible that the allocated heap space is not enough for the proper functioning of your app.
Does 'static' cause memory leak in Java?
'static' can't straightway be blamed for causing memory leaks. But, if the programmer has not well thought the usage and has not taken care of the setting the references to 'null' explicitly after using the static objects then they can definitely cause memory leaks. Let's see how.
As you know 'static' members will by default live for the entire life of an app unless they are explicitly set to 'null'. So, always make it a point to nullify the references as soon as you reach at a point in your code where the use of the static member is over. For example: suppose you have created a 'Statement' object from a DB Connection and the connection is a pooled one. Now as you know calling close()method on a pooled connection will not actually close the connection instead it will return the Connection object to the pool to be re-used. So, in such a case unless you explicitly close the 'Statement' object, it would keep consuming precious memory space for no real use. Just think the scenario where you have declared the 'Statement' object as a static member, it'll be maintained in the memory for the entire life time of the app even when the control is out of the scope. It's just a sample scenario and many of you might never have used 'Statement' object in such an irresponsible manner. It's just an attempt to show how the 'static' can be misused to cause memory leaks in Java.
Not that if your Statement object is non-static you should reply on the out-of-scope nullification (i.e., as soon as control is out of scope the local objects would be marked for re-claimation) as in case you still have a significant amount of code (in terms of time/space) after using the Statement last and before reaching the end of the local scope, it would be a sheer wastage of memory if you don't explicitly nullify the 'Statement' after its use is over. Such a scenario should also be thought of as memory leaks only and one should always make sure the nullification of resources is as close to their last usage as possible.
Therefore, in summary we can say that one should/must :-
- always think if you really need to make this variable/member a 'static' one?
- always try to confine the scope of an object to restrict its usage only to the section it's actually needed
- always make a conscious effort to explicitly nullify objects once you finish using them (especially the large objects)
Friday, 7 December 2012
Create Jar File In JAVA
How to Make A Jar File In JAVA
Step 1: Consider a class
Step 2: Create a manifest file manifest.txt
Main-Class: AwtExample
Uses
Step 3: Create Jar File
Create a Jar file by adding “
Open cmd and type: You can issue following command to create a “
jar -cvfm AwtExample.jar manifest.txt com/*.class
Step 1: Consider a class
AwtExample.java
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class AwtExample {
public static void main(String[] args) {
Frame f = new Frame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new Label("This JAR file is executable!"));
f.setSize(500, 500);
f.setVisible(true);
}
}
Step 2: Create a manifest file manifest.txt
c:\test\classes\manifest.txt
c:\test\classes\com\AwtExample.class
inside manifest file:Main-Class: AwtExample
Uses
Main-Class as the entry point of this Jar file, when you double click on this Jar file, the “AwtExample.class” main() method will be launched.Step 3: Create Jar File
Create a Jar file by adding “
AwtExample.class” and “manifest.txt” files together.jar -cvfm AwtExample.jar manifest.txt com/awt/*.class
Open cmd and type: You can issue following command to create a “
AwtExample.jar.jar -cvfm AwtExample.jar manifest.txt com/*.class
main() method is other than public?
Why main method is public static in Java
What is main method in Java?
Now come to the main point "Why main method is static in Java", there are quite a few reasons around but here are few reasons which make sense to me:
What is main method in Java?
Main method in Java is entry point for any core Java Program.Remember We are not talking about Servlet, MIDlet or any other container managed Java program where life cycle methods are provided to control the execution. In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[]) method in that class and if it doesn't find that method it throws error NoSuchMethodError:main and terminates.
Signature of main method in Java
Main method has to strictly follow its syntax; other wise JVM will not be able to locate it and your program will not run. Here is the exact signature of main method
public static void main(String args[])
This signature is classic signature and there from start of Java but with introduction of variable argument or varargs in Java5 you can also declare main method in Java using varargs syntax as shown in below example:
public static void main(String... args)
Remember varargs version of java main method will only work in Java 1.5 or later version. Apart from public, static and void there are certain keywords like final, synchronized and strictfp which are permitted in signature of java main method.
Why main method is static in Java
Now come to the main point "Why main method is static in Java", there are quite a few reasons around but here are few reasons which make sense to me:
1. Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.
2. Since C and C++ also has similar main method which serves as entry point for program execution, following that convention will only help Java.
3. If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
4. Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:
public class JavaClass{
protected JavaClass(int x){}
public void main(String[] args){
}
}
Should the JVM call new JavaClass(int)? What should it pass for x?
If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.
There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why main is static.
Why main mehtod is public in Java
Java specifies several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessible from outside of that class. Since main method is public in
Java, JVM can easily access and execute it.
Why main method is void in Java
Since main method in Java is not supposed to return any value, its made void which simply means main is not returning anything.
Summary:
1. Main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.
2. JVM throws NoSuchMethodException:main if it doesn't find main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.
3. Main method is entry point for any Core Java program. Execution starts from main method.
4. Main method is run by a special thread called "main" thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from main method is running.
5. When you see "Exception in Thread main” e.g.
Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.
6. You can declare main method using varargs syntax from Java 1.5 onwards e.g.
public static void main(String... args)
7. Apart from static, void and public you can use final, synchronized and strictfp modifier in signature of main method in Java.
8. Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature specified above.
9. You can use throws clause in signature of main method and can throw any checked or unchecked Exception.
10. Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.
modeled on the Sun Certification for JavaTM 6 Programmer exam
Mock exam 1 for SCJP 6
The sample test is modeled on the Sun Certification for JavaTM 6 Programmer exam. The test has 50 questions and needs to be executed in 2 hours. The real exam may be a little tougher than this. You need to score 35 correct answers out of 60 to clear the real exam in 180 minutes. Please let us know at ngabrani At hotmail dot com if you find any issues with the test.
- Which declaration of the main method below would allow a class to be started as a standalone program. Select the one correct answer.
- public static int main(char args[])
- public static void main(String args[])
- public static void MAIN(String args[])
- public static void main(String args)
- public static void main(char args[])
- What all gets printed when the following code is compiled and run? Select the three correct answers.
- i=0 j=0
- i=0 j=1
- i=0 j=2
- i=1 j=0
- i=1 j=1
- i=1 j=2
- i=2 j=0
- i=2 j=1
- i=2 j=2
- What gets printed when the following code is compiled and run with the following command -
java test 2
Select the one correct answer. - test
- test -1
- 0
- 1
- 2
- In Java technology what expression can be used to represent number of elements in an array named arr ?
- How would the number 5 be represented in hex using up-to four characters.
- Which of the following is a Java keyword. Select the four correct answers.
- extern
- synchronized
- volatile
- friend
- friendly
- transient
- this
- then
- Is the following statement true or false. The constructor of a class must not have a return type.
- true
- false
- What is the number of bytes used by Java primitive long. Select the one correct answer.
- The number of bytes is compiler dependent.
- 2
- 4
- 8
- 64
- What is returned when the method substring(2, 4) is invoked on the string "example"? Include the answer in quotes as the result is of type String.
- Which of the following is correct? Select the two correct answers.
- The native keyword indicates that the method is implemented in another language like C/C++.
- The only statements that can appear before an import statement in a Java file are comments.
- The method definitions inside interfaces are public and abstract. They cannot be private or protected.
- A class constructor may have public or protected keyword before them, nothing else.
- What is the result of evaluating the expression 14 ^ 23. Select the one correct answer.
- 25
- 37
- 6
- 31
- 17
- 9
- 24
- Which of the following are true. Select the one correct answers.
- && operator is used for short-circuited logical AND.
- ~ operator is the bit-wise XOR operator.
- | operator is used to perform bitwise OR and also short-circuited logical OR.
- The unsigned right shift operator in Java is >>.
- Name the access modifier which when used with a method, makes it available to all the classes in the same package and to all the subclasses of the class.
- Which of the following is true. Select the two correct answers.
- A class that is abstract may not be instantiated.
- The final keyword indicates that the body of a method is to be found elsewhere. The code is written in non-Java language, typically in C/C++.
- A static variable indicates there is only one copy of that variable.
- A method defined as private indicates that it is accessible to all other classes in the same package.
- What all gets printed when the following program is compiled and run. Select the two correct answers.
- 0
- 1
- 2
- 3
- What all gets printed when the following program is compiled and run. Select the one correct answer.
- 0
- 1
- 2
- The program does not compile because of statement "i=++i;"
- What all gets printed when the following gets compiled and run. Select the three correct answers.
public class test { public static void main(String args[]) { int i=1, j=1; try { i++; j--; if(i/j > 1) i++; } catch(ArithmeticException e) { System.out.println(0); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(1); } catch(Exception e) { System.out.println(2); } finally { System.out.println(3); } System.out.println(4); } }- 0
- 1
- 2
- 3
- 4
- What all gets printed when the following gets compiled and run. Select the two correct answers.
- 0
- 1
- 2
- 3
- 4
- What all gets printed when the following gets compiled and run. Select the two correct answers.
- 1
- 2
- 3
- 4
- What all gets printed when the following gets compiled and run. Select the two correct answers.
- 1
- 2
- 3
- 4
- Which of the following are legal array declarations. Select the three correct answers.
- int i[5][];
- int i[][];
- int []i[];
- int i[5][5];
- int[][] a;
- What is the range of values that can be specified for an int. Select the one correct answer.
- The range of values is compiler dependent.
- -231 to 231 - 1
- -231-1 to 231
- -215 to 215 - 1
- -215-1 to 215
- How can you ensure that the memory allocated by an object is freed. Select the one correct answer.
- By invoking the free method on the object.
- By calling system.gc() method.
- By setting all references to the object to new values (say null).
- Garbage collection cannot be forced. The programmer cannot force the JVM to free the memory used by an object.
- What gets printed when the following code is compiled and run. Select the one correct answer.
- 0
- 1
- 2
- -1
- Which of these is a legal definition of a method named m assuming it throws IOException, and returns void. Also assume that the method does not take any arguments. Select the one correct answer.
- void m() throws IOException{}
- void m() throw IOException{}
- void m(void) throws IOException{}
- m() throws IOException{}
- void m() {} throws IOException
- Which of the following are legal identifier names in Java. Select the two correct answers.
- %abcd
- $abcd
- 1abcd
- package
- _a_long_name
- At what stage in the following method does the object initially referenced by s becomes available for garbage collection. Select the one correct answer.
- Before statement labeled 1
- Before statement labeled 2
- Before statement labeled 3
- Before statement labeled 4
- Never.
String s = new String("xyz");
Assuming the above declaration, which of the following statements would compile. Select the one correct answer.- s = 2 * s;
- int i = s[0];
- s = s + s;
- s = s >> 2;
- None of the above.
- Which of the following statements related to Garbage Collection are correct. Select the two correct answers.
- It is possible for a program to free memory at a given time.
- Garbage Collection feature of Java ensures that the program never runs out of memory.
- It is possible for a program to make an object available for Garbage Collection.
- The finalize method of an object is invoked before garbage collection is performed on the object.
- If a base class has a method defined as
void method() { }
Which of the following are legal prototypes in a derived class of this class. Select the two correct answers. - void method() { }
- int method() { return 0;}
- void method(int i) { }
- private void method() { }
- In which all cases does an exception gets generated. Select the two correct answers.
- if((i == 0) || (j/i == 1))
- if((i == 0) | (j/i == 1))
- if((i != 0) && (j/i == 1))
- if((i != 0) & (j/i == 1))
- Which of the following statements are true. Select the two correct answers.
- The wait method defined in the Thread class, can be used to convert a thread from Running state to Waiting state.
- The wait(), notify(), and notifyAll() methods must be executed in synchronized code.
- The notify() and notifyAll() methods can be used to signal and move waiting threads to ready-to-run state.
- The Thread class is an abstract class.
- Which keyword when applied on a method indicates that only one thread should execute the method at a time. Select the one correct answer.
- transient
- volatile
- synchronized
- native
- static
- final
- What is the name of the Collection interface used to represent elements in a sequence (in a particular order). Select the one correct answer.
- Collection
- Set
- List
- Map
- Which of these classes implement the Collection interface SortedMap. Select the one correct answers.
- HashMap
- Hashtable
- TreeMap
- HashSet
- TreeSet
- Vector
- Which of the following are true about interfaces. Select the two correct answers.
- Methods declared in interfaces are implicitly private.
- Variables declared in interfaces are implicitly public, static, and final.
- An interface can extend any number of interfaces.
- The keyword implements indicate that an interface inherits from another.
- Assume that class A extends class B, which extends class C. Also all the three classes implement the method test(). How can a method in a class A invoke the test() method defined in class C (without creating a new instance of class C). Select the one correct answer.
- test();
- super.test();
- super.super.test();
- ::test();
- C.test();
- It is not possible to invoke test() method defined in C from a method in A.
- What is the return type of method round(double d) defined in Math class.
- What gets written on the screen when the following program is compiled and run. Select the one right answer.
- 4
- 5
- 6
- 6.1
- 9
- Is the following statement true or false. As the toString method is defined in the Object class, System.out.println can be used to print any object.
- true
- false
- Which of these classes defined in java.io and used for file-handling are abstract. Select the two correct answers.
- InputStream
- PrintStream
- Reader
- FileInputStream
- FileWriter
- Name the collection interface used to represent collections that maintain unique elements.
- What is the result of compiling and running the following program.
- abc
- def
- abcabc
- abcdef
- defabc
- abcdefdef
- Select the one correct answer. The number of characters in an object of a class String is given by
- The member variable called size
- The member variable called length
- The method size() returns the number of characters.
- The method length() returns the number of characters.
- Select the one correct answer. Which method defined in Integer class can be used to convert an Integer object to primitive int type.
- valueOf
- intValue
- getInt
- getInteger
- Name the return type of method hashCode() defined in Object class, which is used to get the unique hash value of an Object.
- Which of the following are correct. Select the one correct answer.
- An import statement, if defined, must always be the first non-comment statement of the file.
- private members are accessible to all classes in the same package.
- An abstract class can be declared as final.
- Local variables cannot be declared as static.
- Name the keyword that makes a variable belong to a class, rather than being defined for each instance of the class. Select the one correct answer.
- static
- final
- abstract
- native
- volatile
- transient
- Which of these are core interfaces in the collection framework. Select the one correct answer.
- Tree
- Stack
- Queue
- Array
- LinkedList
- Map
- Which of these statements are true. Select the two correct answers.
- For each try block there must be at least one catch block defined.
- A try block may be followed by any number of finally blocks.
- A try block must be followed by at least one finally or catch block.
- If both catch and finally blocks are defined, catch block must precede the finally block.
public class xyz {
public static void main(String args[]) {
for(int i = 0; i < 2; i++) {
for(int j = 2; j>= 0; j--) {
if(i == j) break;
System.out.println("i=" + i + " j="+j);
}
}
}
}
public class test {
public static void main(String args[]) {
Integer intObj=Integer.valueOf(args[args.length-1]);
int i = intObj.intValue();
if(args.length > 1)
System.out.println(i);
if(args.length > 0)
System.out.println(i - 1);
else
System.out.println(i - 2);
}
}
public class test {
public static void main(String args[]) {
int i, j=1;
i = (j>1)?2:1;
switch(i) {
case 0: System.out.println(0); break;
case 1: System.out.println(1);
case 2: System.out.println(2); break;
case 3: System.out.println(3); break;
}
}
}
public class test {
public static void main(String args[]) {
int i=0, j=2;
do {
i=++i;
j--;
} while(j>0);
System.out.println(i);
}
}
public class test {
public static void main(String args[]) {
int i=1, j=1;
try {
i++;
j--;
if(i == j)
i++;
}
catch(ArithmeticException e) {
System.out.println(0);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(1);
}
catch(Exception e) {
System.out.println(2);
}
finally {
System.out.println(3);
}
System.out.println(4);
}
}
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = "abc";
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = new String("abc");
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
public class test {
public static void main(String args[]) {
int i = 1;
do {
i--;
} while (i > 2);
System.out.println(i);
}
}
void method X() {
String r = new String("abc");
String s = new String("abc");
r = r+1; //1
r = null; //2
s = s + r; //3
} //4
int i = 0, j = 1;
public class test {
public static void main(String args[]) {
int i;
float f = 2.3f;
double d = 2.7;
i = ((int)Math.ceil(f)) * ((int)Math.round(d));
System.out.println(i);
}
}
public class test {
public static void main(String args[]) {
String str1="abc";
String str2="def";
String str3=str1.concat(str2);
str1.concat(str2);
System.out.println(str1);
}
}
Answers to Sample Test 1
- b
- b, c, f
- d. Note that the program gets one command line argument - 2. args.length will get set to 1. So the condition if(args.length > 1) will fail, and the second check if(args.length > 0) will return true.
- arr.length
- Any of these is correct - 0x5, 0x05, 0X05, 0X5
- b, c, f, g
- a
- d
- "am"
- a, c. Please note that b is not correct. A package statement may appear before an import statement. A class constructor may be declared private also. Hence d is incorrect.
- a
- a
- protected
- a, c
- b, c
- c
- a, d, e
- d, e
- a, c
- b, c
- b, c, e
- b
- d
- a
- a
- b, e . The option c is incorrect because a Java identifier name cannot begin with a digit.
- d
- c
- c, d
- a, c
- b, d
- b, c
- c
- c
- c
- b, c
- f
- long
- e
- a
- a, c
- Set
- a
- d
- b
- int
- d
- a
- f
- c, d