Introductory Concepts in Java Flashcards

1
Q

Who created Java?

A

Sun Microsystems

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

Describe the Structure of a call

A

It contains an access modifier followed by a class name and {} brackets with the main method in the class

public class MyClass {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the main method in Java

A

It is the method that Java first looks for when to run a program

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

How do you add single line comments in Java?

A

Use two forward slashes to start a comment //

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

How do you do a multi-line comment?

A

It begins with a /* and ends with a */

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

What are variables in Java?

A

Variables are used to store data

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

what are 5 types of variables?

A
1 - String
2 - Int
3 - Float 
4 - Char 
5 - Boolean
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you declare a variable in Java?

A

The basic syntax for declaring a variable is Data Type Name of Variable = Value of Variable
A specific String Variable String firstName = “Doug”;

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

What happens when you add the keyword final to the start of a variable?

A

It makes it no longer possible to change the value of the variable

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

How do you display the value of the variable?

A

Here is the specific example

String firstName = “Bob”;
system.out.println(firstName);

You would use the printLn method and use the name of the variable.

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

What is the best way to declare multiple variables with the same type?

A

Use a comma separated list

String firstName = “Bob”, firstName2 = “Mary”, firstName3 =”Terry”;

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

what are some tips to naming variables?

A

1 - Choose names that help describe the purpose of the variable
2 - Can’t use reserved words
3- Can use letters, underscore and dollar sign
4- Needs to start with a lower case letter

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

What are the two groups of variables?

A

1 - Primitive

2- Non-Primitive

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

What are the primitive data types?

A
1- Byte
2- Short 
3 - Int
4 - Long
5 - Float
6 - Double
7 - Boolean
8 - Char
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the non-primitive types?

A

1 - String
2 - Array
3 - Class

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

What are the two groups of the number data type?

A

1 - Integer

2 - Floating Point Types

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

What are the two values of the boolean data type?

A

1 - True

2 - False

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

What is the char Data type?

A

1 - It represents one character and is surrounded by quotes.

For example

Char myChar = “b”;

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

What is type casting in Java?

A

It is going from one value to another value in primitive type.

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

What are the two types of casting?

A

1 - Widening

2 - Narrowing

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

What are the groups for operators in Java?

A
1 - Arithmetic
2 - Assignment
3 - Comparison
4 - Logical 
5 - Bitwise
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the syntax to designate a String data type?

A

String name = “Bob”;

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

What are some of the most popular String Methods?

A

1 - toUpperCase()
2 - toLowerCase()
3 - indexOf()

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

What is the Math Class?

A

The math class has many built in Math Methods that help perform many different Math functions.

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

What are some of the built in Math Methods?

A
1- Max()
2- Min()
3 - sqrt()
4- abs()
5 random()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the syntax for the Boolean data type?

A

boolean isTrue = true;

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

What is the syntax for conditional statements in Java?

A
if(parameter){
code block
}else if(parameter){
code block
}else {
code block
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is a ternary operator?

A

It is a short-hand way of writing a if else conditional statement.

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

What is the syntax for the ternary operator?

A

int score = 9;

String outcome = (score < 10) ? “You lose!” : “You win!”;

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

What is a switch statement?

A

A switch statement is a conditional statement that can be used when there are many cases.

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

What is the syntax for the switch statement?

A
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Why is it important to add a break statement after the code block?

A

If a break statement is not included it will continue onto the next statement until there is either a break statement or the end of the cases.

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

What is the default keyword in the Switch statement?

A

It will run if not of the other conditions are valid.

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

What is a while loop?

A

It is a custom code block to execute a block of code until a specific condition is reached

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

What is the syntax for the while loop?

A
while (condition) {
  // code block to be executed
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is the difference between a while loop and a do/while loop?

A

A Do/While loop will execute once before it checks the condition while the while loop will check the condition before it runs the code block

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

What is the syntax for a do/while loop?

A
do {
  // code block to be executed
}
while (condition);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is a for loop?

A

It is used to run a code block when it is known how many times you want to loop through a block of code.

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

What is the syntax for a for loop?

A
for (statement 1; statement 2; statement 3) {
  // code block to be executed
 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is a break statement in a for loop?

A

It breaks out of a loop when a condition is met

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

What is the syntax for the break statement?

A
for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  System.out.println(i);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is the syntax for an array?

A

String[] cars;

int[] myNum = {10, 20, 30, 40};

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

What are the steps of a java program?

A

This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program execution. Phases are as follows: we write the program, then we compile the program and at last we run the program.

1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler included in java development kit (JDK). It takes java program as input and generates java bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run phase

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

What is the primary function of the Java Virtual Machine?

A

So, now that we understood that the primary function of JVM is to execute the bytecode produced by compiler. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language

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

Where is the bytecode saved after it is compiled?

A

javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. The bytecode is saved in a .class file by compiler.

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

What is the function of the Java Compiler?

A

Compiler(javac) converts source code (.java file) to the byte code(.class file). As mentioned above, JVM executes the bytecode produced by compiler. This byte code can run on any platform such as Windows, Linux, Mac OS etc. Which means a program that is compiled on windows can run on Linux and vice-versa. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language.

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

What are the 4 main concepts of Object Oriented Program in Java?

A

4 main concepts of Object Oriented programming are:

Abstraction
Encapsulation
Inheritance
Polymorphism

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

Why is Java considered a simple language?

A

Java is considered as one of simple language because it does not have complex features like Operator overloading, Multiple inheritance, pointers and Explicit memory allocation.

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

Why is Java a reliable or robust language?

A

Robust means reliable. Java programming language is developed in a way that puts a lot of emphasis on early checking for possible errors, that’s why java compiler is able to detect errors that are not easy to detect in other programming languages. The main features of java that makes it robust are garbage collection, Exception Handling and memory allocation.

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

Describe Java is distributed

A

Using java programming language we can create distributed applications. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java. In simple words: The java programs can be distributed on more than one systems that are connected to each other using internet connection. Objects on one JVM (java virtual machine) can execute procedures on a remote JVM.

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

What is multi threading in Java?

A

Java supports multithreading. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU.

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

What does portable mean with Java?

A

java code that is written on one machine can run on another machine. The platform independent byte code can be carried to any platform for execution that makes java code portable.

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

What is another definition of static?

A

static: We do not need to create object for static methods to run. They can run itself.

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

What is the variable naming convention for Java?

A

1) Variables naming cannot contain white spaces, for example: int num ber = 100; is invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case letter, for example int number; For lengthy variables names that has more than one words do it like this: int smallNumber; int bigNumber; (start the second word with capital letter).
4) Variable names are case sensitive in Java.

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

What are the three types of variables?

A

1) Local variable 2) Static (or class) variable 3) Instance variable

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

What is the syntax for a ternary operator?

A

variable num1 = (expression) ? value if true : value if false

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

What is a constructor?

A

Constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and method are different(More on this at the end of this guide). People often refer constructor as special type of method in Java.

Constructor has same name as the class and looks like this in a java code

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

How does the constructor work?

A
When we create the object of MyClass like this
The new keyword here creates the object of class MyClass and invokes the constructor to initialize this newly created object.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

What are the three constructor types?

A

Default, No-arg constructor and Parameterized.

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

What is constructor overloading?

A

Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.

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

Constructor Recap

A
Every class has a constructor whether it’s a normal class or a abstract class.
Constructors are not methods and they don’t have any return type.
Constructor name should match with class name .
Constructor can use any access specifier, they can be declared as private also. Private constructors are possible in java but there scope is within the class only.
Like constructors method can also have name same as class name, but still they have return type, though which we can identify them that they are methods not constructors.
If you don’t implement any constructor within the class, compiler will do it for.
this() and super() should be the first statement in the constructor code. If you don’t mention them, compiler does it for you accordingly.
Constructor overloading is possible but overriding is not possible. Which means we can have overloaded constructor in our class but we can’t override a constructor.
Constructors can not be inherited.
If Super class doesn’t have a no-arg(default) constructor then compiler would not insert a default constructor in child class as it does in normal scenario.
Interfaces do not have constructors.
Abstract class can have constructor and it gets invoked when a class, which implements interface, is instantiated. (i.e. object creation of concrete class).
A constructor can also invoke another constructor of the same class – By using this(). If you want to invoke a parameterized constructor then do it like this: this(parameter list).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

What is the difference between a method and constructor?

A
The purpose of constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code.
Constructors cannot be abstract, final, static and synchronised while methods can be.
Constructors do not have return types while methods do
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

What is the static key word?

A

Static keyword can be used with class, variable, method and block. Static members belong to the class instead of a specific instance, this means if you make a member static, you can access it without object

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

what is a child class?

A

The class that extends the features of another class is known as child class, sub class or derived class

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

What is a parent class?

A

The class whose properties and functionalities are used(inherited) by another class is known as parent class, super class or Base class

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

What is the relationship with constructors and inheritance?

A

constructor of sub class is invoked when we create the object of subclass, it by default invokes the default constructor of super class. Hence, in inheritance the objects are constructed top-down. The superclass constructor can be called explicitly using the super keyword, but it should be first statement in a constructor. The super keyword refers to the superclass, immediately above of the calling class in the hierarchy. The use of multiple super keywords to access an ancestor class other than the direct parent is not permitted

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

What is aggregation?

A

Aggregation is a special form of association. It is a relationship between two classes like association, however its a directional association, which means it is strictly a one way association. It represents a HAS-A relationship.

It really defines the relationship between two classes.

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

Why we need aggregation?

A

It is to help reuse code over and over again

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

What is association?

A

Association establishes relationship between two separate classes through their objects. The relationship can be one to one, One to many, many to one and many to many

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

What is the difference between composition, association, and aggregation?

A

Association is a relationship between two separate classes and the association can be of any type say one to one, one to may etc. It joins two entirely separate entities.

Aggregation is a special form of association which is a unidirectional one way relationship between classes (or entities), for e.g. Wallet and Money classes. Wallet has Money but money doesn’t need to have Wallet necessarily so its a one directional relationship. In this relationship both the entries can survive if other one ends. In our example if Wallet class is not present, it does not mean that the Money class cannot exist.

Composition is a restricted form of Aggregation in which two entities (or you can say classes) are highly dependent on each other. For e.g. Human and Heart. A human needs heart to live and a heart needs a Human body to survive. In other words when the classes (entities) are dependent on each other and their life span are same (if one dies then another one too) then its a composition. Heart class has no sense if Human class is not present.

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

What is the super keyword?

A

The super keyword refers to the objects of immediate parent class. It can have access to the variables of the parent and can call the instantiation of the parent class.

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

What are the three ways to overload a method?

A

1 - The amount of parameters
2- data types of parameters
3 - order or data types of parameter

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

What is method overriding?

A

Declaring a method in sub class which is already present in parent class is known as method overriding. Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. In this case the method in parent class is called overridden method and the method in child class is called overriding method. In this guide, we will see what is method overriding in Java and why we use it.

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

what is polymorphism?

A

Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways. For example, lets say we have a class Animal that has a method sound(). Since this is a generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a generic message.

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

what are the types of polymorphism?

A

There are two types of polymorphism in java:

1) Static Polymorphism also known as compile time polymorphism
2) Dynamic Polymorphism also known as runtime polymorphism

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

Why can’t we create a class of the abstract class?

A
Because these classes are incomplete, they have abstract methods that have no body so if java allows you to create object of this class then if someone calls the abstract method using that object then What would happen?There would be no actual implementation of the method to invoke.
Also because an object is concrete. An abstract class is like a template, so you have to extend it and build on it before you can use it.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

Rules of Abstract Classes and methods

A

Abstract methods don’t have body, they just have method signature as shown above.

  1. If a class has an abstract method it should be declared abstract, the vice versa is not true, which means an abstract class doesn’t need to have an abstract method compulsory.
  2. If a regular class extends an abstract class, then the class must have to implement all the abstract methods of abstract parent class or it has to be declared abstract as well.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

What is encapsulation?

A

Encapsulation simply means binding object state(fields) and behaviour(methods) together. If you are creating class, you are doing encapsulation. In this guide we will see how to do encapsulation in java program.

The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class

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

How to encapsulate in Java?

A

1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields

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

What are the advantages of encapsulation?

A
It improves maintainability and flexibility and re-usability: for e.g. In the above code the implementation code of void setEmpName(String name) and String getEmpName() can be changed at any point of time. Since the implementation is purely hidden for outside classes they would still be accessing the private field empName using the same methods (setEmpName(String name) and getEmpName()). Hence the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the underlying class.
The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) that we don’t want to be changed so we simply define the variable as private and instead of set and get both we just need to define the get method for that variable. Since the set method is not present there is no way an outside class can modify the value of that field.
User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

What are packages?

A

Packages in java and how to use them
BY CHAITANYA SINGH | FILED UNDER: OOPS CONCEPT

A package as the name suggests is a pack(group) of classes, interfaces and other packages. In java we use packages to organize our classes and interfaces. We have two types of packages in Java: built-in packages and the packages we can create (also known as user defined package). In this guide we will learn what are packages, what are user-defined packages in java and how to use them

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

Advantages of using packages

A

Reusability: While developing a project in java, we often feel that there are few things that we are writing again and again in our code. Using packages, you can create such things in form of classes inside a package and whenever you need to perform that same task, just import that package and use the class.
Better Organization: Again, in large java projects where we have several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency.
Name Conflicts: We can define two classes with the same name in different packages so to avoid name collision, we can use packages

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

What are the four access modifiers?

A

. default

  1. private
  2. protected
  3. public
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

What is an exception?

A

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user

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

Why an exception occurs?

A

There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc

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

What are the advantages of exception?

A

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.

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

What is the difference between an error and exception?

A

Errors indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.

Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for example array size is 5 (which means it has five elements) and you are trying to access the 10th element

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

What are the types of exceptions?

A

Checked exceptions

2)Unchecked exceptions

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

What are some of the common exceptions?

A

Example 1: Arithmetic exception
Example 2: ArrayIndexOutOfBounds Exception
Example 3: NumberFormat Exception
Example 4: StringIndexOutOfBound Exception
Example 5: NullPointer Exception

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

What is a thread?

A

A thread is a light-weight smallest part of a process that can run concurrently with the other parts(other threads) of the same process. Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads. All threads of a process share the common memory

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

What is multithreading?

A

The process of executing multiple threads simultaneously is known as multithreading.

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

Summary of Multithreading

A

The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.

  1. Threads are lightweight sub-processes, they share the common memory space. In Multithreaded environment, programs that are benefited from multithreading, utilize the maximum CPU time so that the idle time can be kept to minimum.
  2. A thread can be in one of the following states:
    NEW – A thread that has not yet started is in this state.
    RUNNABLE – A thread executing in the Java virtual machine is in this state.
    BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.
    WAITING – A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
    TIMED_WAITING – A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
    TERMINATED – A thread that has exited is in this state.
    A thread can be in only one state at a given point in time
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

Multitasking vs Multithreading vs Multiprocessing vs parallel processing

A

Multitasking vs Multithreading vs Multiprocessing vs parallel processing
If you are new to java you may get confused among these terms as they are used quite frequently when we discuss multithreading. Let’s talk about them in brief.

Multitasking: Ability to execute more than one task at the same time is known as multitasking.

Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.

Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.

Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.

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

How to create a thread?

A

There are two ways to create a thread in Java:

1) By extending Thread class.
2) By implementing Runnable interface.

Before we begin with the programs(code) of creating threads, let’s have a look at these methods of Thread class. We have used few of these methods in the example below.

getName(): It is used for Obtaining a thread’s name
getPriority(): Obtain a thread’s priority
isAlive(): Determine if a thread is still running
join(): Wait for a thread to terminate
run(): Entry point for the thread
sleep(): suspend a thread for a period of time
start(): start a thread by calling its run() method

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

How to create a file in Java?

A

we will see how to create a file in Java using createNewFile() method. This method creates an empty file, if the file doesn’t exist at the specified location and returns true. If the file is already present then this method returns false

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

What are two ways to read files?

A

1 - Buffered Input Stream

2 - Buffered Reader

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

What are some Java 8 features?

A

Java 8 – Lambda Expression

  1. Java 8 – Method references
  2. Java 8 – Functional interfaces
  3. Java 8 – Interface changes: Default and static methods
  4. Java 8 – Streams
  5. Java 8 – Stream filter
  6. Java 8 – forEach()
  7. Java 8 – Collectors class with example
  8. Java 8 – StringJoiner class with example
  9. Java 8 – Optional class with example
  10. Java 8 – Arrays Parallel Sort
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

What are some Java 9 features?

A

. JShell

  1. JPMS (Java Platform Module System)
  2. JLink (Java Linker)
  3. Http/2 client
  4. Process API updates
  5. Private Methods Inside Interface
  6. Try with resources enhancements
  7. Factory Methods to create unmodifiable collections

Java 9 – Factory Methods to create Immutable List
Java 9 – Factory Methods to create Immutable Set
Java 9 – Factory Methods to create Immutable Map
9. Java 9 – Stream API enhancements
10. Diamond operator enhancement
11. SafeVarargs Annotation
12. G1 GC (Garbage first Garbage collector) – default garbage collector
13. Java 9 – Anonymous Inner classes and Diamond Operator
14. Java 9 Modules

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

What is a servlet?

A

Servlet is a java program that runs inside JVM on the web server. It is used for developing dynamic web applications.

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

What are the advantages of the servlet?

A

Unlike CGI, the servlet programs are handled by separate threads that can run concurrently more efficiently. Servlet only uses Java as programming language that makes it platform independent and portable. Another benefit of using java is that the servlet can take advantage of the object oriented programming features of java.

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

what are the main features of a servlet?

A
  1. Portable:
    As I mentioned above that Servlet uses Java as a programming language, Since java is platform independent, the same holds true for servlets. For example, you can create a servlet on Windows operating system that users GlassFish as web server and later run it on any other operating system like Unix, Linux with Apache tomcat web server, this feature makes servlet portable and this is the main advantage servlet has over CGI.
  2. Efficient and scalable:
    Once a servlet is deployed and loaded on a web server, it can instantly start fulfilling request of clients. The web server invokes servlet using a lightweight thread so multiple client requests can be fulling by servlet at the same time using the multithreading feature of Java. Compared to CGI where the server has to initiate a new process for every client request, the servlet is truly efficient and scalable.
  3. Robust:
    By inheriting the top features of Java (such as Garbage collection, Exception handling, Java Security Manager etc.) the servlet is less prone to memory management issues and memory leaks. This makes development of web application in servlets secure and less error prone.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

How do you implement a servlet?

A

You need to use Servlet API to create servlets. There are two packages that you must remember while using API, the javax.servlet package that contains the classes to support generic servlet (protocol-independent servlet) and the javax.servlet.http package that contains classes to support http servlet. You may be wondering what is generic and http servlet, I have explained them later in this post.

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

What is the http Servlet?

A

If you creating Http Servlet you must extend javax.servlet.http.HttpServlet class, which is an abstract class. Unlike Generic Servlet, the HTTP Servlet doesn’t override the service() method. Instead it overrides one or more of the following methods. It must override at least one method from the list below:

doGet() – This method is called by servlet service method to handle the HTTP GET request from client. The Get method is used for getting information from the server
doPost() – Used for posting information to the Server
doPut() – This method is similar to doPost method but unlike doPost method where we send information to the server, this method sends file to the server, this is similar to the FTP operation from client to server
doDelete() – allows a client to delete a document, webpage or information from the server
init() and destroy() – Used for managing resources that are held for the life of the servlet
getServletInfo() – Returns information about the servlet, such as author, version, and copyright.

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

What is JSP?

A

ava Server Pages (JSP) is a server side technology for developing dynamic web pages. This is mainly used for implementing presentation layer (GUI Part) of an application

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

Where does the servlet sit on the request process?

A

Before the database

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

What two packages build servlets?

A

javax. servlet(Basic)

javax. servlet.http(Advance)

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

What is DBMS?

A

DBMS stands for Database Management System. We can break it like this DBMS = Database + Management System. Database is a collection of data and Management System is a set of programs to store and retrieve those data. Based on this we can define DBMS like this: DBMS is a collection of inter-related data and set of programs to store & access those data in an easy and effective manner.

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

What is the purpose of Database System?

A

The main purpose of database systems is to manage the data. Consider a university that keeps the data of students, teachers, courses, books etc. To manage this data we need to store this data somewhere where we can add new data, delete unused data, update outdated data, retrieve data, to perform these operations on data we need a Database management system that allows us to store the data in such a way so that all these operations can be performed on the data efficiently.

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

What is an ENUM?

A

An enum is a special type of data type which is basically a collection (set) of constants. In this tutorial we will learn how to use enums in Java and what are the possible scenarios where we can use them.

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

What is a good example of an ENUM?

A

Days of Week,Months etc.. it would be constants that don’t change

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

What are Java annotations?

A

Java Annotations allow us to add metadata information into our source code, although they are not a part of the program itself. Annotations were added to the java from JDK 5. Annotation has no direct effect on the operation of the code they annotate (i.e. it does not affect the execution of the program).

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

What are some built in annotations?

A

@Override
@Deprecated
@SuppressWarnings

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

What are regular Expressions?

A

Regular expressions are used for defining String patterns that can be used for searching, manipulating and editing a text. These expressions are also known as Regex (short form of Regular expressions).

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

How to delete a file in Java?

A
import java.io.File;
public class DeleteFileJavaDemo
{
   public static void main(String[] args)
   {	
      try{
         //Specify the file name and path
    	 File file = new File("C:\\myfile.txt");
         /*the delete() method returns true if the file is
          * deleted successfully else it returns false
          */
    	 if(file.delete()){
    	    System.out.println(file.getName() + " is deleted!");
         }else{
    	    System.out.println("Delete failed: File didn't delete");
    	  }
       }catch(Exception e){
           System.out.println("Exception occurred");
    	   e.printStackTrace();
    	}
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
115
Q

How do you rename a file?

A
import java.io.File;
public class RenameFileJavaDemo
{
    public static void main(String[] args)
    {	
        //Old File
	File oldfile =new File("C:\\myfile.txt");
	//New File
	File newfile =new File("C:\\mynewfile.txt");
	/*renameTo() return boolean value
	 * It return true if rename operation is
	 * successful
	 */
        boolean flag = oldfile.renameTo(newfile);
	if(flag){
	   System.out.println("File renamed successfully");
	}else{
	   System.out.println("Rename operation failed");
	 }
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
116
Q

What is JSON?

A

JSON stands for JavaScript Object Notation. JSON objects are used for transferring data between server and client, XML serves the same purpose. However JSON objects have several advantages over XML and we are going to discuss them in this tutorial along with JSON concepts and its usages.

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

What is the syntax for JSON?

A
var chaitanya = {
   "firstName" : "Chaitanya",
   "lastName" : "Singh",
   "age" :  "28"
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
118
Q

What is polymorphism?

A

Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways. For example, lets say we have a class Animal that has a method sound(). Since this is a generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a generic message.

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

What is the JVM?

A

Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your computer) and the machine language for JVM is byte code. This makes it easier for compiler as it has to generate byte code for JVM rather than different machine code for each type of machine. JVM executes the byte code generated by compiler and produce output. JVM is the one that makes java platform independent.

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

What is inheritance?

A

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

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

What is abstraction?

A

Hiding internal details and showing functionality is known as abstraction. For example phone call, we don’t know the internal processing.

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

What is encapsulation?

A

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

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

What is coupling?

A

Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation.

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

What is cohesion?

A

Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces.

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

What is association?

A

Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects:

One to One
One to Many
Many to One, and
Many to Many
Let's understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have one prime minister (many to one), and many ministers can have many departments (many to many).

Association can be undirectional or bidirectional.

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

What is aggregation?

A

Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects.

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

What is composition?

A

The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically.

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

What are some naming conventions for Classes?

A

It should start with the uppercase letter.
It should be a noun such as Color, Button, System, Thread, etc.
Use appropriate words, instead of acronyms

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

What is a naming convention for Interfaces?

A

It should start with the uppercase letter.
It should be an adjective such as Runnable, Remote, ActionListener.
Use appropriate words, instead of acronyms

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

What is a naming convention for methods?

A

It should start with lowercase letter.
It should be a verb such as main(), print(), println().
If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed().

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

What is a naming convention for variables?

A

It should start with a lowercase letter such as id, name.
It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName.
Avoid using one-character variables such as x, y, z.

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

What is a naming convention for packages?

A

It should be a lowercase letter such as java, lang.

If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang.

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

What is a naming convention for constants?

A

t should be in uppercase letters such as RED, YELLOW.
If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY.
It may contain digits but not as the first letter.

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

A class in Java typically contains?

A
Fields
Methods
Constructors
Blocks
Nested class and interface
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
135
Q

What does the new keyword due in Java?

A

The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.

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

What are three ways to initialize an object?

A

There are 3 ways to initialize object in Java.

By reference variable
By method
By constructor

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

What is an anonymous object?

A

Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.

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

When is the constructor called in a class?

A

It is called when the object is initialized and the parameters are inserted. A constructor is called a default constructor when it doesn’t have an parameters.

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

Can a constructor use overloading?

A

Yes

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

Can constructor perform other tasks instead of initialization?

A

Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the constructor as you perform in the method.

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

What is the static keyword?

A

next →← prev
Java static keyword
Static variable
Program of the counter without static variable
Program of the counter with static variable
Static method
Restrictions for the static method
Why is the main method static?
Static block
Can we execute a program without main method?
The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. 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
142
Q

Why is Static important?

A

Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, “college” refers to the common property of all objects. If we make it static, this field will get the memory only once.

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

What is a Java Static Method?

A

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
144
Q

Q) Why is the Java main method static?

A

Ans) It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.

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

Q) Can we execute a program without main() method?

A

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a Java class without the main method.

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

What are the uses for this keyword?

A

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
147
Q

What is inheritance?

A

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also

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

What is the syntax for inheritance?

A
class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
149
Q

What is aggregation?

A

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below

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

What is the syntax for aggregation?

A
class Employee{  
int id;  
String name;  
Address address;//Address is a class  
...  
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
151
Q

What are two ways to overload a method?

A

There are two ways to overload the method in java

By changing number of arguments
By changing the data type

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

What is the 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.

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

When do you use the super keyword?

A
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
154
Q

What are the instance initializer block?

A
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be done directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
155
Q

Where are the three places in Java to perform operations?

A

There are three places in java where you can perform operations:
method
constructor
block

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

Where can the final keyword be made?

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. We will have detailed learning of these. Let's first learn the basics of final keyword.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
157
Q

What happens when you make a method final?

A

If you make any method as final, you cannot override it.

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

What happens if you make a class final?

A

If you make any class as final, you cannot extend it.

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

What is polymorphism?

A

Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word “poly” means many and “morphs” means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

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

What is the java instanceOf?

A

The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.

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

What is abstraction?

A

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don’t know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

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

What are some things to remember with abstraction?

A

An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.

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

What is a factory method?

A

A factory method is a method that returns the instance of the class. We will learn about the factory method later.

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

What is an interface?

A

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

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

What is encapsulation?

A

Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines.

encapsulation in java
We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
166
Q

What is a java bean?

A

The Java Bean class is the example of a fully encapsulated class.

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

What are some advantages of encapsulation?

A

By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods.

It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE’s are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.

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

What is the object class?

A

The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don’t know. Notice that parent class reference variable can refer the child class object, know as upcasting.

Let’s take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object.

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

What is object cloning?

A

The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don’t implement Cloneable interface, clone() method generates CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

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

What are the advantages of object cloning?

A

Although Object.clone() has some design issues but it is still a popular and easy way of copying objects. Following is a list of advantages of using clone() method:

You don't need to write lengthy and repetitive codes. Just use an abstract class with a 4- or 5-line long clone() method.
It is the easiest and most efficient way for copying objects, especially if we are applying it to an already developed or an old project. Just define a parent class, implement Cloneable in it, provide the definition of the clone() method and the task will be done.
Clone() is the fastest way to copy array.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
171
Q

What are the disadvantages of object cloning?

A

To use the Object.clone() method, we have to change a lot of syntaxes to our code, like implementing a Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling Object.clone() etc.
We have to implement cloneable interface while it doesn’t have any methods in it. We just have to use it to tell the JVM that we can perform clone() on our object.
Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.
Object.clone() doesn’t invoke any constructor so we don’t have any control over object construction.
If you want to write a clone method in a child class then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.
Object.clone() supports only shallow copying but we will need to override it if we need deep cloning.

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

What is the java math class?

A

Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Unlike some of the StrictMath class numeric methods, all implementations of the equivalent function of Math class can’t define to return the bit-for-bit same results. This relaxation permits implementation with better-performance where strict reproducibility is not required.

If the size is int or long and the results overflow the range of value, the methods addExact(), subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException.

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

What is the wrapper class?

A

The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing

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

What is the
next →← prev
Java Strictfp Keyword?

A

Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language have provided the strictfp keyword, so that you get same result on every platform. So, now you have better control over the floating-point arithmeti

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

What are the differences between an object and a class?

A

https://www.javatpoint.com/difference-between-object-and-class

176
Q

What is the difference between method overloading and method overriding?

A

https://www.javatpoint.com/method-overloading-vs-method-overriding-in-java

177
Q

What are two ways to create a string?

A

By string literal

By new keyword

178
Q

What are three ways to compare a string?

A
By equals() method
By = = operator
By compareTo() method
179
Q

What is string concatenation?

A

In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java:

By + (string concatenation) operator
By concat() method
180
Q

What is a substring?

A

A part of string is called substring. In other words, substring is a subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive.

181
Q

What are methods in Strings?

A

The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.

182
Q

What is the sting buffer class?

A

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

183
Q

What is the string builder class?

A

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

184
Q

What is the ToString method?

A

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the string representation of the object.

If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

185
Q

What is a string tokenizer?

A

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.

It doesn’t provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

186
Q

What is Regular Expressions?

A

The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.

It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.

187
Q

What is the exception handling ?

A

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.

188
Q

What is exception handling part 2?

A

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

189
Q

What are the advantages of exception handling?

A

The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling.

190
Q

What are types of exceptions?

A

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:

Checked Exception
Unchecked Exception
Error

191
Q

What is the try block?

A

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.

192
Q

What are multi catch blocks?

A

Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.

Points to remember
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.

193
Q

What is finally block?

A

Java finally block is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

194
Q

What is the throw exception?

A

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

195
Q

What is the throws keyword?

A

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.

196
Q

What is a custom exception?

A

f you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let’s see a simple example of java custom exception.

197
Q

What is a java inner class?

A

Java inner class or nested class is a class which is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.

Additionally, it can access all the members of outer class including private data members and methods.

198
Q

What are advantages of the java inner class?

A

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.

199
Q

What is a java anonymous inner class?

A

A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:

Class (may be abstract or concrete).
Interface

200
Q

What is multithreading?

A

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don’t allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

201
Q

What are advantages of multithreading?

A

It doesn’t block the user because threads are independent and you can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn’t affect other threads if an exception occurs in a single thread.

202
Q

What is a thread?

A

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.

Threads are independent. If there occurs exception in one thread, it doesn’t affect other threads. It uses a shared memory area.

203
Q

What is the thread class?

A

Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

204
Q

What are the stages of a thread?

A
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
205
Q

How do you create a thread?

A

There are two ways to create a thread:

By extending Thread class
By implementing Runnable interface
206
Q

What are some commonly used thread classes?

A

Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)

207
Q

What is a thread scheduler?

A

Thread scheduler in java is the part of the JVM that decides which thread should run.

There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.

Only one thread at a time can run in a single process.

208
Q

What is sleeping a thread?

A

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

209
Q

Can you start a thread twice?

A

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

210
Q

What is a thread pool?

A

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times.

In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

211
Q

What is the runtime class?

A

Java Runtime class is used to interact with java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory etc. There is only one instance of java.lang.Runtime class is available for one java application.

212
Q

What is a synchronized block?

A

Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.

213
Q

What is Java I/O?

A

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

We can perform file handling in Java by Java I/O API.

214
Q

What is a stream?

A

A stream is a sequence of data. In Java, a stream is composed of bytes. It’s called a stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

Let’s see the code to print output and an error message to the console.

215
Q

What is an output stream?

A

Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket.

216
Q

What is an input stream?

A

Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket

217
Q

What is a socket?

A

A socket in Java is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number.

218
Q

What is Java FileOutputStream?

A

Java FileOutputStream is an output stream used for writing data to a file.

If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.

219
Q

What is the file input stream?

A

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.

220
Q

Java BufferedOutputStream class

A

Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let’s see the syntax for adding the buffer in an OutputStream:

221
Q

What is the Java console class?

A

The Java Console class is be used to get input from console. It provides methods to read texts and passwords.

If you read password using Console class, it will not be displayed to the user.

222
Q

What is the java writer class?

A

It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency, functionality or both.

223
Q

What is the reader class?

A

Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods to provide higher efficiency, additional functionality, or both.

Some of the implementation class are BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader

224
Q

what is the file class?

A

The File class is an abstract representation of file and directory pathname. A pathname can be either absolute or relative.

The File class have several methods for working with directories and files such as creating new directories or files, deleting and renaming directories or files, listing the contents of a directory etc.

225
Q

what is the scanner class?

A

Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.

226
Q

what is java networking?

A

Java Networking is a concept of connecting two or more computing devices together so that we can share resources.

Java socket programming provides facility to share data between different computing devices.

227
Q

Important networking items

A
P Address
Protocol
Port Number
MAC Address
Connection-oriented and connection-less protocol
Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:

TCP
FTP
Telnet
SMTP
POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications.

The port number is associated with the IP address for communication between two applications.

4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller). A network node can have multiple NIC but each with unique MAC.

5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of connection-less protocol is UDP.

6) Socket
A socket is an endpoint between two way communication.

Visit next page for java socket programming.

228
Q

What is java socket programming?

A

Java Socket programming is used for communication between the applications running on different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

229
Q

what does a url contain?

A

A URL contains many information:

Protocol: In this case, http is the protocol.
Server name or IP Address: In this case, www.javatpoint.com is the server name.
Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1.
File Name or directory name: In this case, index.jsp is the file name.

230
Q

Start here

A

https://www.javatpoint.com/URL-class

231
Q

What is the toString() method

A

It is a built in method in the object class that can give you information about the object, it is often overwritten and modified with information about the specific class that is created, including variables and attributes

232
Q

How do you override the default toString() method

A

Would use the annotation @Override

233
Q

What do you extend the object class?

A

It is automatically extended

234
Q

why are access modifiers important?

A

It gives the user access for what they need and nothing else

235
Q

what is a unique aspect of getters and setters?

A

It can set the variable to be a global variable that can be used throughout the program

236
Q

What is one requirement of an interface?

A

It is like a contract and the class that implements it, must use all of it.

237
Q

where does the exception typically go in a try/catch block?

A

It goes in as an argument with the type and variables

238
Q

How would you write a custom exception?

A

Create a class and extend the exception class

239
Q

What are the steps to create a custom exception?

A
1- Constructor that takes a value that will throw an exception
2- Assign value of local variable class variable
3- overrride toString method to provide exception
240
Q

what class do you use to read a file?

A

Buffered reader

file reader

241
Q

What is one thing to consider when reading and writing to a file?

A

Make sure to include multiple exceptions

242
Q

What is a java bean?

A

It is a file where you can share information for the application, store properties for the instance variables, it is a class with properties and getters and setters

243
Q

What is a java servlet?

A

It is a file that handles the get and post requests from the application.

244
Q

What are the classes for dates and time?

A

The java.time, java.util, java.sql and java.text packages contains classes for representing date and time. Following classes are important for dealing with date in java.

245
Q

How to convert from string to integer?

A

public static int parseInt(String s)

246
Q

What are some of the steps to convert from a data type to another?

A

Need to use one of the designated methods and follow the syntax

247
Q

What is a collection in Java?

A

The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

248
Q

More details on Collections

A

What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java
It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:

Interfaces and its implementations, i.e., classes
Algorithm

249
Q

What is the iterator interface?

A

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

250
Q

What is the list interface?

A

List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

251
Q

What is the array list?

A

The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of different data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements stored in the ArrayList class can be randomly accessed.

252
Q

What is the linked list?

A

LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast because no shifting is required.

253
Q

What is a set interface?

A

Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered set of elements which doesn’t allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

254
Q

What is a hash set?

A

HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.

255
Q

What is a tree set?

A

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.

256
Q

What is the difference between a generic and non-generic?

A

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime.

Let’s see the old non-generic example of creating java collection.

ArrayList al=new ArrayList();//creating old non-generic arraylist

ArrayList al=new ArrayList();//creating new generic arraylist

257
Q

What is the Java list interface?

A

List Interface is the subinterface of Collection. It contains index-based methods to insert and delete elements. It is a factory of ListIterator interface.

258
Q

How to sort in collections?

A

We can sort the elements of:

String objects
Wrapper class objects
User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
259
Q

How to compare objects?

A

Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else.

260
Q

What is the property class in Java?

A

The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable.

It can be used to get property value based on the property key. The Properties class provides methods to get data from the properties file and store data into the properties file. Moreover, it can be used to get the properties of a system.

261
Q

What is the JDBC?

A

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. There are four types of JDBC drivers:

JDBC-ODBC Bridge Driver,
Native Driver,
Network Protocol Driver, and
Thin Driver
We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save, update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC) provided by Microsoft.

262
Q

What are some popular interfaces?

A

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:

Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
263
Q

What are some popular classes?

A

A list of popular classes of JDBC API are given below:

DriverManager class
Blob class
Clob class
Types class
264
Q

Why should we use JDBC?

A

Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following activities:

Connect to the database
Execute queries and update statements to the database
Retrieve the result received from the database.

265
Q

Start here

A

https://www.javatpoint.com/jdbc-driver

266
Q

What the the domain name?

A

It is the web address

267
Q

What is the relative path?

A

it includes the part after the domain name and it calls the file that will be called. In Java it will send the form data to the java file and process the form info. It is also the path to the file in the application

268
Q

What is the pathname?

A

It is what comes after the domain name
the whole web site is https://www.w3schools.com/jsref/prop_loc_pathname.asp
path name is /jsref/tryit.asp

269
Q

What is the process to process a form in java?

A

Need to create a form and set the input form with a name then the action needs to point to the relative path for the java file that will process the form. The java file is a servlet that is a special class to process get and post requests and responses. The response will process the form and request and send back a response

270
Q

How do you use beans to store form data?

A

Need to import bean into the file and then set property in it Use JSP set property. The bean looks for any parameters that match the name in the bean

271
Q

What is scope in JSP?

A

There are a bunch of options, session etc.. that determine how long a value is stored

272
Q

What is the session object?

A

transfer data from jsp to servlet in the same session

The HttpSession object is used for session management. A session contains information specific to a particular user across the whole application. When a user enters into a website (or an online application) for the first time HttpSession is obtained via request.getSession(), the user is given a unique ID to identify his session. This unique ID can be stored into a cookie or in a request parameter.

The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t specify the value in tag. This means that when the user doesn’t visit web application time specified, the session is destroyed by servlet container. The subsequent request will not be served from this session anymore, the servlet container will create a new session.

This is how you create a HttpSession object.

protected void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
}
You can store the user information into the session object by using setAttribute() method and later when needed this information can be fetched from the session. This is how you store info in session. Here we are storing username, emailid and userage in session with the attribute name uName, uemailId and uAge respectively.

273
Q

Session object

A

with the session object can set items that would be relavant during a session http request

274
Q

What is casting in java?

A

1

animal = (Animal) cat;

275
Q

Connecting to a database

A

There is typically a connector class that is available if you are using tom cat, need to have a connector class

276
Q

Connecting to a database

A

Also need to have a connection string

277
Q

What is a servlet?

A

It is basically a route / end point in the data base that points to a file and handles the request and issues a resposne

278
Q

How is JSP process and Java?

A

The request is sent to the server, the server sends back the html code with the java code that will process things based on the request information

279
Q

What are java servlets?

A
1 Java class that is processed on the server
2 Java class that creates html and returns it 
3 Can read html form data, use cookies, sessions
280
Q

What is @webServlet

A
it returns the path to the servlet that will process it 
servlet is an imported java class
that handles the request and sends back a response
281
Q

What are the steps on a servlet?

A

1- Set the content type text/html
2 get the printwriter
3 generate the html contennt

282
Q

What is an applet?

A

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side.

283
Q

What are the advantages of applets?

A

There are many advantages of applet. They are as follows:

It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.

284
Q

What is the syntax for applet?

A
285
Q

What is java reflection?

A

Java Reflection is a process of examining or modifying the run time behavior of a class at run time.

The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.

The java.lang and java.lang.reflect packages provide classes for java reflection

286
Q

Where is the reflection API used?

A

The Reflection API is mainly used in:

IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
Debugger
Test Tools etc.

287
Q

What are the classes that contain date and time?

A

The java.time, java.util, java.sql and java.text packages contains classes for representing date and time. Following classes are important for dealing with date in java.

288
Q

Java conversion

A

There are many different data types to convert to

289
Q

What are collections in Java?

A

The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

A Collection represents a single unit of objects, i.e., a group.

290
Q

What is the difference between a list and a set?

A

A list can contain duplicate elements whereas Set contains unique elements only.

291
Q

What is the Map Interface?

A

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

292
Q

What is the tree map?

A

Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order.

The important points about Java TreeMap class are:

Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
Java TreeMap contains only unique elements.
Java TreeMap cannot have a null key but can have multiple null values.
Java TreeMap is non synchronized.
Java TreeMap maintains ascending order.

293
Q

What is the comparable interface?

A

Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else.

compareTo(Object obj) method
public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns

positive integer, if the current object is greater than the specified object.
negative integer, if the current object is less than the specified object.
zero, if the current object is equal to the specified object.

294
Q

What is Java JDBC?

A

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. There are four types of JDBC drivers:

JDBC-ODBC Bridge Driver,
Native Driver,
Network Protocol Driver, and
Thin Driver
We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save, update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC) provided by Microsoft.

295
Q

Why should we use JDBC?

A

Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following activities:

Connect to the database
Execute queries and update statements to the database
Retrieve the result received from the database.

296
Q

What are the steps to connect to a database?

A
Register the Driver class
Create connection
Create statement
Execute queries
Close connection
297
Q

What to connect with a Oracle Database?

A

To connect java application with the oracle database, we need to follow 5 following steps. In this example, we are using Oracle 10g as the database. So we need to know following information for the oracle database:
Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. You may get all these information from the tnsnames.ora file.
Username: The default username for the oracle database is system.
Password: It is the password given by the user at the time of installing the oracle database.

298
Q

What is a connection in java?

A

A Connection is the session between java application and database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit(), rollback() etc.

299
Q

What is a statement interface?

A

The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

300
Q

How to store an image in an oracle database?

A

You can store images in the database in java by the help of PreparedStatement interface.

The setBinaryStream() method of PreparedStatement is used to set Binary information into the parameterIndex.

301
Q

What is batch processing in JDBC?

A

Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance fast.

The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.

302
Q

What are some of the new features in Java?

A

There are many new features that have been added in java. There are major enhancement made in Java5, Java6, Java7 and Java8 like auto-boxing, generics, var-args, java annotations, enum, premain method , lambda expressions, functional interface, method references etc.

303
Q

What is Remote Method Invocation?

A

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM.

The RMI provides remote communication between the applications using two objects stub and skeleton.

304
Q

What is one key of the servelt?

A

It holds the business logic

305
Q

How would you define the MVC in Java?

A
Model = database
Controller = Servlet
View = JSP Page
306
Q

How to set up a servlet?

A

Go to eclipse and select create servlet and then set one up and modify the doGet or doPost methods

307
Q

What is a helper class?

A

A class that can access a database or serve another purpose to help another class

308
Q

What is a request dispatcher?

A

It connects the jsp page to the data and to the request address

309
Q

How to get value in the JSP or Slightly?

A

if you put ${tempStudent.firstName} if you put the name in there it will call the get method

310
Q

How to access servlet from an html page?

A

Would set the href to the servlet name to call the servlet when clicked

311
Q

What is a database connection pool?

A

Allows app to scale and handle multiple users quickly

312
Q

What do you need to have to connect to database?

A

Need to have driver jar file

313
Q

What is a DAO?

A

Data Accessor Object and is a very common design pattern in Java. Responsible for interfacing with the database using JDBC code.

314
Q

What are some common steps for MVC?

A

1- Web Browsers sends a request to the servlet(controller)
2- Servlet passes request to Helper Class dbUtil (model) to help request to databse (DAO) Data Accessor Object
3- DAO retrieves data from database and is sent back to controller
4- Controller combines data with jsp and sends to view
5- View is sent back to browser

315
Q

How are the regular class and helper class (DAO) connected?

A

THE DAO connects to the database and connects data to the class and references the class. It will also build the object to return from the database

316
Q

Why add a to String method to a class?

A

Helpful to debug and log information

317
Q

How is the helper class (DAO) related to the servlet?

A

The servlet is the aggregator it will take the DAO and helper class and the jsp and serve them up. Set up a reference to the DAO. The servlet will create the actual connection, whereas the DAO will set the framework for the connection and is another class. Do all of the initialization work on top

318
Q

What is a welcome file?

A

Java Servlet spec defines a deployment descriptor file
*Web-inf / web.xml file
* various configs for application deployment
defines a list of welcome files.

If the file is not identified then it will look for welcome files

319
Q

What is the purpose of an xml file in java?

A

It will serve as configuration for the application

320
Q

How do you link a form to a servlet?

A

It will be the action of the form and it will send it there

321
Q

Why would you have a input hidden in form ?

A

It can pass some values into the form and database. It can serve as a router depending on command that is sent

322
Q

What does the get parameter function do on the request object?

A

It will grab the form data based on the name of the form that is submitted

323
Q

Summary comparing to Angular

A

The servlet is the express js file that handles the database requests, the DAO/helper file is the express js file that connects and creates a class to call that is used by the server, could also be classified as a service.

324
Q

Define the HTTPServletRequest Class

A

it is a class to handle requests and is used to grab parameters that are sent to the servlet from a form

325
Q

Breakdown of servlet

A

The servlet will use a class that will define the structure of the data, similar to a model for angular. Then it will utilize the helper class that will create a connection to the database and write the sql code and then will connect the data to the jsp page to sent it back to the browser

326
Q

What are explicit type conversions?

A

Conversions performed explicitely in code with a cast operator

long Ival = 50;
in ival = (int) Ival;

327
Q

How to create a class instance?

A
Use the new keyword to create a class instance
allocates memory described by the class
returns a reference to the allocated memory
328
Q

One thing to remember about parameters

A

Need to include the type

329
Q

Special references for Null

A

Null is a reference literal
represents an uncreated object
can be assigned to any reference variable

330
Q

What is one of the purposes of constructors?

A

To set initial state of the object

331
Q

What is an initialization block?

A

It is a block of code that will initially set the code for a variables
{int num = 5;}

332
Q

What are typed references?

A

In Java there are four types of references differentiated on the way by which they are garbage collected.

Strong References
Weak References
Soft References
Phantom References

Strong References: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. The object is garbage collected only when the variable which was strongly referenced points to null.

MyClass obj = new MyClass ();

333
Q

what is the difference between sting and string buffer?

A

String buffer has methods to manipulate strings like append etc..

334
Q

Describe a static final field?

A

It is basically a Constant

335
Q

When are exceptions or errors are used?

A

Typically during the catch portion of the code block, throw an exception

336
Q

Can you have multiple catch statements with multiple exceptions?

A

Yes

337
Q

What is the throws clause?

A

it will throw an exception and we know it will be our responsibility to deal with exception. The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

338
Q

What is the throws clause?

A

it will throw an exception and we know it will be our responsibility to deal with exception. The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

The throw keyword is used to create a custom error.

The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.

The exception type is often used together with a custom method, like in the example above.

339
Q

Describe custom exceptions

A

These are exceptions that are created to handle errors and are created when extending the exceptions class

340
Q

What needs to be qualified when using Java?

A

Don’t need to qualify classes in the same package or types, types in java.lang don’t need to be qualified, if it is not one of these then need to import a type

341
Q

What is one more benefits of packages?

A

Packages provide a unit of distribution

342
Q

What happens when classes implement interfaces?

A

It issues a contract that a class has to conform to. Expresses that the class conforms to the contract. Interfaces don’t limit other aspects of the class’ implementation.

343
Q

Describe interfaces

A

Can have methods but not implementations, can extend another interface and have a contract

344
Q

What is an anonymous classes?

A
Declared as part of their creation
useful for simple interface implemenations or class extensions
are inner classes
345
Q

Why do you use collections vs arrays?

A
Arrays are inflexible and difficult to add items to and to manipulate.  Coollections, 
1- Iteration Order lists
2- Uniqueness sets
3- Defining and iteration
4- Collections of pairs--Mpa
5-  Collections methods
346
Q

What are common in lists?

A

1- Have order
2- Can iterate
3- Can index

347
Q

How do you pick a collection?

A

1 Elements are keyed –List of not list
2 Are elements unique? –Set
3- Are elements first in first out
4- Is order important – Map or Sorted Map

348
Q

What is a generic type parameter?

A

It takes a collection and gives it a type

Collection products = new ArrayList<>();

349
Q

What is one consideration when looping over a collection?

A

Can use a for loop, but can’t modify the collection when using a for loop

350
Q

What are key features of list Collection?

A
1- Iteration order
2- has an index
3- add method
4- Get method
5- can look up values at an index
351
Q

What is a linked list?

A

Points to next element and previous list and is ordered

352
Q

What does a garbage collector do?

A

Java also takes care of memory management and it also provides an automatic garbage collector. This collects the unused objects automatically.

353
Q

Start here

A

https://www.geeksforgeeks.org/java-how-to-start-learning-java/

354
Q

what is a 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. Being an interface the queue needs a concrete class for the declaration and the most common classes are the PriorityQueue and LinkedList in Java.It is to be noted that both the implementations are not thread safe. PriorityBlockingQueue is one alternative implementation if thread safe implementation is needed. Few important characteristics of Queue are:

The Queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It follows FIFO concept.
The Java Queue supports all methods of Collection interface including insertion, deletion etc.
LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations.
If any null operation is performed on BlockingQueues, NullPointerException is thrown.

355
Q

What is a priority queue?

A

A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a queue follows First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

In the below priority queue, element with maximum ASCII value will have the highest priority.

PriorityQueue doesn’t permit null.
We can’t create PriorityQueue of Objects that are non-comparable
PriorityQueue are unbound queues.
The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements — ties are broken arbitrarily.
The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.
It inherits methods from AbstractQueue, AbstractCollection, Collection and Object class.

356
Q

What are stacks?

A

A Stack is a Last In First Out (LIFO) data structure. It supports two basic operations called push and pop. The push operation adds an element at the top of the stack, and the pop operation removes an element from the top of the stack. Java provides a Stack class which models the Stack data structure.

357
Q

what is a deque?

A

The java.util.Deque interface is a subtype of the java.util.Queue interface. The Deque is related to the double-ended queue that supports addition or removal of elements from either end of the data structure, it can be used as a queue (first-in-first-out/FIFO) or as a stack (last-in-first-out/LIFO). These are faster than Stack and LinkedList.

Few important features of Deque are:

It provides the support of resizable array and helps in restriction-free capacity, so to grow the array according to the usage.
Array deques prohibit the use of Null elements and do not accept any such elements.
Any concurrent access by multiple threads is not supported.
In the absence of external synchronization, Deque is not thread-safe.

358
Q

What is one important aspect of maps?

A

The speed to compile and time savings

359
Q

What are maps in Java?

A

The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.

Few characteristics of the Map Interface are:

A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null value like the HashMap and LinkedHashMap, but some do not like the TreeMap.
The order of a map depends on specific implementations, e.g TreeMap and LinkedHashMap have predictable order, while HashMap does not.
There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap, TreeMap and LinkedHashMap.

Maps are perfect to use for key-value association mapping such as dictionaries. The maps are used to perform lookups by keys or when someone wants to retrieve and update elements by keys.

360
Q

What are collection algorithms?

A

Methods that are available on collections,
1- Rotate
2- Sort
3- Search

361
Q

What are collection factories?

A

Factory methods are special type of static methods that are used to create unmodifiable instances of collections. It means we can use these methods to create list, set and map of small number of elements. Each interface has it’s own factory methods, we are listing all the methods in the following tables.

362
Q

What are java generics?

A

Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type

Code Reuse: We can write a method/class/interface once and use for any type we want.

363
Q

Servlet details

A

When the servlet is first started it will do the init method and then will listen to and handle requests for do get and to post.

364
Q

what are java beans?

A

Java classes that can store information, store properties that store information about instance variables. A bean has properties and gettter and setter methods

365
Q

What is the getParameterss() function in a servlet

A

it will get the url parameters and be able to use them

Can be used on both get and post requests

366
Q

MVC Java explained for FORMS

A

When submitting data into a form need to have an action that will submit to the servlet that will set the values in the class and then will display the values. And will send back a page based on the form that is submitted. Then you would create a bean to hold the data than can be reused later

367
Q

What is a servlet?

A
Java class that is processed on the server
2- Can generate html and returned to the browser
3- Can read form data , cookies , and sessions
368
Q

what is the path to a servlet?

A

https://localhost:8080/{projectname}/servetName and the servlet name is typically spelled out in the @webservlet notation

369
Q

Can a servlet read xml parameters?

A

Yes, it would use the ServletContext class and use the getInitialParameter to read it. web.xml file

370
Q

How do you define configuration elements of the application?

A

Would do it in the web.xml file called context param, include a name and value

371
Q

Go over some details on servlets and object oriented programming.

A

Servlets are a class, and typically create a class to represent the data object and then another class to connect to the database and then pull the files in to make is sustainable. One important thing is to figure out what is the purpose of the class

372
Q

What does the @resource notation do

A

It can connect to a resource like a database and then have a datasource below it

373
Q

What composes the Java environment?

A

Java Environment: The programming environment of Java consists of three components mainly:
JDK
JRE
JVM

374
Q

What is a variable in Java?

A

Variables in Java: A variable is the name given to a memory location. It is the basic unit of storage in a program.

375
Q

How does the JVM Java Virtual Machine work?

A

JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java enabled system without any adjustment. This is all possible because of JVM.

When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file are generated by the Java compiler. This .class file goes into various steps when we run it. These steps together describe the whole JVM

376
Q

Describe inheritance

A

Inheritance: Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class.
Important terminology:
Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
The keyword used for inheritance is extends

377
Q

what is encapsultion?

A
Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
378
Q

what is abstraction?

A

Abstraction: Data Abstraction is the property by virtue of which only the essential details are displayed to the user.The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.

Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.

In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.

379
Q

What is a constructor?

A

Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation.

Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no.
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.

380
Q

What are collections?

A

A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.

The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes.

Need for Collection Framework :
Before Collection Framework (or before JDK 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Vectors or Hashtables. All of these collections had no common interface.

Accessing elements of these Data Structures was a hassle as each had a different method (and syntax) for accessing its members

381
Q

What are streams?

A

Streams are a way of modifying arrays

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
The features of Java stream are –

A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
Different Operations On Streams-
Intermediate Operations:

map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x->x*x).collect(Collectors.toList());
filter: The filter method is used to select elements as per the Predicate passed as argument.
List names = Arrays.asList(“Reflection”,”Collection”,”Stream”);
List result = names.stream().filter(s->s.startsWith(“S”)).collect(Collectors.toList());
sorted: The sorted method is used to sort the stream.
List names = Arrays.asList(“Reflection”,”Collection”,”Stream”);
List result = names.stream().sorted().collect(Collectors.toList());

382
Q

Start here

A

https://www.geeksforgeeks.org/exceptions-in-java/

383
Q

Why is it important to change perspectives in eclipse?

A

Need to change perspective to match the project, need to change to Java EE to create games.

384
Q

What is a server?

A

A server is another computer that receieves a request and issues a response, mostly static pages, but not it can serve up dynamic pages. There can be a web server and an application server. The server will determine the output and sent it back to the client and the browser will render the response.

385
Q

What is the dynamic web model?

A

Can contain user provided data
data stored by cookies
current time, date, browser
triggered by client behavior

386
Q

What is java model 2 architecture?

A

1- Client sends request
2- Web Server handles request and sends to servlet
3- Servlet handles request and incorporates helper clas to query database or retrieve informaton
4- Java Server Pages compiles the view and retrieves data

387
Q

Configuration: web.xml file

A

1- Many web applications require configuration information so that the server will know how to set up, deploy, and connect to various components of the application
1- older java applications stored all the configuration in the web.xml file
2- web.xml is a deployment descriptor
3- the web.xml file must reside in the WEB-INF directory – found in Web Content of eclipse projects

388
Q

Servlets and url mappings

A

in the web.xml file can have a servlet with a name and then add a serlet mapping to have a custom name to access that servlet

389
Q

What are the 4 types of errors?

A

1- Syntax errors
2- Compile Errors
3- Run time errors
4- Logic Errors

390
Q

What is syntax error?

A

Collection of rules for spelling, naming, and punctuation for java.

391
Q

What is a compile error?

A

write in a high level language and then it is compiled. Compiling is the process of translating the java program into machine language and the error occurs when it is compiled. It can pass syntax without errors, but when compiles there are more rules that it may not meet and not compile. One example of this is having a string set to an integer.

392
Q

What is a run time error?

A

These are errors that occur durring some point when you run the program. Make sure test program using as many scenarios as possible.

393
Q

What are logic errors?

A

It is when the program runs correctly, but then sends the wrong results. Need to find when testing .

394
Q

What are some basic debugging techniques?

A

1- Print debugging
2- Analyze error messages and stack traces
3- Narrow down where error is location
4- using debugging tools in ide

395
Q

What is a database server?

A

It is a database that receives a request (query) and issues a response data

396
Q

What is a software driver?

A

1- a software driver is a form of middleware
2- a small program that comes between two technologies
3- primary purpose is to act as a translator between two technologies
–the two technologies are the application and the databse

397
Q

What is the JDBC?

A

1- Java based data access technology
2- generally thought to stand for Java Datbase Connectivity
3- Provides an API for java programming language that defines how we may access a database with our applications
4- JDBC classes are stored in the java.sql and javax.sql packages of the JCL

398
Q

What are the general steps for connecting to a database in java?

A

0- import and attach appropriate driver to your project
1- Make a connection to the database
2- make a prepared statement to allow sql commands
3- execute the SQL command
4- Process the results

399
Q

What is one way to think of the request and response object?

A

It can be thought of an input and output.

400
Q

What is an exception?

A

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.

Error vs Exception

Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.

401
Q

What is the exception hierarchy?

A

All exception and errors types are sub classes of class Throwable, which is base class of hierarchy.One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception.Another branch,Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.

402
Q

How does the JVM handle exceptions?

A

All exception and errors types are sub classes of class Throwable, which is base class of hierarchy.One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception.Another branch,Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.

403
Q

How handle an exception?

A

Customized Exception Handling : Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.

404
Q

What are some points to remember in Exceptions?

A
In a method, there can be more than one statements that might throw exception, So put all these statements within its own try block and provide separate exception handler within own catch block for each of them.
If an exception occurs within the try block, that exception is handled by the exception handler associated with it. To associate exception handler, we must put catch block after it. There can be more than one exception handlers. Each catch block is a exception handler that handles the exception of the type indicated by its argument. The argument, ExceptionType declares the type of the exception that it can handle and must be the name of the class that inherits from Throwable class.
For each try block there can be zero or more catch blocks, but only one finally block.
The finally block is optional.It always gets executed whether an exception occurred in try block or not . If exception occurs, then it will be executed after try and catch blocks. And if exception does not occur then it will be executed after the try block. The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection.
405
Q

Why are handling exceptions important?

A

It is important to handle your exceptions because then the rest of the program will be handled, if it is not handled then It will print out the exception description
2- Print a stack trace
3- terminate the running program

406
Q

What are regular expressions?

A

Regular Expressions or Regex (in short) is an API for defining String patterns that can be used for searching, manipulating and editing a string in Java. Email validation and passwords are few areas of strings where Regex are widely used to define the constraints. Regular Expressions are provided under java.util.regex package. This consists of 3 classes and 1 interface.

407
Q

What are the regular expression classes?

A

1- Match Result Interface
2- Pattern Class
3- Matcher Class
4- PatternSyntax Exception class

408
Q

What is a CDN?

A

A content delivery network (CDN) refers to a geographically distributed group of servers which work together to provide fast delivery of Internet content. A CDN allows for the quick transfer of assets needed for loading Internet content including HTML pages, javascript files, stylesheets, images, and videos.

409
Q

What is multithreading in Java?

A

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms :

  1. Extending the Thread class
  2. Implementing the Runnable Interface
410
Q

Start here

A

https://www.geeksforgeeks.org/file-handling-in-java-with-crud-operations/

411
Q

What is type casting with example?

A
Example
int y = 10;
short x = (short)y
System.out.println(y);
This is called manual casting and happens when narrow casting
412
Q

What do datatypes affect?

A

Memory allocation

413
Q

Are variable names case sensitive?

A

Yes

414
Q

What is a generics?

A

It is using a parameter for a method, class, or interface so it can be used over and over again with a different data type, the key point is that is a parameter that needs to be put in when it is instantiated

415
Q

Extending bounds in Generics

A

It is adding additional types to generics

416
Q

what is the best way to work with stack traces?

A

Start with the bottom and work your way up

417
Q

what is url mapping in servlets?

A

it is a way of mapping the url to the appropriate servlet

418
Q

How does the project affect the url?

A

It is part of the url address

419
Q

How does a java program go from a written program t a executable application?

A

First start with a source file with a java extension
Second it will be compiled
The java c command will compile it
to run files need to have a jvm on the file, it reads the file that was compiled and runs it. It will run it in the console the browser or on a phone

420
Q

what is the servlet process?

A

1- Browser sends the an http request that goes to a web container
2- The web container holds multiple servlets
3- Servlet is a special method that java uses to handle incoming HTTP requests
4- In web containers there is a router that decides where the request goes and which servlet will handle it
5 - Java handles this in a web.xml file , tells web container when a request comes in where to route the request.
6- the route request will look for the name of the servlet and class that needs to be loaded and then will attach to the url mapping, define the servlet and map the servlet

421
Q

What are java annotations?

A

Adding an annotation encapsulates the method or class

1- @secured– can define role method in the interface
2-

422
Q

What does the web xml file do?

A

It helps the program know what it has, it describes the part of the code the web container needs to know about. Load the name and class of the servlet and then the mapping for the servlet

423
Q

Java Cookies Explaination

A

When a user logs in the server will send a cookie to the user that will be stored as a session the users computer so they can be remembered. The user will send the cookie back to the server and allow access.

424
Q

what is a web service?

A

information provided by one server and used for many applications and can consume or use in an application. Need to annotation with @webservice

Web services is basically an api

425
Q

How do you consume a web service?

A

Can explose that web service from a wsdl

describes the class that is being exposed and call the service

make a call to a proxy and to an xml message

Can create a web service on the server and one on the client

There is a wizard to do it and create a series of classes

426
Q

What is multithreading in Java?

A

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms :

  1. Extending the Thread class
  2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

427
Q

How to add a logger?

A

final static Logger logger = logger.getLogger(current.class)

This will log to the logger and create a file for the logger ;

and it will write to the log file

Need to modify it to show where it will file the logs

428
Q

How do you connect a database to an application?

A

Need to have a driver , need jar file and msqlConnected

and then need to add an external JAR file

429
Q

How do you log something into the console?

A

need to put system.out.ln(‘This is the message’);

430
Q

What is a JDBC? Connectivity

A

Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access any kind of tabular data, especially relational database. It is part of Java Standard Edition platform, from Oracle Corporation. It acts as a middle layer interface between java applications and database.

The JDBC classes are contained in the Java Package java.sql and javax.sql.
JDBC helps you to write Java applications that manage these three programming activities:

Connect to a data source, like a database.
Send queries and update statements to the database
Retrieve and process the results received from the database in answer to your query

JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC drivers:

Type-1 driver or JDBC-ODBC bridge driver
Type-2 driver or Native-API driver
Type-3 driver or Network Protocol driver
Type-4 driver or Thin driver

431
Q

what is a microservice?

A

A microservice is a small, loosely coupled distributed service. Microservice Architectures evolved as a solution to the scalability and innovation challenges with Monolith architectures (Monolith applications are typically huge – more 100, 000 line of code). It allows you to take a large application and decompose or break into easily manageable small components with narrowly defined responsibilities.

Reasons for using Microservice:
In monolith application, there are few challenges:

For a large application, it is difficult to understand the complexity and make code changes fast and correctly, sometimes it becomes hard to manage the code.
Applications need extensive manual testing to ensure the impact of changes.
For small change, the whole application needs to be built and deployed.
The heavy application slows down start-up time.

Small Modules –
Application is broken into smaller modules which are easy for developers to code and maintain.
Easier Process Adaption –
By using microservices, new Technology & Process Adaption becomes easier. You can try new technologies with the newer microservices that we use.
Independent scaling –
Each microservice can scale independently via X-axis scaling (cloning with more CPU or memory) and Z-axis scaling (sharding), based upon their needs.
Unaffected –
Large applications remain largely unaffected by the failure of a single module.
DURS –
Each service can be independently DURS (deployed, updated, replaced, and scaled).

432
Q

What are three common packages?

A

java. io package
java. lang package
java. util package

433
Q

What is an iterator in Java?

A

‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection.
java.util package has public interface Iterator and contains three methods:

boolean hasNext(): It returns true if Iterator has more element to iterate.
Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.
void remove(): It removes the current element in the collection. This method throws ‘IllegalStateException’ if this function is called before next( ) is invoked.
434
Q

What is garbage collection in java?

A

Garbage Collection in Java
Introduction

In C/C++, programmer is responsible for both creation and destruction of objects. Usually programmer neglects destruction of useless objects. Due to this negligence, at certain point, for creation of new objects, sufficient memory may not be available and entire program will terminate abnormally causing OutOfMemoryErrors.
But in Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects.
Garbage collector is best example of Daemon thread as it is always running in background.
Main objective of Garbage Collector is to free heap memory by destroying unreachable objects.

435
Q

What is composition?

A

It signals a has a relationship between classes and not a is a relationship. A computer has a motherboard and not a car is a vehicle. It is how you construct a class from several smaller classes.