-
General Knowledge
-
General Topics
- Abbreviations
- Books and Authors
- Famous Academies and Institutes
- First in India (Man)
- First in India (Women)
- Important Dates
- Famous Personalities
- Public Administration Science
- Astronomy
- Biology
- Botany
- Chemistry
- Physics
- Zoology
- Inventions and Scientists Geography
- Geographical Epithets India
- Geographical Epithets World
- Places Associated with Industries in India
- National Parks and Sanctuaries
- Towns on River Banks History
- Indian History and Culture
- Indian National Movement
- Indian Polity and Constitution
- Ancient Period in Indian History
- World History
- Governor General of India Culture
- Languages
- Indian Dance and Music
- Classical Dances of India
- Folk Dances in India and Tribal Dances in India
- Famous Dancers, Instrumentalists, Vocalists in India World
- First in the World
- Parliament Names
- United Nation Organizations (UNO)
- World's Famous News Agencies
- World Industries
- National Emblems
- Countries and Alternative Names
- Countries and Capitals
- View More topics...
- General Aptitude
- Problems on Ages
- Alligation and Mixture
- Area
- Arithmetic Progression
- Average
- Banker's Discount
- Boats and Streams
- Calendar
- Chain Rule
- Clock
- Compound Interest
- Decimal Fraction
- Height and Distance
- Logarithms
- Mensurations
- Numbers
- Odd Man Out and Series
- Partnership and Share
- Percentage
- Permutation and Combination
- Pipes and Cisterns
- Probability
- Problems on H.C.F and L.C.M
- Problems on Numbers
- Problems on Trains
- Profit and Loss
- Races and Games
- Ratio and Proportion
- Simple Interest
- Simplification
- Stocks and Shares
- Surds and Indices
- Time and Distance
- Time and Work
- True Discount
- Volume & Surface Areas
- General English
- Antonyms
- Synonyms
- Vocabulary Test
- One Word Substitution
- Sentence Completion
- Sentence Improvement
- Idioms & Phrases
- Homonyms
- Word Formation
- Active & Passive Voice
- Direct and Indirect Speech
- Spotting Errors
- Double Synonyms
- Choose the Appropriate Filter
- Spelling Test
- Transformation
- Reconstruction of Sentence
- Chooose the Correct or Incorrect Sentence
- Networking
- Interview Questions
-
Programming
- .NET
- Java
- ASP.NET
- C++
- Perl
- Python
- Ruby and Rails
- Struts
- Core Java
- Hibernate Database
- DB2
- MS SQL Server
- MySQL
- Oracle
- SQL
- DBMS
- Data Warehousing
- Data structures and Algorithms Cisco
- CCNA
- CCNP Routing
- CCNP Switching
- Internetworking
- Border Gateway Protocol Windows
- MCSE
- Exchange Server
- Windows Server 2008
- DNS & Active Directory
- Firewall Questions Linux
- Unix
- Linux Server Administrator
- Linux System Administrator
- Linux File Manipulation
- Database
- Home
- Online-Quiz
- Programming
- Java Online Quiz
Instructions
- Total Questions 20
- Each question carry 1 mark
- Must answer all the questions (otherwise report card will not be generated)
- If you dont want to take a test, simply click the check answers button and view all the answers with explanations
- Do Not Refresh the Page
- No Time Limit
- Good Luck :)
You Scored % - /
Correct Answers :
[A, C, D]
Explanation :
Option (a) is correct. A package enables you to create a namespace to
group related classes and interfaces together.
Option (b) is incorrect. A base class overloads its base class method, as required.
Making derived classes overload their base class methods doesn't make it an incorrect or inefficient design.
Options (c) and (d) are also correct. The functionality of your classes should be
exposed using the public methods. The private methods are called within the class in which they're defined. They usually work as helper methods.
class Wood {
public Wood() {
System.out.println("Wood");
}
{
System.out.println("Wood:init");
}
}
class Teak extends Wood {
{
System.out.println("Teak:init");
}
public Teak() {
System.out.println("Teak");
}
public static void main(String args[]) {
new Teak();
}
}
Correct Answers :
[A]
Explanation :
When a class is compiled, the contents of its initializer block are added
to its constructor, just before its own contents. For example, here's the decompiled
code for class Wood. As you can see, the contents of its initializer block are added to
its constructor:
class Wood
{
public Wood()
{
System.out.println("Wood:init");
System.out.println("Wood");
}
}
enum Keywords {
ASSERT(1.4), // line1
DO, IF, WHILE; // line2
double version = 1.0; // line3
Keywords() { // constructor 1
this.version = 1.0; // constructor 1
} // constructor 1
Keywords(double version) { // constructor 2
this.version = version; // constructor 2
} // constructor 2
public static void main(String args[]) {
Keywords[] keywords = Keywords.values();
for (Keywords val:keywords) System.out.println(val);
}
}
Correct Answers :
[E]
Explanation :
The code compiles successfully. An enum can define and use multiple constructors. The declaration of enum constants must follow the opening brace of the enum declaration. It can't follow the definition of variables or methods.
abstract class Foo {
abstract void run();
}
Which of the classes correctly subclass Foo? (Choose all that apply.)
Correct Answers :
[A, B]
Explanation :
When a class extends another class or implements an interface, the methods
in the derived class must be either valid overloaded or valid overridden methods.
Option (c) is incorrect. The concrete class Her extends Foo and implements Run.
To compile Her, it must implement run() with public access so that it implements
run() with default access in class Foo and run() with public access in interface Run:
class Her extends Foo implements Run {
public void run() {}
}
Because class Her in option (c) defines run() with default access, it fails to implement
public run() from interface Run and fails compilation.
Option (d) is incorrect. Method run() defined in class His and method run()
defined in class Foo don't form either valid overloaded or overridden methods.
public class Prim { // line 1
public static void main(String[] args) { // line 2
int num1 = 12; // line 3
float num2 = 17.8f; // line 4
boolean eJavaResult = true; // line 5
boolean returnVal = num1 >= 12 && num2 < 4.567 // line 6
|| eJavaResult == true;interface Online {
String course = "OCP";
int duration = 2;
}
class EJavaGuru implements Online {
String course = "OCA";
public static void main(String args[]) {
EJavaGuru ejg = new EJavaGuru();
System.out.print(ejg.course); // n1
System.out.print(EJavaGuru.duration); // n2
}
}
System.out.println(returnVal); // line 7
} // line 8
}
Correct Answers :
[D]
Explanation :
Class EJavaGuru defines an instance variable course. Interface Online
also defines a variable with the same name—course (which is implicitly static). Class
EJavaGuru implements Online. Using EJavaGuru's instanceName.course will refer to
its instance variable. Using Online.course will refer to the variable course from
Online. Using EJavaGuru.course will result in a compilation error. Code on line n1
compiles successfully and prints OCA.
Because the variables defined in an interface are implicitly static and final, the variable
duration can be accessed as EJavaGuru.duration. Code on line n2 compiles successfully
and prints 2.
However, a class can't define static and instance variables with the same name. The
following class won't compile:
class EJavaGuru {
String course;
static String course;
}
Correct Answers :
[D]
Explanation :
Option (a) is incorrect. java.lang.Object is the base class of all classes
in Java. Making class java.lang.Object extend another class can be extremely risky.
Adding a method with a particular signature can break code of some other class, if it
has defined a method with the same name (defaultValue()) but a different signature
that isn't compatible, forming invalid overloaded methods.
Option (b) is incorrect. Because the requirement expects an object of Switch-
Argument, adding just method defaultValue() to class java.lang.Object won't serve
the purpose. To define a new type, we need to define SwitchArgument as either a class
or an interface.
Option (c) is incorrect. The requirement mentions that the object of Switch-
Argument, passed to a switch statement, should define method defaultValue().
Defining this method in interface SwitchArgument ensures that all classes that implement
interface SwitchArgument define method defaultValue().
Option (d) is correct. Creation of type SwitchArgument as an interface with
method defaultValue() provides a convenient option for all existing classes that
want to be passed as an argument to the switch statement. When the classes implement
the interface SwitchArgument, they'll be responsible for implementing method
defaultValue().
Correct Answers :
[A, C, D]
Explanation :
Though Java recommends using single letters like T or V to specify the
type, using the letters A and B is correct in option (a) as per the syntax.
Option (b) is incorrect because it uses invalid syntax to specify the type parameters
to a class. To specify multiple type parameters in a class declaration, you need to specify
a placeholder for only the type—not its variables.
Option (c) and (d) are correct. It’s acceptable to define the type parameters as a
subtype of an existing Java class. Though not recommended, it’s acceptable to use
type parameters with more than one letter: Aa and Bb.
Correct Answers :
[B, C]
Explanation :
Option (a) is incorrect. A raw type doesn’t include the generic information.
For the generic type List<T>, its raw type is List. You don’t need to define a raw type explicitly for any generic class or interface. You can access the raw type of all the
generic types.
Option (d) is incorrect. Like generic classes, generic interfaces can define any number of generic type parameters.
class Format1 {
public static void main(String... args) {
double num1 = 7.12345678;
int num2 = (int)8.12345678;
System.out.printf("num1=%f, num2=%2d, %b", num1, num2, num2);
}
}
Correct Answers :
[C]
Explanation :
By default, %f prints out six digits after the decimal number. It also
rounds off the last digit. So num1=%f outputs 7.123457 and not 7.123456.
Because the double literal 8.12345678 is explicitly casted to an int value, num2 contains
the integer part of the double literal 8.12345678, that is, 8. %2d sets the total
width of the output to 2 digits, padded with spaces and right-aligned by default. It outputs
a space preceding the digit 8.
For all non-Boolean primitive values, %b outputs true.
java Regex1 \d\d 761cars8 5dogs-total846
what is the output of the following code?
class Regex1 {
public static void main(String[] args) {
Pattern pattern = Pattern.compile(args[0]);
Matcher matcher = pattern.matcher(args[1]);
boolean found = false;
while(found = matcher.find()) {
System.out.println(matcher.group());
}
}
}
Correct Answers :
[B]
Explanation :
The last argument (5dogs-total846) is ignored when you use the following
command line because a space precedes it.
java -ea Regex1 \d\d 761cars8 5dogs-total846
When you pass the regex by using the command-line arguments, you don’t need to
escape the backslashes. It’s required only for literal string values.
\d\d will match two adjacent digits in the literal 761cars8—that is, 76. It won’t
match 61 because the digit 6 was already consumed in finding 76. By default, Java’s
regex engine won’t use characters that have already been consumed.
Correct Answers :
[A, B]
Explanation :
Option (c) is incorrect. If a resource couldn’t be initialized because of
an exception, it doesn’t exist. There’s no point in auto-closing such a resource.
Option (d) is incorrect. Subsequent calls to close() don’t throw an exception.
Option (e) is incorrect. The resources declared within a try-with-resources statement
are accessible only within the try block.
String s = "assert";
which of the following code options will compile successfully? (Choose all that apply.)
Correct Answers :
[B, C, D, E, F]
Explanation :
Option (a) is incorrect. For the longer form of the assert statement that uses two expressions, you can’t enclose both expressions within a single parentheses. Options (b) and (c) are correct. It’s optional to include the individual expressions used in the longer form within a single parentheses.
Options (d) and (e) are correct. The shorter form of the assert statement uses only one expression, which might or might not be included within parentheses.
Option (f) is correct. The semicolon placed after the condition s == "assert"
delimits the assert statement, and the statement following the semicolon is treated as
a separate statement. It’s equivalent to an assert statement using its shorter form followed
by another statement, as follows:
assert s == "assert" ;
s.replace('a', 'z');
Option (g) is incorrect because the first expression in an assert statement must return a boolean value. In this code, the first expression returns an object of class String.
Option (h) is incorrect because the second expression in an assert statement must return a value of any type. In this code, the return type of method println() is void.
Option (i) is incorrect. It incorrectly encloses both expressions of the assert statement within a single pair of parentheses. If parentheses were removed, it’s also an illegal usage of the long form because it uses an expression that doesn’t return a boolean value for its first expression and its second expression doesn’t return any value.
import java.io.*;
class Q1 {
public static void main(String args[]) throws IOException {
DataOutputStream dos = new DataOutputStream(
new FileOutputStream("contacts.txt"));
dos.writeDouble(999.999);
DataInputStream dis = new DataInputStream(
new FileInputStream("contacts.txt"));
System.out.println(dis.read());
System.out.println(dis.read());
dis.close();
dos.close();
}
}
Correct Answers :
[D]
Explanation :
dos.writeDouble(999.999) writes 8 bytes of data to the underlying stream, and dis.read() reads a single byte of data from the underlying stream, interprets it as an integer value, and outputs it. So the code neither prints 999.999 nor throws an EOFException.
import java.io.*;
class ReadFromConsole {
public static void main(String args[]) throws IOException {
Console console = System.console();
String name = "";
while (name.trim().equals("")) {
name = console.readLine("What is your name?\n");
console.printf(name);
}
}
}
Correct Answers :
[A, B, C]
Explanation :
Option (d) is incorrect because System.console() might return null, depending on how the JVM is invoked. A console isn’t available to a JVM if it’s started using another program or a background process, or if the underlying OS doesn’t support it. In such cases, console.readLine throws a NullPointerException.
|- MyDir
|- 8_1.java
|- 8_1.class
|- Hello.txt
which options when inserted at /* INSERT CODE HERE */will delete the file represented by the Path object path?
import java.nio.file.*;
class Q8_1 {
public static void main(String... args) throws Exception {
Path path = Paths.get("Hello.txt");
Files.delete(/* INSERT CODE HERE */);
}
}
Correct Answers :
[A, C]
Explanation :
Option (b) is incorrect. The call path.resolveSibling("Q8_1.class")
will resolve the path from file Q8_1.class against the parent directory of file Hello.txt.
Because these files exist in the same directory, a (valid) path to file Q8_1.class is
returned. So Files.delete() will not delete file Hello.txt, but Q8_1.class instead.
Option (d) will fail compilation. Method resolve() accepts either a Path or a
String, resolving it against the path on which it’s called.
class Q8_2 {
public static void main(String... args) {
Path path1 = FileSystems.getDefault().getPath("/main/sub/notes/
file.txt");
Path path2 = Paths.get("code/Hello.java");
System.out.println(path1.getRoot()+ ":" + path2.getRoot());
System.out.println(path1.getName(0) + ":" + path2.getName(0));
System.out.println(path1.subpath(1, 3) + ":" + path2.subpath(0,1));
}
}
Correct Answers :
[D]
Explanation :
The getRoot method returns the root of a path for an absolute path and
null for a relative path. Because "/main/sub/notes/file.txt" starts with a /, it's
considered an absolute path and getRoot will return / or \ depending on your underlying
OS (\ for Windows and / for UNIX).
Method getName() excludes the root of a path and returns the element of this
path, specified by the index parameter to this method. The element closest to the root
in the directory hierarchy has an index of 0 and the element farthest from the root
has an index of count-1 (where count is the total number of Path elements).
Method subpath() (small p) returns the subsequence of the name elements of a
Path, starting at the method parameter startIndex (inclusive) up to the name element
at endIndex (exclusive).
class PrepStatement {
public static void main(String[] args) {
try {
String query = "....."; //line1
Connection con = getConnection();
PreparedStatement statement =
con.prepareStatement(query);
System.out.println(
statement.executeUpdate());
}
catch (SQLException e) {
System.out.println(e);
}
}
}
Correct Answers :
[B,C,D]
Explanation :
You can’t use method executeUpdate() to execute a SQL SELECT query.
If you do, you’ll get a SQLException with a similar message:
java.sql.SQLException: Can not issue executeUpdate() for SELECTs
Similarly, you can’t execute data deletion and modification queries with method
executeQuery(). If you do so, you’ll get a SQLException:
java.sql.SQLException: Can not issue data manipulation statements with
executeQuery().
Correct Answers :
[B]
Explanation :
One of the goals of JDBC 4.1, which is shipped with Java 7, is to be consistent with SQL:2003. JDBC 3.0 supported SQL99 features that were widely supported by the industry. JDBC 4.1 is supporting major components of SQL:2003.
enum Seasons{SPRING,SUMMER}
class ETree extends Thread {
String name;
public ETree(String name) {this.name = name;}
public void run() {
for (Seasons season : Seasons.values())
System.out.print(name + "-" + season + " ");
}
public static void main(String args[]) {
ETree oak = new ETree("Oak"); oak.start();
ETree maple = new ETree("Maple"); maple.start();
}
}
Correct Answers :
[A, D, E, F]
Explanation :
Each thread instance oak and maple, when started, will output the values
of enum Seasons—that is, SPRING and SUMMER (always in this order). The order of the
elements returned by Seasons.values() isn’t random. The enum values are always
returned in the order in which they are defined.
You can’t guarantee whether thread oak completes or begins its execution before
or after thread maple.
The thread scheduler can start oak, make it print Oak-SPRING,
run maple so that it prints Maple-SPRING, return the control to oak, or run maple to
completion.
Whatever the sequence, the happens-before contract guarantees that
code in a thread executes in the order it’s defined. So the thread oak or maple can
never print the enum value SUMMER before the enum value SPRING.
public class EThread {
public static void main(String[] args) {
Thread bug = new Thread() {
public void run() {
System.out.print("check bugs");
}
};
Thread reportQA = new Thread(bug);
reportQA.run();
}
}
Correct Answers :
[B, F]
Explanation :
The following code creates an anonymous class that subclasses class
Thread. Its instance is referred by bug, a reference variable of type Thread.
Thread bug = new Thread() {
public void run() {
System.out.print("check bugs");
}
};
Because class Thread implements the Runnable interface, you can pass its instance as a
target object to instantiate another Thread instance, reportQA:
Thread reportQA = new Thread(bug);
The variable reportQA refers to an anonymous class instance that overrides its method
run(). So calling reportQA.run() executes the overridden method run() and prints
check bugs only once.
Option (f) is correct. Even though calling reportQA.run() doesn’t start a separate
thread of execution and reportQA.start() does, both will print check bugs once on
the system’s console.
|
|
||||||||||||||||||||||||||||