Fundamentals Flashcards

1
Q

Methods to Take Input in Java

A

BufferedReader Class
Scanner Class

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

Using BufferedReader Class for String Input In Java

A

It is a simple class that is used to read a sequence of characters. It has a simple function that reads a character another read which reads, an array of characters, and a readLine() function which reads a line.

InputStreamReader() is a function that converts the input stream of bytes into a stream of characters so that it can be read as BufferedReader expects a stream of characters. BufferedReader can throw checked Exceptions.

// Creating BufferedReader Object
// InputStreamReader converts bytes to
// stream of character
BufferedReader bfn = new BufferedReader(
new InputStreamReader(System.in));

    // String reading internally
    String str = bfn.readLine();
 
    // Integer reading internally
    int it = Integer.parseInt(bfn.readLine());
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Using Scanner Class for Taking Input in Java

A

It is an advanced version of BufferedReader which was added in later versions of Java. The scanner can read formatted input. It has different functions for different types of data types.

The scanner is much easier to read as we don’t have to write throws as there is no exception thrown by it.
It was added in later versions of Java
It contains predefined functions to read an Integer, Character, and other data types as well.

Scanner scn = new Scanner(System.in);
Integer: nextInt()
Float: nextFloat()
String : next() and nextLine()
// Scanner definition
Scanner scn = new Scanner(System.in);

    // input is a string ( one word )
    // read by next() function
    String str1 = scn.next();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Important Points About Java Scanner Class

A

To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.

To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()

To read strings, we use nextLine().

To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.

The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example, Suppose there is an input string: How are you

In this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods.

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

Difference between print() and println() in Java

A

print(): doesnt add next line, works with arguments

println(): add new line after, can work withour aguments

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

Need of Wrapper Classes in Java

A

Firstly the question that hits the programmers is when we have primitive data types then why does there arise a need for the concept of wrapper classes in java. It is because of the additional features being there in the Wrapper class over the primitive data types when it comes to usage. These methods include primarily methods like valueOf(), parseInt(), toString(), and many more.

A wrapper class wraps (encloses) around a data type and gives it an object appearance. Wrapper classes are final and immutable. Two concepts are there in the wrapper classes namely autoboxing and unboxing.

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

Autoboxing and unboxing

A

Autoboxing is a procedure of converting a primitive value into an object of the corresponding wrapper class. For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value is:

Passed as a parameter to a method that expects an object of the corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.

Unboxing is a procedure of converting an object of a wrapper type to its corresponding primitive value. For example conversion of Integer to int. The Java compiler applies to unbox when an object of a wrapper class is:

Passed as a parameter to a method that expects a value of the corresponding primitive type.
Assigned to a variable of the corresponding primitive type.

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

Now let us land on discussing the useful features of wrapper classes, they are listed as follows:

A

They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).

The classes in java.util package handles only objects and hence wrapper classes help in this case also.

Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.

An object is needed to support synchronization in multithreading.

One of the major important features provided by wrapper classes is a lot of utility methods. Say when we have a float value, and we want to find the integer value of that float, then we have a specific method for that which is depicted from the illustration given below.

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

We can use two ways to construct the instance of the Wrapper Classes

A

Using the constructor of the wrapper class
Using the valueOf() method provided by the Wrapper classes
Using concept of AutoBoxing

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

The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class. It is used to restrict a user in Java.

The following are different contexts where the final is used:

A

final variable- is constant
final method- prevent method overriding
final classes- prevent inheritance

Initialization: Final variables must be initialized either at the time of declaration or in the constructor of the class. This ensures that the value of the variable is set and cannot be changed.

Performance: The use of a final can sometimes improve performance, as the compiler can optimize the code more effectively when it knows that a variable or method cannot be changed.

Security: The final can help improve security by preventing malicious code from modifying sensitive data or behavior.

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

static Keyword in Java

A

The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class. The static keyword is used for a constant variable or a method that is the same for every instance of a class.

The static keyword is a non-access modifier in Java that is applicable for the following:

Blocks
Variables
Methods
Classes

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

Characteristics of static keyword

A

Shared memory allocation: Static variables and methods are allocated memory space only once during the execution of the program. This memory space is shared among all instances of the class, which makes static members useful for maintaining global state or shared functionality.

Accessible without object instantiation: Static members can be accessed without the need to create an instance of the class. This makes them useful for providing utility functions and constants that can be used across the entire program.

Associated with class, not objects: Static members are associated with the class, not with individual objects. This means that changes to a static member are reflected in all instances of the class, and that you can access static members using the class name rather than an object reference.

Cannot access non-static members: Static methods and variables cannot access non-static members of a class, as they are not associated with any particular instance of the class.

Can be overloaded, but not overridden: Static methods can be overloaded, which means that you can define multiple methods with the same name but different parameters. However, they cannot be overridden, as they are associated with the class rather than with a particular instance of the class.

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

Static blocks

A

If you need to do the computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded.

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

Static variables

A

When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.

Important points for static variables:

We can create static variables at the class level only.

static block and static variables are executed in the order they are present in a program.

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

Static methods

A

When a method is declared with the static keyword, it is known as the static method. The most common example of a static method is the main( ) method. As discussed above, Any static member can be accessed before any objects of its class are created, and without reference to any object. Methods declared as static have several restrictions:

They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.

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

enum in Java

A

In Java, Enumerations or Java Enum serve the purpose of representing a group of named constants in a programming language. Java Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. The set of constants in an enum type doesn’t need to stay fixed for all time.

17
Q

What is Enumeration or Enum in Java?

A

A Java enumeration is a class type. Although we don’t need to instantiate an enum using new, it has the same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just like classes, you can give them constructors, add instance variables and methods, and even implement interfaces.

18
Q

transient keyword in Java

A

transient is a variables modifier used in serialization. At the time of serialization, if we don’t want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type.

19
Q

Serialization

A

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.

transient keyword plays an important role to meet security constraints. There are various real-life examples where we don’t want to save private data in file. Another use of transient keyword is not to serialize the variable whose value can be calculated/derived using other serialized objects or system such as age of a person, current date, etc.

Practically we serialized only those fields which represent a state of instance, after all serialization is all about to save state of an object to a file. It is good habit to use transient keyword with private confidential fields of a class during serialization.

20
Q

volatile Keyword in Java

A

Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem. Consider the below example.

Suppose that two threads are working on SharedObj. If two threads run on different processors each thread may have its own local copy of sharedVariable. If one thread modifies its value the change might not reflect in the original one in the main memory instantly. This depends on the write policy of cache. Now the other thread is not aware of the modified value which leads to data inconsistency.

21
Q

Access Modifier in Java

A

Public vs
Protected vs
Package vs
Private

22
Q

Modifier 1: Public Access Modifiers

A

If a class is declared as public then we can access that class from anywhere.

In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B’s main method we create an object of type class A and trying to access the data of method m1.

23
Q

Modifier 2: Protected Access Modifier

A

This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface.

A member is declared as protected as we can access that member within the current package and only in the child class of the outside package.

24
Q

Modifier 3: Private Access Modifiers

A

This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructors, methods, and fields inside the classes.

If a variable or methods or constructor is declared as private then we can access them only from within the class i.e from outside the class we can’t access them.

25
Q

Modifier 4: Package(Default) Access Modifier

A

A class or method or variable declare without any access modifier then is considered that it has a package(default)access modifier The default modifier act as public within the same package and acts as private outside the package. If a class is declared as default then we can access that class only within the current package i.e from the outside package we can’t access it. Hence, the default access modifier is also known as the package–level access modifier. A similar rule also applies for variables and methods in java.

26
Q

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 :

Extending the Thread class

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.

27
Q

Another method to create a thread

A

Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.

28
Q

Thread Class vs Runnable Interface

A

If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.

We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.

Using runnable will give you an object that can be shared amongst multiple threads.

29
Q

Lifecycle and States of a Thread in Java

A

New State
Runnable State
Blocked State
Waiting State
Timed Waiting State
Terminated State

30
Q

Synchronization in Java

A

Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results.

Java Synchronization is used to make sure by some synchronization method that only one thread can access the resource at a given point in time.

Java provides a way of creating threads and synchronizing their tasks using synchronized blocks.

A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object and can only have one thread executed inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.

31
Q

Types of Synchronization

A

There are two synchronizations in Java mentioned below:

Process Synchronization
Thread Synchronization
1. Process Synchronization in Java
Process Synchronization is a technique used to coordinate the execution of multiple processes. It ensures that the shared resources are safe and in order.

  1. Thread Synchronization in Java
    Thread Synchronization is used to coordinate and ordering of the execution of the threads in a multi-threaded program. There are two types of thread synchronization are mentioned below:

Mutual Exclusive
Cooperation (Inter-thread communication in Java)

32
Q

Common Network Protocols

A

Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows secure communication between different applications. TCP is a connection-oriented protocol which means that once a connection is established, data can be transmitted in two directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent, making it a complete protocol for transporting information like still images, data files, and web pages.

User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less protocol that allows data packets to be transmitted between different applications. UDP is a simpler Internet protocol in which error-checking and recovery services are not required. In UDP, there is no overhead for opening a connection, maintaining a connection, or terminating a connection. In UDP, the data is continuously sent to the recipient, whether they receive it or not.

33
Q
A