JAVA REV Flashcards

1
Q

Decision Making Structures

A

Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Java programming language provides following types of decision making statements.

A

if statement
if..else statement
nested if statement
switch statement

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

IF Statement

A

An if statement consists of a Boolean expression followed by one or more statements.

Syntax :
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not, the first set of code after the end of the if statement (after the closing curly brace) will be executed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

IF..ELSE Statement

A

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax :
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

IF..ELSE IF Statement

A

An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement.

When using if, else if, else statements there are a few points to keep in mind.

An if can have zero or one else’s and it must come after any else if’s.
An if can have zero to many else if’s and they must come before the else.
Once an else if succeeds, none of the remaining else if’s or else’s will be tested.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Nested IF Statement

A

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

SWITCH Statement

A

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Rules for SWITCH Statement

A

The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums.
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Loops In Java

A

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Types Of Loops :

A

Java programming language provides the following types of loop to handle looping requirements :

While loop
For loop
Do..While loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

While Loop

A

A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.

Syntax :
while(Boolean_expression) {
// Statements
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non zero value.

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

When the condition becomes false, program control passes to the line immediately following the loop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

For Loop

A

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax :
for(initialization; Boolean_expression; update) {
// Statements
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Do..While Loop

A

A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.

Syntax :
do {
// Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Enhanced For Loop

A

As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays.

Syntax :
for(declaration : expression) {
// Statements
}

Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Usage of “this” keyword

A

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.

Here is given the 6 usage of java this keyword.

this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Usage of the “new” keyword

A

When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class.

Declaration : First, you must declare a variable of the class type. This variable does not define an object.

Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.

The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Usage of “super” keyword

A

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.

super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Static Keyword

A

The static keyword in Java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance of the class.

The static can be:

Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Static variable

A

If you declare any variable as static, it is known as a static variable.

The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time of class loading.
It makes your program memory efficient (i.e., it saves memory).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Final Keyword

A

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a String?

A

Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects.

The Java platform provides the String class to create and manipulate strings.

Note : The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.

22
Q

Concatenating Strings

A

The String class includes a method for concatenating two strings :

string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals

“My Name is”.concat(“Zara”);
Strings are most commonly concatenated with the “+” operator

“Hello,” + “ world” + “!”

23
Q

Some String Handling Methods

A

char charAt(int index) - Returns the character at the specified index.
int compareTo(Object o) - Compares this String to another Object.
String concat(String str) - Concatenates the specified string to the end of this string.
boolean equals(Object anObject) - Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString) - Compares this String to another String, ignoring case considerations.

24
Q

Package

A

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

25
Q

Advantages Of Packages

A

Java package is used to categorize the classes and interfaces so that they can be easily maintained.
Java package provides access protection.
Java package removes naming collision.

26
Q

Accessing a package from other packages

A

There are three ways to access the package from outside the package.

import package.*;
import package.classname;
fully qualified name.

27
Q

Using packagename.*

A

If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.

The import keyword is used to make the classes and interface of another package accessible to the current package.

28
Q

Using packagename.classname

A

If you import package.classname then only declared class of this package will be accessible.

29
Q

Using fully qualified name

A

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.

30
Q

Sequence of program

A

Sequence of the program must be package then import then class.

31
Q

Interface

A

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

32
Q

Similarities between an interface and a class

A

An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
The byte code of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

33
Q

Differences between an interface and a class

A

You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
An interface is not extended by a class, it is implemented by a class.
An interface can extend multiple interfaces.

34
Q

Implementing Interfaces

A

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

35
Q

Exceptions?

A

Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.).

In Java, an exception is an object that wraps an error event that occurred within a method and contains:

Information about the error including its type
The state of the program when the error occurred
Optionally, other custom information
Categories of Exceptions :

Checked Exceptions
Unchecked Exceptions
Errors

36
Q

Checked Exceptions

A

Checked exceptions are those that :

The compiler enforces that you handle them explicitly.
Methods that generate checked exceptions must declare that they throw them.
Methods that invoke other methods that throw checked exceptions must either handle them (they can be reasonably expected to recover) or let them propagate by declaring that they throw them.

37
Q

Unchecked Exceptions

A

Errors and RuntimeExceptions are unchecked — that is, the compiler does not enforce (check) that you handle them explicitly.
Methods do not have to declare that they throw them (in the method signatures).
It is assumed that the application cannot do anything to recover from these exceptions (at runtime).

38
Q

Errors

A

These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

39
Q

Catching Exceptions

A

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following

try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}

40
Q

The Throw/Throws Keyword

A

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.
One can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.
Understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.

41
Q

Finally Block

A

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax

42
Q

Array

A

Normally, an array is a collection of similar type of elements that have a contiguous memory location.

Java array is an object which contains elements of a similar data type. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in java is index-based, the first element of the array is stored at the 0 index.

43
Q

Array advantage and disadvantages

A

Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

44
Q

Types of Array

A

There are two types of array.

Single Dimensional Array
Multidimensional Array

45
Q

Queue

A

The Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.

LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations.

46
Q

Collection Interface

A

The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have.

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following :

Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.
In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.

47
Q

The List Interface

A

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.

Elements can be inserted or accessed by their position in the list, using a zero-based index.
A list may contain duplicate elements.
In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following table.
Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.

48
Q

ArrayList

A

ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

ArrayList inherits AbstractList class and implements List interface.
ArrayList is initialized by a size, however the size can increase if collection grows or shrunk if objects are removed from the collection.
Java ArrayList allows us to randomly access the list.
ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.
Code to create a generic integer ArrayList :

ArrayList<Integer> arrli = new ArrayList<Integer>();</Integer></Integer>

49
Q

The Set Interface

A

The Set Interface
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.

50
Q

The Map Interface

A

The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date.

Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
Several methods throw a NoSuchElementException when no items exist in the invoking map.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map.
An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map.