Sei sulla pagina 1di 33

Java Basics

• Brief History;
1. Java was originally called “Oak”.
2. Java was meant to be a programming language specifically for appliances and various
small devices. Like Set-Top Boxes and Televisions.

3. Java original specification is owned by Sun Microsystems.


4. Java applications run on a virtual machine environment that:
▪ Isolates the underlying platform
▪ Achieves portability and performance
▪ Provides security
5. Java source code is written as plain text files (.java) that are compiled as platform
independent bytecodes (.class)
6. Java byte-codes are interpreted and executed by the virtual machine that passes the
instructions to the
actual platform.
7. Java Architecture:
8. Java Development Kit (JDK):
▪ JDK is a set of software, tools and libraries that need to be installed in order to start
writing and compiling Java applications
▪ It installs the virtual machine (runtime environment) needed in order to execute Java
applications on the platform
▪ The virtual machine can be downloaded separately from the JDK as a JRE (Java
Runtime Environment) download.
9. Integrated Development Environment (IDE):
▪ Java source files are in text format and can be written using any text editor
▪ For greater productivity, an Integrated Development Environment (IDE) is highly
recommended. An IDE: ▪ Provides you with a set of tools that assist in developing,
testing, and debugging Java applications.
▪ Popular IDEs are:
▪ Eclipse
▪ IntelliJ
▪ NetBeans

10.Main Method in Java:


▪ The main method acts as the entry point for any Java application.
▪ Java does not allow any code to be written outside a class. Consider a class is the
basic

building block of any Java application. So whatever code we write, has to be written
inside a class including the main method as well
▪ For the main method to be executable, it has to be “public” “static” “void” “main”
followed by “String[] args”
11.Java Keywords:
▪ Java recognizes a set of keywords as part of the Java language
▪ Java keywords are used to support programming constructs, such as class
declaration, variable declaration, and control flow.
1. Abstract
2. Assert
3. Boolean
4. Break
5. Byte
6. Case
7. Catch
8. Char
9. Class
10.Continue
11.Default
12.Do
13.Double
14.Else
15.Extends
16.False
17.Final
18.Finally
19.Float
20.For
21.If
22.Implements
23.Import
24.Instanceof
25.Int
26.Interface
27.Long
28.Native
29.New
30.Null
31.Package
32.Private
33.Protected
34.Public
35.Return
36.Short
37.Static
38.Strictfp
39.Super
40.Switch
41.Synchronized
42.This
43.Throw
44.Throws
45.Transient
46.True
47.Try
48.Void
49.Volatile
50.While
51.Const
52.Goto

12.Primitive Data Types:

13.Data Types:
Youtube Video Link: https://www.youtube.com/watch?v=OmcFVHpb0v0
a. Primitive data type assigned value: Variable contains the Value.

b. Reference data type assigned value: Variable has the address or reference to
actual value
14.Variables:
a. Variable is the name for a location in memory.
b. There are 2 types of variable:
1. Primitive
2. Reference
c. Variable must have a ‘Data Type’.
d. Variable must have a ‘Name or Identifier’.
e. Variable name can start with a Letter/ Underscore (_)/Dollar sign ($).
f. Variable name cannot be any of the Keyword.
15. Type Conversion of primitive data types:
• Java implicitly cast to longer data types.
• When placing larger to smaller types, you must use explicit casting to mention
type name to which you are converting.

16. Parameter passing in java:


▪ Parameters in Java are Passed by Value

a. Passing Primitive Data Type by Value Arguments:


▪ A copy of the value is passed to the method.
▪ Any changes to the value exists only within the scope of the method.
▪ When the method returns, any changes to the value are lost. The original value
remains as it is.
▪ Primitive types are – Pass by Value in nature. So separate memory will be allocated
for x variable to copy the value passed to compute method. If we try to change the
value of X variable in compute, it won’t be visible to caller.
b. Passing Reference Data Type Arguments:
▪ A copy of the object’s reference’s value is being passed.
▪ The values of the object's fields can be changed inside the method, if they have the
proper access level.
▪ When the method returns, the passed-in reference still references the same object as
before. However, the changes in the object’s fields will be retained.

17. Problem with simple variables:


▪ One variable can hold only one value.
▪ The value may change over time, but at any given time, a variable holds a single
value.
▪ If you want to keep track of many values, you need many variables.
▪ All these variables need to have names.
▪ What if you need to keep track of hundreds or thousands of values?
▪ A better way to store multiple values of the same type is to use Arrays.

18. Arrays:
a. An Array is a named set of variables of the same type.
b. Each variable in an array is called an array element.
c. For ex: int[] arrayName = new int[8];
d. An array lets you associate one name with a fixed (but possibly large) number
of values.
e. All values must have the same type.
f. The values are distinguished by a numerical index between 0 and (array size
minus 1).
g. To index a single array element, use arrayName [index].
h. Indexed elements can be used just like simple variables
▪ You can access their values
▪ You can modify their values
i. An array index is sometimes called a SUBSCRIPT.
j. An array may hold any type of value.
k. All values in an array must be the same type
▪ For example, you can have:
▪ an array of integers
▪ an array of Strings
▪ an array of Person
▪ an array of arrays of String
▪ an array of Object

19. Declaring and Defining Arrays:


Declaration: int[] array; or int array[];
Definition: array = new int[10];

Declare and Define: int[] array = new int[10];


Or int[] array = {1,2,3,4,5,6,7}; // This can be only used in Array
Declaration.

20.An array’s size is not part of its type.

When you declare an array, you declare its type; you must not specify its size.
▪ Example: String names[ ];

When you define the array, you allocate space; you must specify its size.
▪ Example: names = new String[50];

This is true even when the two are combined.


▪ Example: String names[ ] = new String[50];

21.Array Assignment:
▪ When you assign an array value to an array variable, the types must be compatible.
▪ The following is not legal:
double dub[ ] = new int[10]; // illegal
▪ The following is legal:
int myArray[ ] = new int[10];
...and later in the program,
myArray = new int[500]; // legal!
▪ Legal because array size is not part of its type

22. Length of an array:


▪ Arrays are objects
▪ Every array has an instance constant, length, that tells how large the array is
▪ Example: for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
▪ Use of length is always preferred over using a constant such as 10.
▪ Strings have a length() method!
23.Initializing Arrays II
▪ There is a special syntax for giving initial values to the elements of arrays
▪ This syntax can be used in place of new type[size]
▪ It can only be used in an array declaration
▪ The syntax is: {value, value, ..., value}
▪ Examples:
int primes[ ] = {2, 3, 5, 7, 11, 13, 19};
String languages[ ] = {"Java", "C", "C++"};

24.Array literals:
▪ You can create an array literal with the following syntax:
type[ ] { value1, value2, ..., valueN }
▪ Examples:
myPrintArray(new int[] {2, 3, 5, 7, 11});

int foo[ ]; foo = new int[]{42, 83};

25.Intializing Arrays III


▪ To initialize an array of Person:
Person people[ ] = { new Person(“Ram"),
new Person(“Shyam"),
new Person(“Amar"),
new Person(“Raj") };
▪ Notice that you do not say the size of the array
▪ The computer is better at counting than you are!

26.Using Array elements:


27.Conditional Statements:
▪ A conditional statement lets us choose which statement will be executed next by
using a conditional test.
▪ Therefore, they are sometimes called Selection Statements.
▪ Conditional statements give us the power to make basic decisions.
▪ Java's conditional statements are
▪ if statement.
▪ if-else statement.
▪ switch statement.

28. if statement:

if is a Java Conditions must


KEYWORD. if (Conditions) be BOOLEAN
expressions,
{
producing either
Statements; TRUE or FALSE!
}

if the conditions are true then the


statements will get executed.

29.Switch statement:
switch (expression) {
case value1: statements ; break ;
case value2: statements ; break ;
...(more cases)...
default : statements ; break ; }
If you forget the break; Statement:

30.While Loop: ‘Entry Controlled’


while(condition Boolean expression){
Statements;
}

31.Do while Loop: ‘Exit Controlled’


do {
Statements;
} while(conditions Boolean expression);

32.For Loop:
for (initialization ; boolean expression ; increment or decrement){
Statements;
}
33.Enhanced For-Each Loop:
A convenient way to write for loop is the enhanced for loop supported by Java.
We don’t need to iterate over the index of an array.
Rather we direct read the elements of the array one by one and do further processing
on it.
34.Comments:
// Single Line Comment
/* Multiple
Line
Comment */
/** Javadoc comment – Multiple line comment that can be read by Javadoc tool to
provide HTML documentation */

35.Access Modifiers:
a. Public: All the classes inside and outside of package can access public features.
You have to write public keyword.
b. Default: All the classes in the package can access default features.
c. Protected: Classes that are in the package and all its subclasses.
d. Private: within the class

36.Overview of Object-Oriented Programming:


▪ Object-Oriented Programming is a programming pattern that makes use of objects
and their interactions to design and implement applications.
▪ Objects are entities that serve as the basic building blocks of an object-oriented
application.
▪ An object is a self-contained entity with attributes and behaviours.
▪ In some way everything can be an object.
▪ In general, an object is a person, place, thing, event, or concept.
▪ Because different people have different perceptions of the same object, what an
object is depends upon the point of view of the observer.
▪ That is, we describe an object on the basis of the features and behaviours that are
important or relevant to us.

37.Abstraction:
▪ An object is thus an abstraction.
▪ An object is an “abstraction of something in the problem domain, reflecting the
capabilities of the system to keep information about it, interact with it, or both.”
(Coad and Yourdon)
▪ An abstraction is a form of representation that includes only what is useful or
interesting from a particular viewpoint.
▪ e.g., a map is an abstract representation, since no map shows every detail of the
territory it covers.

38.Types of Objects:
▪ Objects representing physical things. e.g. students, furniture, buildings, classrooms.
▪ Objects representing concepts. e.g., courses, departments, loan.
39.Class:
▪ We classify similar objects as a type of thing in order to categorize them and make
inferences about their attributes and behaviour. This classification is generally defined
as a Class.
▪ A class is a template for a specific object
▪ A class defines the attributes and methods that all objects belonging to the class.
▪ The attributes and methods of a class are called ‘fields’ or ‘members’.
▪ An instance refers to an object that is a member of a particular class. All objects that
belong to a class are instances of that class.
▪ A class is a "blueprint" or description for the objects.
▪ An object is a specific instance of a class.
▪ Objects are thus instantiated (created/defined) from the class.

40.Class Definition:
▪ Classes are the most fundamental structural element
in Java or C#.
▪ Every program has at least one class defined.
▪ Data member declarations appear within classes.
▪ Methods appear within classes.
▪ Statements appear within methods and properties.
41.Constructors:
▪ When an object of a class is created (via new), a special method called a constructor
is always invoked.
▪ You can supply your own constructor, or let the compiler supply one (that does
nothing).
▪ Constructors are often used to initialize the instance variables for that class.
▪ Characteristics of a constructor:
a. Constructor method has same name as the class.
b. Constructor method never returns a value and must not have a return type
specified (not even void).

42.Encapsulation:
▪ Perhaps the most important principle in OO is that of encapsulation (also known as
information hiding or implementation hiding)
▪ This is the principle of separating the implementation of a class from its interface
and hiding the implementation from its clients
▪ Thus, someone who uses a software object will have knowledge of what it can do,
but will have no knowledge of how it does it.
▪ Encapsulation is implemented through access protection.
▪ Every class, data member and method in a Java or C# program is defined as either
public, private, protected or unspecified/default.
▪ Benefits:
a. Maximizes maintainability:
Making changes to the implementation of a well encapsulated class should have no
impact on rest of system.
b. Decouples content of information from its form of representation thus, the user of
an object will not become tied to format of the information.
▪ An encapsulated object can be thought of as a black box or an abstraction.
▪ Its inner workings are hidden to the client, which only invokes the interface
methods.

43.Inheritance:
▪ Inheritance is the representation of an is a, is like, is kind of relationship between
two classes.
▪ e.g., a Student is a Person, a Professor is kind of a Person
▪ With inheritance, you define a new class that encapsulates the similarities between
two classes.
▪ A superclass/base class/parent class – the class from which the attributes and
behaviours are derived.
▪ A subclass/derived class/child class – a class that derives attributes and behaviours
from another class.
▪ Inheritance is one of the language constructs that encourages the re-use of code by
allowing the behaviours of existing classes to be extended and specialized.
44.Polymorphism:
▪ The ability to change the behavior of the application depending upon the type of an
object.
▪ The ability to manipulate objects of distinct classes using only the knowledge of
their shared members.
▪ It allows us to write several versions of a method in different classes of a subclass
hierarchy and give them all the same name.
▪ The subclass version of an attribute or method is said to override the version from
the superclass.
45.Interface:
46.Abstract and Concrete Classes:
• MCQs:

Question-1. Which of the following would the below Java coding snippet return as its
output?
class Super {
public int index = 1;
}

class App extends Super {

public App(int index) {


index = index;
}

public static void main(String args[]) {


App myApp = new App(10);
System.out.println(myApp.index);
}
}
A. 0
B. 10
C. 1
D. Compile time error
Answer. C

Question-2. Which of the following combinations would the below Java coding
snippet print?
class TestApp {
protected int x, y;
}

class Main {
public static void main(String args[]) {
TestApp app = new TestApp();
System.out.println(app.x + " " + app.y);
}
}
A. 0 1
B. 1 0
C. 0 0
D. null null
Answer. C
Question-3. What would be the outcome of following Java coding snippet?
class TestApp {
public static void main(String[] args) {
for (int index = 0; 1; index++) {
System.out.println("Welcome");
break;
}
}
}
A. Welcome
B. Welcome Welcome
C. Type mismatch error
D. Run infinite-times
Answer. C

Question-4. What would the below Java coding snippet print?


class TestApp {
public static void main(String[] args) {
for (int index = 0; true; index++) {
System.out.println("Welcome");
break;
}
}
}
A. Welcome
B. None
C. Type mismatch error
D. Run infinite times
Answer. A

Question-5. Which of the following values would the below Java coding snippet print
in results?
class TestApp {
int i[] = { 0 };

public static void main(String args[]) {


int i[] = { 1 };
alter(i);
System.out.println(i[0]);
}

public static void alter(int i[]) {


int j[] = { 2 };
i = j;
}
}
A. 0
B. 1
C. 2
D. Compilation error
Answer. B

Question-6. Which of the following is the result of the following Java code?
class TestApp {

String args[] = { "1", "2" };

public static void main(String args[]) {


if (args.length > 0)
System.out.println(args.length);
}
}
A. The program compiles but prints nothing.
B. The program fails to compile.
C. The program compiles and prints 2.
D. The program compiles and prints 0.
Answer. A

Question-7. What is the result of the following Java coding snippet?


class TestApp {

public static void main() {


int odd = 1;
if (odd) {
System.out.println("odd");
} else {
System.out.println("even");
}
}
}
A. odd
B. even
C. Run-time exception
D. Type mismatch error
Answer. D Note- Type mismatch: cannot convert from int to boolean.
Question-8. What would the following function yield when called?
public void test(boolean a, boolean b) {
if (a) {
System.out.println("A");
} else if (a && b) {
System.out.println("A && B");
} else {
if (!b) {
System.out.println("!B");
} else {
System.out.println("None");
}
}
}
A. If a and b both are true, then the output is “A && B”.
B. If a is true and b is false, then the output is “!B”.
C. If a is false and b is true, then the output is “None”.
D. If a and b both are false, then the output is “None”.
Answer. C

Question-9. What would the following Java coding snippet return as its output?
class TestApp {

public static void main(String[] args) {


class Tutorial {
public String name;

public Tutorial(String tutorial) {


name = tutorial;
}
}

Object obj = new Tutorial("Java Quiz");


Tutorial tutorial = (Tutorial) obj;
System.out.println(tutorial.name);
}
}
A. An exception occurs while instantiating Tutorial class.
B. It’ll print “Java Quiz”.
C. The program will print null.
D. Compilation error at line number 13.

Answer. B
Question-10. What does the following Java coding snippet print?
import java.io.CharArrayReader;
import java.io.IOException;

class TestApp {

public static void main(String[] args) {


String obj = "abcdef";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0, length, c, 0);
CharArrayReader io_1 = new CharArrayReader(c);
CharArrayReader io_2 = new CharArrayReader(c, 0, 3);
int i;
try {
while ((i = io_1.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
A. abc
B. abcd
C. abcde
D. abcdef
Answer. D

Question-11. What will be the output of following Java coding snippet?


import java.io.CharArrayReader;
import java.io.IOException;

class TestApp {

public static void main(String[] args) {


String obj = "abcdef";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0, length, c, 0);
CharArrayReader io_1 = new CharArrayReader(c);
CharArrayReader io_2 = new CharArrayReader(c, 0, 3);
int i;
try {
while ((i = io_2.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
A. abc
B. abcd
C. abcde
D. abcdef
Answer. A

Question-12. What would the following Java coding snippet return?


import java.io.CharArrayReader;
import java.io.IOException;

class TestApp {

public static void main(String[] args) {


String obj = "abcdef";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0, length, c, 0);
CharArrayReader io_1 = new CharArrayReader(c);
CharArrayReader io_2 = new CharArrayReader(c, 1, 4);
int i, j;
try {
while ((i = io_1.read()) == (j = io_2.read())) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
A. abc
B. abcd
C. abcde
D. abcdef
E. Nothing would get printed.
Answer. E Note- Nothing would get printed. Since none of the char in the arrays
matches, so the control would come out of the loop without printing anything.

Question-13. What is the outcome of the below Java code?


class TestApp {

public static void main(String args[]) {


System.out.println(test());
}

static float test() {


static float x = 0.0;
return ++x;
}
}
A. 0.0
B. 1
C. 1.0
D. Compile time error
Answer. D Note- The program would result in a compile error. Unlike C++, Java
doesn’t support static variables declared as local. Though, a class can have static
members to compute the number of function calls or other purposes.

Question-14. What does the following Java coding snippet yield?


class TestApp {

static int index = 0;

public static void main(String args[]) {


System.out.println(test());
}

int test() {
int index = 1;
return index;
}
}
A. 0
B. 1
C. Run-time error at line number 6
D. Compile time error
Answer. D Note- In Java, non-static methods aren’t allowed to get called from a static
method. If we turn test() to static, then the program will compile without any compiler error.
Question-15. Which of the following is the result of the below Java coding snippet?
class TestApp {

public static void main(String args[]) {


int bits;

bits = -3 >> 1;
bits = bits >>> 2;
bits = bits << 1;
System.out.println(bits);
}
}
A. 1
B. 7
C. -2147483646
D. 2147483646
Answer. D

Question-16. Which of the following is a result of the Java code given below?
class TestApp {

public static void main(String args[]) {


int index = 0;
boolean flag = true;
boolean reg1 = false, reg2;
reg2 = (flag | ((index++) == 0));
reg2 = (reg1 | ((index += 2) > 0));

System.out.println(index);
}
}
A. 0
B. 1
C. 2
D. 3
Answer. D

Question-17. What would the following Java coding snippet display on execution?
Command-line: java TestApp 1 2 3 4 5

class TestApp {

public static void main(String[] args) {


System.out.println(args[1] + args[2] + args[3]);
}
}
A. 1 2 3
B. 123
C. 234
D. Compilation Error
Answer. C

Question-18. What would the below Java coding snippet print if input given is ?
Command-line: java TestApp abcqfghqbcd

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class TestApp {

public static void main(String args[]) throws IOException {


char bit;
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
do {
bit = (char) obj.read();
System.out.print(bit);
} while (bit != 'q');
}
}
A. abcqfgh
B. abc
C. abcq
D. abcqfghq
Answer. C

Question-19. What would the following Java coding snippet yield on execution?
import java.io.File;

class TestApp {

public static void main(String args[]) {


File sys = new File("/java/system");
System.out.print(sys.canWrite());
System.out.print(" " + sys.canRead());
}
}
A. true false
B. false true
C. true true
D. false false
Answer. D

Question-20. What does the following Java coding snippet print as its output?
class Cluster {
}

class Node1 extends Cluster {


}

class Node2 extends Cluster {


}

public class TestApp {


public static void main(String[] args) {
Cluster tree = new Node1();
if (tree instanceof Node1)
System.out.println("Node1");
else if (tree instanceof Cluster)
System.out.println("Cluster");
else if (tree instanceof Node2)
System.out.println("Node2");
else
System.out.println("Unexpected");
}
}
A. Cluster
B. Node1
C. Node2
D. Unexpected
Answer. B

Question-21. Which of the following is the result of the below program?


public class SimpleTest {
public static void stringReplace(String str) {
str = str.replace('c', 'c');
}
public static void bufferReplace(StringBuffer str) {
str.trimToSize();
}

public static void main(String args[]) {


String myString = new String("cplus");
StringBuffer myBuffer = new StringBuffer(" plus");
stringReplace(myString);
bufferReplace(myBuffer);
System.out.println(myString + myBuffer);
}
}
A. cplusplus
B. plus plus
C. cplus plus
D. c plus plus
Answer. C

Question-22. Which of the following is the outcome of the below program? Assume
the given input is <abc’def/’egh>.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SimpleTest {

public static void main(String args[]) throws IOException {


char bit;
BufferedReader console = new BufferedReader(new
InputStreamReader(System.in));
do {
bit = (char) console.read();
System.out.print(bit);
} while (bit != '\'');
}

}
A. abc’
B. abcdef/’
C. abc’def/’egh
D. abcqfghq
Answer. A
Question-23. Which of the following is the result of the below Java coding snippet?
import java.io.File;

public class SimpleTest {

public static void main(String args[]) {


File sys = new File("/MVC/system");
System.out.print(sys.getParent());
System.out.print(" " + sys.isFile());
}

}
A. MVC true
B. MVC false
C. \MVC false
D. \MVC true
Answer. C

Question-24. Which of the following would the below Java coding snippet return on
execution?
public class SimpleTest {

static int test;


boolean final()
{
test++;
return true;
}

public static void main(String[] args)


{
test=0;
if ((final() | final()) || final())
test++;
System.out.println(test);
}
}
A. 1
B. 2
C. 3
D. Compilation error
Answer. D Note- In Java, is a reserved keyword so the program will not compile.
Question-25. Which of the following values would the below Java coding snippet
yield?
public class SimpleTest {

public static void main(String[] args) {


String text = "199";
try {
text = text.concat(".5");
double decimal = Double.parseDouble(text);
text = Double.toString(decimal);
int status = (int) Math.ceil(Double.valueOf(text).doubleValue());
System.out.println(status);
} catch (NumberFormatException e) {
System.out.println("Invalid number");
}
}
}
A. 199
B. 199.5
C. 200
D. Invalid number
Answer. C

Question-26. Which of the following combinations would the below program print?
public class SimpleTest {

public static void main(String ags[]) {


String initial = "ABCDEFG", after = "";
after = initial = initial.replace('A', 'Z');
System.out.println(initial + ", " + after);
}
}
A. ABCDEFG, ABCDEFG
B. ABCDEFG, ZBCDEFG
C. ZBCDEFG, ABCDEFG
D. ZBCDEFG, ZBCDEFG

Answer. D

Question-27. Which of the following values would the below Java coding snippet
print?
public class SimpleTest {
public static void main(String args[]) {
String str = (String) returnStringAsArray()[-1 + 1 * 2];
System.out.println(str);
}

public static Object[] returnStringAsArray() {


return new String[] { "Java", "Quiz" };
}
}
A. Java
B. ArrayIndexOutOfBoundsException
C. Quiz
D. Compilation error
Answer. C

Question-28. What would the below Java coding snippet print on execution?
public class SimpleTest {

public static void main(String args[]) {


try {
args[0] = "0";
return;

} catch (Exception e) {
System.out.print("Exception");
} finally {
System.out.print("Final");
}
}
}
A. Exception
B. Final
C. ExceptionFinal
D. Compilation error
Answer. C

Question-29. What does the following Java coding snippet print on execution?
public class SimpleTest {

public static void main(String[] args) {


int[] table = { 1, 2, 3, 4, 5 };
table[1] = (table[2 * 1] == 2 - args.length) ? table[3] : 99;
System.out.println(table[1]);
}
}
A. Compilation fails.
B. 3
C. 2
D. 99
Answer. D

Question-30. What would be the output of the below Java coding snippet upon
execution?
import java.util.Random;

public class SimpleTest {

static int count = 0;

public static void main(String[] args) throws InterruptedException {


Consumer test = new Consumer();
Producer prod1 = new Producer(test, "thread-1");
Producer prod2 = new Producer(test, "thread-2");
prod1.start();
prod2.start();
}
}

class Producer extends Thread {


Consumer test;
String message;

Producer(Consumer test, String msg) {


this.test = test;
message = msg;
}

public void run() {


Random rand = new Random();
int randomNum = rand.nextInt((1000 - 10) + 1) + 10;
System.out.println(message);
}
}

class Consumer {
private int count = 0;
public int nextCounter() {
synchronized (this) {
count++;
return count;
}
}
}
A. Runtime Exception
B. thread-1 thread-2
C. thread-2 thread-1
D. Sometimes thread-2 will precede thread-1.
Answer. D

Potrebbero piacerti anche