alarm
  
1h 50m
Q1 of 39
What is the output of the given code?    

public class Tester {
       public static void main(String[] args) {
             Base obj = new Derived();
             obj.method();
       }
}

class Base {
       public void method(int a) {
             System.out.println("Base Method");
       }
}

class Derived extends Base {
       public void method() {
             System.out.println("Derived Method");
       }
}
Compilation Error
Base Method
Derived Method
Runtime Exception
Q2 of 39
What is the output of the below code?

public class Tester {
       public static void main(String[] args) {
             Base obj = new Derived();
             obj.method(25);
       }
}

class Base {
       public static void method(int a) {
             System.out.println("Base Method");
       }
}

class Derived extends Base {
       public static void method(int a) {
             System.out.println("Derived Method");
       }
}
 

Base Method
Derived Method
Compilation Error
Runtime Exception
Q3 of 39
What is the output of the below code?

abstract class BaseAbsClass {
       public void method() {
             System.out.println("BaseAbsClass Method");
       }
       public abstract void method2();
}

class Derived extends BaseAbsClass {
       public void method2() {
             System.out.println("Derived method");
       }
}

public class Testing {
       public static void main(String[] args) {
             BaseAbsClass obj = new Derived();
             obj.method2();
       }
}
Derived method
Compilation Error: Cannot have non abstract method in an abstract class
Compilation Error: Cannot have a reference to Abstract class
BaseAbsClass Method
Q4 of 39
What is the output of the below code? 

interface MyInterface {
       void method1();
}

class MyImplementation implements MyInterface {
       void method1() {
             System.out.println("My Method");
       }
}

public class Testing1 {
       public static void main(String[] args) {
             MyInterface obj = new MyImplementation();
             obj.method1();
       }
}
My Method
Compilation Error: cannot reduce the visibility of inherited method
Compilation Error: cannot have non-public methods in MyInterface
Compilation Error: cannot have a reference of the interface
Q5 of 39
What is the output of the below code?

class Vehicle {
       Vehicle() {
             System.out.println("Vehicle is created");
       }
}

public class Bike5 extends Vehicle {
       Bike5() {
             super();
             System.out.println("Bike is created");
       }
       public static void main(String[] args) {
             Bike5 b = new Bike5();
       }
}
Vehicle is created            Bike is created
Vehicle is created  Vehicle is created  Bike is created
Bike  is created    Vehicle is created
Vehicle is created    Bike is created Vehicle is created
Q6 of 39
What is the output of the below code?

public class Tester1 {
       public static void main(String[] args) {
             String s1 = "Infosys";
             String s2 = "Infosys";
             if (s1 == s2) {
                    System.out.print("Equal");
             } else {
                    System.out.print(" UnEqual");
             }
             if (s1.equals(s2)) {
                    System.out.print(" Equal");
             } else {
                    System.out.print(" UnEqual");
             }
       }
}
Equal Unequal
Equal Equal
UnEqual Equal
UnEqual UnEqual
Q7 of 39
If a class's methods and variables are to be made accessible only to its sub classes in different packages, what is the suitable access specifier?

protected
default
public
private
Q8 of 39
Find the statements which are true with respect to method overriding

Method signature should vary (no of arguments and its type)

Method to be invoked is decided at runtime

Method to be invoked is decided based on the object

Method can be static and private

i, ii
ii, iii and iv
ii, iii
i, iii and iv
Q9 of 39
What is the result of attempting to compile and run the program?

public class StringTest {
       public static void main(String[] args) {
             String s1 = "A", s2 = "a", s3 = "b";
             s1.toLowerCase();
             s3.replace('b', 'a');
             System.out.print((s1.equals(s2)) + "," + (s2.equals(s3)));
       }
}
Prints: false,false
Prints: false,true
Prints: true,false
Prints: true,true
Q10 of 39
What is the result of attempting to compile and run the program?

public class InfyTest {
       public static void main(String[] args) {
             int x, y, z;
             System.out.println(x + y + z);
       }
}
 

Prints: null
Prints: 0
Run-time error, since x, y and, z is not initialized
Compile-time error, since x, y and, z is not initialized
Q11 of 39
Given:

package p1;
class A { }

package p2;
import p1.A;
class B extends A { }
What is the output?

class A & class B compiles
Both class A and B compile but class B shows some warnings
Compilation of class B fails
class B throws an exception
Q12 of 39
What is the output of the following code?

public class SuperClass {
       private void displayName() {
             System.out.println("Super Class");
       }
       public static void main(String[] args) {
             SuperClass superClass = new SubClass();
             superClass.displayName();
       }
}

public class SubClass extends SuperClass {
       private void displayName() {
             System.out.println("SubClass is a type of SuperClass");
       }
}
SubClass is a type of SuperClass
Super Class
Compilation Error
No error, but no output also
Q13 of 39
What is the output of the following code?

class Person{                      
    public Person(String name){  
           System.out.println(name);
  }
}

public class Student extends Person{
       public Student(){          //line 8            
              System.out.println("Student");
       }
       public static void main(String[] args) { // line 11 
             new Person("Bob");                
       }
}
BobStudent
Bob
The code will not compile due to line 8
The code will not compile due to line 11
Q14 of 39
What is the output of the following code?

abstract class Person1 {
    public final void display(){
         System.out.println("Display method in Person");
    }
 
    public static void main(String[] args){
         Person1 person = new Student1();        //line 6
         person.display();                     //line 7           
        }
}

public class Student1 extends Person1{
       public void display(){                  //line 11
             System.out.println("Display method in Student");
       }
}
Display method in Person
Display method in Student
Code will not compile because of line 7
Code will not compile because of line 11
Q15 of 39
What will happen if the following code is compiled and executed?

(Choose 2 options)

package com.mypack.demoOne;
public class Employee {
       int id = 1000;  
       protected String name = "Smith";
       public String role = "Software Engineer";
}

package com.mypack.demoTwo;
import com.mypack.demoOne.*;
public class Trainee {
       public static void main(String[] args) {
             Employee emp = new Employee();               //line 11 
             System.out.print(" "+ emp.id);               //line 12 
             System.out.print(" " + emp.name);            //line 13
             System.out.print(" "+ emp.role);             //line 14
       }
}
1000 Smith Software Engineer
Compilation error at line 11
Compilation error at line 12
Compilation error at line 13
Compilation error at line 14
Q16 of 39
Which of the following lines of code compile?

(Choose any 4 options)

int number = 1234;
float f1 = 1234.0;
float f2 = 1234;
double d3 = 1234.0;
long num = 1234;
Q17 of 39
What is the output of the following code?

class Employee {
   public void display() {
          System.out.print(" display ");
   }

   public void print(int age) {
          System.out.print(" Employee ");
   }
}

public class Trainee extends Employee {
   public void display(String name) { // line 2
          System.out.print(name);
   }
   public int print(int age) { // line 5
          System.out.print(" Trainee ");
          return age;
   }
   public static void main(String[] args) {
          Trainee trainee = new Trainee();
          trainee.display(); // line 10
          trainee.display("Bob"); // line 11
          trainee.print(10); // line 12
   }
}
display Bob Trainee
compile error at line 5
compile error at line 10
compile error at line 12
Q18 of 39
What is the output of the following code?

class Employee {
       public static void display() { // line 2
             System.out.print(" Employee ");
       }
}

public class Trainee extends Employee {
       public static void display() { // line 5
             System.out.print(" Trainee ");
       }
       public static void main(String[] args) {
             Employee employee = new Trainee();
             employee.display(); // line 9
       }
}
Trainee
Employee
compile error at line 5
compile error at line 9
Q19 of 39
What is the output of the following code?

abstract class Employee {
   private void display() {
          System.out.print(" Employee ");
   }
}

public class Trainee extends Employee {
   protected void display() { // line 5
         System.out.print(" Trainee ");
   }
   public static void main(String[] args) {
          Employee emp = new Trainee();
          emp.display(); // line 10
   }
}
Employee
Trainee
Compiler error at line 5
Compiler error at line 10
Q20 of 39
What is the result when the following code is compiled?

public class Test {
    public void method() {
        for(int i = 0; i < 3; i++) {
            System.out.print(i);
        }
        System.out.print(i);
    }
}
0123
123
Compilation error
Runtime error
Q21 of 39
How many objects are eligible for garbage collection in the below code?

public class Loan {
       public static void main(String[] arg) {
             Loan loan1 = new Loan();
             Loan loan2 = new Loan();
             Loan loan3 = new Loan();
             Loan loan4 = new Loan();        
             loan1=loan3;
             loan2=loan4;
             loan3=null;
       }
}
0
1
2
3
Q22 of 39
What is the output of the below code snippet?

import java.time.LocalDate;

public class DateDemo {

    public static void main(String[] args) {
        LocalDate date = LocalDate.parse("2019-03-07");
        LocalDate date1 = LocalDate.of(2019, 12, 07);
        System.out.println(date.getYear()+date1.getYear()
        +" , "+date.compareTo(date1)+" , "+date1.compareTo(date));
    }
}     
4038 , -9 , 9
Compilation Error
4038 , 9 , -9
4038 , 0 , 0
Q23 of 39
Select all possible options among the following:

Enums can be defined inside___________

(Choose 3 options)

An interface
A Class
A Static Context
A Method
Q24 of 39
Predict the output of the following code

public class VarargsTest {
       public static void main(String[] args) {
             displayRegn("Hockey"); // Line 1
             displayRegn("Kho-Kho", 1, 2, 3);
       }

       public static void displayRegn(String nameOfSport, int... iDs) {
             System.out.print(" Registration for " + nameOfSport + ":");
             for (int i = 0; i < iDs.length; i++) {
                    System.out.print(iDs[i] + " ");
             }
       }
}
 

Registration for Hockey: Registration for Kho-Kho: 1 2 3
Registration for Kho-Kho: 1 2 3
Compilation Error, missing parameters
Runtime Exception due to Line 1
Q25 of 39
Predict the output of the following code

public class VarargsTest {
             public static void main(String[] args) {
                       new VarargsTest().display(5,"Infosys");
                       new VarargsTest().display(4,"Infosys","Limited");
             }
    
            public void display(int b, String... strings) {
                       System.out.print(strings[strings.length-1]+" ");
       }
}
 

Infosys Limited
Infosys Infosys Limited
Infosys
Infosys LimitedInfosys
Q26 of 39
Given the enum and the Java class

public enum Day {
       SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7);
       private int value;
       private Day(int value) {
             this.value = value;
       }

       public int getValue() {
             return this.value;
       }
}
public class TestEnum {
       public static void main(String[] args) {
             for(Day day:Day.values()) {
                    // Line 1
            }
       }
}
What should be placed at line 1 to get the output as shown below?

SUNDAY-MONDAY-TUESDAY-WEDNESDAY-THURSDAY-FRIDAY-SATURDAY-

Not possible, the days will be displayed with their values only
System.out.print(day.getValue()+"-");
System.out.print(day.name ()+"-");
System.out.print(day.getName()+"-");
Q27 of 39
Which of the following is true with respect to StringBuilder in Java?

(Choose 2 options)

StringBuilder is non-synchronized, not thread safe
StringBuilder is synchronized, thread safe
StringBuilder is less efficient
StringBuilder is more efficient
Q28 of 39
Which is the correct way of comparing the contents of the below strings?

String firstString = "String";
StringBuilder secondString = new StringBuilder("String");
 

firstString == secondString
firstString.contains(secondString)
secondString.equals(firstString)
firstString.equals(secondString)
Q29 of 39
Which of the following statements are correct advantages of an immutable class?

Immutable objects are simple
Immutable classes are thread-safe, they require no synchronization
only a is correct
Only b is correct
Both a and b are correct
Both a and b are incorrect
Q30 of 39
import java.util.*;

public class SetImpl {
	public static void main(String[] args) {
		Set<String> set=new TreeSet<String>();
		set.add("Infosys");
		set.add("Google");
		set.add("IBM"); 
	    for(String s:set){
	    	 System.out.print(" "+s);
    	         set.clear();
            }
	}
}
What is the output?

IBM
Runtime Exception
No output
Google
Q31 of 39
import java.util.*;

public class ListImpl {
	public static void main(String[] args) {
		List<String> al = new ArrayList<String>();
		al.add("infosys");
		al.add("google");
		al.add("ibm");
		al.add("Amazon");
		for (int j = 0; j < al.size(); j++) {
			al.remove(j);
			if (al.get(j++).equals("google")) {
				al.add("Oracle");
			}
		}
		System.out.println(al);
	}
}
What is the output?

[google, Oracle, ibm]
[google, ibm, Oracle]
[google, Amazon, Oracle]
Runtime Exception
Q32 of 39
import java.util.*;

public class MapDemoCheck {
	public static void main(String[] args) { 
		Map<Integer, String> map = new TreeMap<Integer, String>();
		map.put(2, "A");
		map.put(1, "B");
		map.put(3, "C"); 
		map.put(null,"E");  //1
		map.put(4,null);    //2
		map.put(1,"D");     //3
		Collection <String> collection = map.values();
		for(String element : collection){
			System.out.println(element);
		}
	}
}
What is the output?

Compile time error, TreeMap cannot contain null as a value as in line 2
Compile time error, TreeMap cannot have duplicate value for a key as in line 3
Run time error, TreeMap cannot contain null as key as in line 1
Will run successfully and map will contain 4 elements
Q33 of 39
Which among the following is true with respect to the below code?

package generic;
import java.util.ArrayList;
import java.util.List;

public class MyListGeneric<T extends Number> {
    private List<T> values = new ArrayList<>();
	
    public void add(T value) {
        values.add(value);
        System.out.println(values);
    }
    public void remove(T value) {
        values.remove(value);
    }
    public T get(int index) {
        return values.get(index);
    }
	
	public static void main(String[] args) {
		MyListGeneric<Float> myList = new MyListGeneric<Float>();
		myList.add(98.7f);
		myList.add(1009);
	}
}
The code will lead to a compilation error in the line "myList.add(1009);"
The code "myList.add(1009);", if replaced with "myList.add(new Integer(1009));", works fine without compilation error
Integer types are subtypes of Number type specified in the MyListGeneric class implementation, hence the program works fine without any errors
The int value 1009 will be internally converted to float and will be added to myList, hence the program works fine without any errors
Q34 of 39
What will be the output of the below code?

public class Test {
	public static void main(String[] args) {
		try {
			System.out.print("In try ");
			return;
		}
		finally {
			System.out.print("In finally ");
		}
		System.out.print("Outside block "); 
	}
}
Compilation error
In try In finally
In try In finally Outside block
Runtime error
Q35 of 39
import java.util.*;

class Person{
	String name;
	Person(String name){
		this.name=name;
	}
	public boolean equals(Object ob){
		return ((Person)ob).name==this.name;
	}
	
	public int hashCode(){
		return name.length();
	}
}
public class MapImpl {
	public static void main(String[] args) {
		Map<Person,String> map=new HashMap<Person,String>(); 
		map.put(new Person("jack"),"sendSalesReport");
		map.put(new Person("jack"),"sendAuditReport");
		map.put(new Person("mady"),"sendInventoryReport");
		
		System.out.println(map.size());
	}
} 

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

    public static void main(String[] args) {
        hello();
    }
}

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.