Java Notes

1) What all datatypes you know in java?

->  Data type specify the size and value that can be store in variable.

    DataType are divided into two group :

   - Primitive datatypes include byte,short,int,long,float,double and char.

   - Non Primitive datatypes include String,Arrays,Classes and Interfaces.ss


2) Can you give size required for each datatype?

-> 

    DataType   Size   Description

   -byte     1 byte       Stores whole numbers from -128 to 127

   -short     2 bytes       Stores whole numbers from -32,768 to 32,767

   -int     4 bytes       Stores whole numbers from -2,147,483,648 to 2,147,483,647

   -long     8 bytes       Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

   -float     4 bytes       Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

   -double      8 bytes       Stores fractional numbers. Sufficient for storing 15 decimal digits

   -boolean     1 bit       Stores true or false values

   -char     2 bytes       Stores a single character/letter or ASCII values


3) What is default value of byte short int float long double boolean char?

-> 

   byte = 0, short = 0, int = 0, long = 0, float = 0.0, double = 0.0, boolean= false, char = single space.


4) Is string datatype?

-> 

  - No its a inbuilt class in java.

  - it in java.lang *package.it has method like length(),trim(),concat(),append() etc.

  - String is used to store sequnce of character.

  - we can create a string variable directly like any other variables as −

    String s = "myString";

    (or)

  - By instantiating the string class using the new keyword as −

    String s = new String("myString");


5) Can you define class?

-> 

  - A class in Java is a logical template to create objects that share common properties and methods.

  - Hence, all objects in a given class  will  have the same  methods or properties.

  - For example: in the real world, a specific cat is an object of the “cats” class. 

  - All cats in the world share some characteristics from the same template such as being a feline, having a tail, or being the coolest of all animals.

 

6) Can you define Object?

->

  -  object is an instance of a class, meaning it is a copy of a specific class. 

  -  Java objects have three primary characteristics: identity, state, and behavior.

  -  we create object in java by using new operator.

  -  To introduce any real world object in programing use class.

  -  object is required memory execution.

  -  object is collection of data and method.

  -  syntax : className refvariable = new className();

  

7) Can you list out some in built classes in java?

-> String - trim(), length(), charAt(), 

   System - 

   Thread - run(),sleep(),start()

   Stringbuffer - insert(),reverse(),delete()

   StringBuilder -append(),replace()

   InputStream - read()

   OutputStream - write ()

   Reader - read(), close(),skip()

   Writer -  write(),close(),flush()

   Object - hashcode(),equal(),clone(),wait(),notify()

   Scanner - nextLine(),next(),nextInt(),nextDouble(),nextShort().

   

   

 8)  What is difference between global and local variable? tell me any 3 to 4 differences.

-> 

  - global variable : it declare the inside a class without using the static keyword but outside of all method,constructor,block.

                     -it is store in the heap memory.

                     -when object are created instance variable are created and for each object a seprate copy of instance variable is created.

                     -the scope of inside instance methods,constructor and block within a class directly and outside a class using the object.

                     -when object is destroyed associated instance variable are destroyed.


  - Local variable : it is declare the inside method parameter and inside method body.

                   - it is store in the stack memory.

                   - when method is called local variable are created.

                   - the scope of inside method body only, outside a method body we can not use local variable.

                   - when method execution is completed local variable are destroyed.


9) Can class be a return type of any method?

-> Yes,

  - A method can have the class name as its return type. 

  - Therefore it must return the object of the exact class or its subclass. 


10) What is block in java? What is its syntax? When is it getting executed?

->

  - java program is a combination of single statements that should be executed sequentially. 

  - In some cases, if we want to use more than one statement to represent a unit of work, we can create a block statement by placing all related statements 

    inside braces, which would be  treated as a single statement.

  - Whenever we load class in memory that time static block will get executed and non staic block will get executed before constructor.

               

11) What is super class of all classes in java?

->

  - The Object class is the superclass of all other classes in Java and a part of the built-in java. lang package. 

  - it has method like toString(),clone(),hashcode(),getclass() etc.


12) Do you know some methods in Object class ? Can you name some of them?

-> 

   - getClass() : Used to get the runtime class of this Object. 

   - hashCode() : Used to get a hash code value for the object. 

   - notify() : It is used to give the notification for only one thread which is waiting for a particular object. 

   - notifyAll() : It is used to give the notification to all waiting threads of a particular object.

   - toString() : It is used to return a string representation of this thread.s

   - wait() : marks the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

   - clone() : Used to create and return a copy of this object.

   - equals(Object obj) : Used to indicate whether some other object is "equal to" this one.

   - finalize() : garbage collector calls this method on an object when it determines that there are no more references to the object. 


13) What is package and import keyword?

->   Package :

   - package keyword is used to group certain classes and interface under one package .

   - It makes things easier for other programmers as they can easily locate related classes.

   - Maintenance : If any developer has newly joined a company, he can easily reach the files needed.

   - Reusability : A common code can be placed in a common folder so that everybody can check that folder and use it.

   - Java package removes naming collision.

     import :

   - import keyword is used include/use the classes and interface from a package in the current program.

   - When we want to use one class in another class we must use the import statement. 

   - import is used to call classes from another package.

   - this  statement we need to write after package statement.


14) Can we give fully qualified class name instead of importing that class? If yes how to do that?

-> yes,

   - because ,If you use fully qualified name then only declared class of this package will be accessible. 

        -  Now there is no need to import.

        -  But you need to use fully qualified name every time when you are accessing the class or interface.


15) What are access modifiers / access specifiers available in java? Explain each of them in details?

->  

       Java Access Specifiers (also known as Visibility Specifiers) regulate access to classes, fields and methods in Java.

  -public : It can be applied to constructor, global variables, static variables, methods, inner classes or outer classes.

            Public members are accessible everywhere, in same class, outside the class, or any package.

            Local variables cannot be public as they already have a scope within the method.


  -private : A class cannot be private.

             Private access specifier can be applied to global variable, method, constructor and inner class only

             Local variables cannot be private but global variables can be private

             Private members can be accessed only within the enclosed brackets


  -Default : When an access specifier is not specified to members of a class, then it is called default.

             Default members can be accessible only within same package or folder.

             Default can be applied to constructor, global variable, local variable, methods, inner classes, outer classes etc.

             Default is a keyword in java. We may mistakenly think that it is an access specifier, but it actually is for a switch statement.

  

 -Protected :It can be applied to constructor, global variable, methods.

             It cannot apply to outer classes, but can be applied to inner classes

             It cannot apply to the local variable

             Protected members are accessible within same package and another package of its subclass only. 

             Inheritance must be there, the caller of protected members is the subclass of protected member’s class.


16) Can you elaborate protected access specifier in java?

-> The protected access specifier in Java allows members to be accessed within the same class, subclasses, and classes in the same package.


17) What is encapsulation? explain in brief?

->  

  -Encapsulation means binding of data into a single entity.

  -by default in java we get encapsulation.

  -encapsulation can be achieved by using private global variable and accessing those variables through getter and setters.


18) Why global variables are recommended to be private?

-> If you make private no one can call those directly and assing invalid value.. we should be accessing it through one method so that we can add some validation 

   if needed.


19) Can you give me any real time example of encapsulation?

->

  -An example of encapsulation in the real world is a car engine. 

  -The inner workings of the engine, such as the combustion process, are encapsulated within the engine block and are not visible to the outside world.

  -The driver only has access to the controls, such as the gas pedal and steering wheel, which provide an interface for interacting with the engine.


20) Explain Inheritance briefly.

->

   -Inheritance is an important pillar of OOP(Object-Oriented Programming). 

   -It is process where one class inherite the properties of other class.

   -Inheritance means creating new classes based on existing ones.

   -A class that inherits from another class can reuse the methods and fields of that class. 

   -we can implement is a relationship in java by using extends keyword.


21) Give real time example of Inheritance.

-> Example :

   car, bus, bike – all of these come under a broader category called Vehicle. 

      That means they’ve inherited the properties of class vehicles, i.e., all are used for transportation. 


22) What are types of inheritance?

->  They are Five type of Inheritance:

   1) Single level Inheritance : Only one class is derived from the parent class. 

   2) Multi-level Inheritance : One class inherits the features from a parent class and the newly created sub-class becomes the base class for another new class.

   3) Hierarchical Inheritance : The type of inheritance where many subclasses inherit from one single class is known as Hierarchical Inheritance. 

   4) Multiple Inheritance : Multiple inheritances is a type of inheritance where a subclass can inherit features from more than one parent class. 

   5) Hybrid Inheritance : Hybrid inheritance is a combination of more than two types of inheritances single and multiple.


23) Can you explain advantages of Inheritance?

-> 

  1. Reusability : Inheritance help the code to be reused in many situations. 

  2.Save time and effort : reusability achieved by inheritance saves the programmer time and effort. 

                           Since the main code written can be reused in various situation as needed.

  3.Data hiding : the base class can decide to keep some data private so that it cannot be altered by the derived class.

  4.Extensibility : it  extensibility the base class logic as per business logic of thederived class.

  5.Easy to understand : It's easy to understand large program with use of inheritance.

  6.Maintainability : It is easy to debug a program when divided in parts. Inheritance provides an opportunity to capture the program.


24) Why multiple Inheritance not supported in case of classes but in case of interfaces?

-> 

   - Multiple inheritance is not supported in the case of class because of ambiguity.

   -However, it is supported in case of an interface because there is no ambiguity. 

   -It is because its implementation is provided by the implementation class.


25) What is multilevel inheritance?

-> One class inherits the features from a parent class and the newly created sub-class becomes the base class for another new class.


26) What is dynamic dispatch?

-> Super class referance variable can store sub class object.


27)  Can we assign subclass to super class and what  will happen if we do that? at compile time and runtime?

->   When you assign the subclass object to the superclass reference variable and, using this reference if you try to access the members of the subclass a 

     compile-time error will be generated.


28) Can private variables or methods inherit?

->  Cannot inherit the private variable or method,because priavate member access only within the class.


29) Explain super keyword and its syntax?

-> 

   -The super keyword refers to superclass (parent) objects. 

   -It is used to call superclass methods, and to access the superclass constructor. 

   -if subclass instance variable and super instance variable name same then use super keywords in subclass to differntiate them.

    syntax: super.methodName().


30) Explain this keyword and its syntax?

->  

  - The this keyword refers to the current object in a method or constructor.

  - this keyword is used to differntiate between local variable and instance variable if the both variable are same.

  - we can use this keyword inside a instance method  and inside a constructor only.

  - we cannot use this keyword inside a static method or static block.


31) Do you know rule for writing super(),this() in a program?

-> 

  -if you call this() or super() in a constructor, it must be the first statement.

  -The Sun compiler says, call to super must be first statement in constructor . 

  -The Eclipse compiler says, Constructor call must be the first statement in a constructor .

  -At time one can use.but not both simultanusly.


32) What is constructor in java.

->

  - Constructor is having same name as a class name, look like a method but does not have return type called as constructor.

  - if we did not write any constructor in class, the JVM will add automatically default constructor.

  - if we write any type of constructor the JVM will be no add.

  - Constructor will get called automatically when object is created.

  - For each object constructor will be executed only once.

  - we can have public ,private, protected and default constructor in java.

  - we can not be constructor final, abstract and static.

  - if we want to execute the anything the before method we can write that code inside the constructor.

  - Constructor are two type :

    1)Default Constructor : When default Constructor is executed instance variable will be initialized with default value.

                           -When it doesnt have any parameter.

    2)Parametrized Constructor : When parameterized Constructor is executed instance variable will be initialized with parameterized value.

                               - Constructor which has a specific number of parameters is called a parameterized constructor.

     Use :The  parameterized constructor used to provide different value to ditinct object .we can provide same value also.


33) Can we call one constructor from another constructor?

-> yes

  -By using this() keyword: It is used when we want to call the current class constructor within the same class. 

  -By using super() keyword: It is used when we want to call the superclass constructor from the subclass.


34) What will happen if we make constructor private?

->  

   - we can't create an object of the class, except within the class. 

   - A private constructor is used when we want to limit the way objects of a class are instantiated.


35) What are the ways to call constructors?

->

  - Constructors are call the three wayes :

     - by using the new keyword.

     - super() is used to call the parent class's constructor. 

     - this() is used when a single class has multiple constructors to help re-use code.


36) How many constructors we can have in a program? If more than one allowed. What care we need to take?

-> 

  -we can create multiple constructer in program with different type of parameter, so then we called constructor overloading.

  -if we are create multiple constructor in class, then we need to take there should be different parameter.


37) Define polymorphism? 

-> 

  - Polymorphism means many form.

  - the process of providing multiple implementation to a method to perform one operation based on sub-type or based on parameter type is called as polymorphism.

  - we can see polymorphosm in java at compile time and runtime.

  - compile time polymorphism is also called as method overloading and runtime polymorphism is called method overriding.


38) Give real time example of polymorphism.

->  Consider a person, who can have multiple characteristics at a time, the person can be a father, a son, and an employee at the same time. 


39) What is method overloading ? explain in detail all rules.

-> 

  - if the class is having multiple method with same name but different argument list.

  - Two or more method is having same name.

  - method with different argument list.

    - Number of argument can be different.

    - Sequence of arguments can be different.

    - Type of arguments can be different.

    - return type anything.

    - access specifier anything.


40) What is method overriding ? explain in detail all rules

-> 

  - If subclass  has the same method as declared in the super  class, it is known as method overriding in Java. 

  - Re-defining parent class method in the child class called as method.

  - Rule : Method must have the same name as in the parent class.

           method must have the same parameter as in the parent class.

           the must be inheritance relationship.

           method overriding occurs in two classes that having parent child relationship.


41) What is @Override annotation?

->

  -@Override is the annotation which is used to make compiler check all the rules of overriding.  

  -If this annotation is not written, then the compiler will apply all overriding rules only .

  -if the superclass and subclass relation exist

  -method name same.

  -the parameters of both methods are same.

  -But, if we write @Override on subclass method, then the compiler must apply all rules, irrespective of the above three points.


42) Can we override static method?

-> 

 - Static methods cannot be overridden since they are bonded at compile time and method overriding relies on dynamic binding at runtime.


43) Can we override constructors?

->  constructors cannot be overridden in the same way that methods can be overridden. 

    Overriding a method means providing a different implementation of the method in a subclass, while maintaining the same method signature (name, return type, 

    and parameters).


44) Can we override final methods?

->

  -We cannot override the final method in java. 

  -If we try to override the final method in java, we get a compilation .


45) Can constructor be overloaded?

-> yes.


46) What is static keyword in java?

-> 

  -Static is a keyword used for memory management.

  -Static means single copy storage for variable or method.

  -Static keyword can be applied to variables, methods, inner class and blocks.

  -static member are called by class name directly.

  -we can not call non static members from static member directly.we need to create a object of class.

  -Static members belongs to class rather than instance of class.

  -Static variables also called as class variable.

  -Static method can not be overriden, as it is class level methods.


47) Can local variable be static?

-> static local variables are not allowed in Java. 

  -Static variables have to be declared at class level and cannot be declared at method level.

  -for local variables even we can not provide any access specifiers.


48) What is difference between instance variable and static variables?

-> 

   Instance Variable: it declare the inside a class without using the static keyword but outside of all method,constructor,block.

                     -it is store in the heap memory.

                     -when object are created instance variable are created and for each object a seprate copy of instance variable is created.

                     -the scope of inside instance methods,constructor and block within a class directly and outside a class using the object.

                     -when object is destroyed associated instance variable are destroyed.

   Static Variable:  it declare the inside a class using static keyword but outside of all method,constructor,block.

                    -it is store in the class or method area.

                    -when .class file loaded in JVM memory static variable are created and for all object a single copy of static variable is created.

                    -The scope inside all method, constructor and block within a class directly and outside a class using object and className.

                    -when .class is unloaded from JVM static variable are destroyed.


49) Do you know static block in java? When is it getting executed?

->

   - The static block is stored in the memory during the time of class loading.

   - and before the main method is executed, so the static block is executed before the          

   main method. 


50) Can constructor be static?

-> No,

    -because, Constructor are intialize the instannce variable.

    -construction is used for creating an object and it is related to objects not class.

    -Static is belong to class.


51) Can we call static method and variables with object? Why it’s not preferrable?

-> Yes,

   -because,static is belong to the whole class.


52) What is final keyword in java?

->

  -final means constant, means can not be changed.

  -Final keyword can be applied to variable, method and class. final member cannot be changed.

  -A variable that is declared as final and not initialized is called a blank final variable.

  -A blank final variable forces the constructors to initialize it.

  -Java classes declared as final cannot be extended. Restricting inheritance.

  -Final parameters - values of the parameters cannot be changed after initialization.s

  -Final method – can not be overridden.


53) What will happen if class is final?

-> Java classes declared as final cannot be extended. Restricting inheritance.


54) What will happen if method is final?

-> When a method is declared as final, it cannot be overridden by a subclass.


55) What will happen if variable is final?

-> When we declare a variable as final, its value cannot be changed.


56) Can local variable be final? in java

-> When final is applied to a local variable,we can not be change the value.


57) What is abstraction in java.

->  The process of hiding the implementation detials from the user, only the essential functionality will be provided to the user.

   -The user will have the information on what the object does insted of how it does.

   -Example :ATM  we can see the different functionality option (withdraw, check balance, change PIN etc). Provided on ATM screen but can't see the actual 

    program developed to run these functionalities.


58) How to achieve abstraction? Explain in detail?

->   There are two way achive to abstraction in java.

    -Abstract class : abstract classes, we can have abstract methods as well as concrete methods.

    -Interface : By using the interface we can achive 100% abstraction.


59) Can you explain interface at least 4 points about it?

-> 

  - Interface like class, an interface is used to represent real world entities.

  - interface are similar to abstract class but having all the method of abstract type.

  - interface are the blueprint of the class.it specify what a class must do and not how.

  - we cannot create object of interface.

  - by using interface we can achive 100% abstraction.

  - All variable are always public, static, final.

  - interface cannot contain instance variable.

  - interface does not contain any constructor.

  - interface is fully unimplemented class. 

  - we can acheive

  

60) Can you explain abstract class at least 4 points about it?

-> 

  - class which contain the abstract keyword declaration it is known as abstract class.

  - By using abstract class we can achive partial abstraction.

  - we can achive 0-100% abstraction using abstract class.

  - abstract classes may or may not contain abstract methods.

  - if we inherite abstract class we have to provide implementation to all the abstrct method in child class.

  - we can't create object of abstract class.

  - we can achive multiple inheritance through interface because interface contains only abstract method which implementation is provided by the subclass.


61) Can you list out difference between interface and abstract class in java? at least 4.

->                                                    

 1) Abstract class can have abstract and non-abstract methods.Interface can have only abstract methods. Since Java 8, it can have default and static methods also.

 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

 3) Abstract class can have final, non-final, static and  non-static variables. Interface has only static and final variables.

 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.

 5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

 6) An abstract class can extend another class and implement multiple Java interfaces. An interface can extend another Java interface only.

 7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".

 8) abstract class can have class members like private, protected, etc. Members of a interface are public by default.

 9)Example:                                                               

public interface Drawable{

void draw();

}

Example:

abstract Drawable{

void draw();

}


62) What is garbage collection concept in java? Explain.

-> 

 -GC means destroying a memomry.

 -

 -its not guaranted.

 -GC is used  for remove the unused object.

 -In java use System.gc()for advising a JVM to run gc.

 -before gc in java finalize method will get called if you override.


63) How to advise or suggest garbage collection to happen?

-> While a developer can never actually force Java garbage collection, there are ways to make the JVM prioritize memory management functions. In review, five ways

   to try and force

   Java garbage collection are:

  -Call the System.gc() command.

  -Call the getRuntime.gc() command.

  

64) Explain System.gc().

->  -The gc() method is used to invoke the garbage collector to perform cleanup processing. 

          -The gc() is found in System and Runtime classes.


65) What is use of finalize method?

-> -finalize() is used garbage collection.

   -Finalize() is the method of Object class. 

   -This method is called just before an object is garbage collected. 

   -This method can be used to perform cleanup processing. 


66) What is difference between final , finally and finalize?

->

  -Final:The ‘final’ keyword in Java is used to create a constant or non-modifiable variable, method, or class.

         -It can be applied in three different contexts:  

         -When a variable is declared as final, its value cannot be changed after it is initialized. 

         -A final method cannot be overridden by a subclass. This is useful when you want to prevent any further modification of a method in a class hierarchy.

         -A final class cannot be extended or subclassed. This is often used for creating immutable classes.

  

  -Finally: The ‘finally’ keyword is used in exception handling, specifically with try-catch blocks. 

           -A ‘finally’ block will always be executed, regardless of whether an exception is thrown or not. 

           -This makes it ideal for cleanup tasks, like closing resources such as files or database connections.

 

 -Finalize: The ‘finalize()’ method is a special method in Java that is called by the garbage collector just before an object is reclaimed. 

           - This method can be overridden to perform cleanup tasks before an object is destroyed. 

           - However, its use is not recommended, as there is no guarantee when or if the garbage collector will call the ‘finalize()’ method.

           - Instead, you should use other mechanisms like ‘try-with-resources’ or explicit resource management for cleanup tasks.


67) How to read file in java? Can you write a program?

-> the process of set the path then crate the folder after createfile in folder.then write a data by using the filewriter method.after read the the file by using 

   the filereader. 


  package com.Filehandling;

  import java.io.BufferedReader;

  import java.io.BufferedWriter;

  import java.io.File;

  import java.io.FileReader;

  import java.io.FileWriter;


   public class FileReading {

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


    // create the file path

File file = new File("test.txt");

String path = File.getAbsolutePath();

System.out.println(file.getAbsoluteFile());

//create the folder

                 File dir = new File("ABC");      

                 boolean iscreated = dir.mkdir();

                 System.out.println(iscreated);

       

       //create the file

        File file1 =new File(dir,"Test.txt");

        boolean fileIsCreated=file1.createNewFile();

        System.out.println(fileIsCreated);

            

        //Data Writer

   File dir1 = new File("JBK");

   File file11 = new File(dir1,"Test.text");

    FileWriter fw = new FileWriter(file11,true);

    BufferedWriter bfw = new BufferedWriter(fw);

fw.write(65);

fw.write("\n");

fw.write("JBK");

fw.close();

System.out.println("data store !!!");

//File reading

File dir11 = new File("JBK");

File file111 = new File(dir11,"Test.txt");

FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);

String line = br.readLine();

while(line != null) {

line = br.readLine();

System.out.println(line);

}

char[] arr = new char[(int)file.length()];

fr.read(arr);

for(char c: arr) {

System.out.println(c);

}

}

}

     

68) How to write text file in java? Can you write a program?

->  the process of set the path then crate the folder after createfile in folder.then write a data byusing thefilewriter method.


package com.Filehandling;

  

  import java.io.File;

  import java.io.BufferedWriter;

  import java.io.FileWriter;


   public class FileReading {

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


    // create the file path

File file = new File("test.txt");

String path = File.getAbsolutePath();

System.out.println(file.getAbsoluteFile());

//create the folder

                 File dir = new File("ABC");      

              boolean iscreated = dir.mkdir();

                System.out.println(iscreated);

       

       //create the file

    File file1 =new File(dir,"Test.txt");

        boolean fileIsCreated=file1.createNewFile();

        System.out.println(fileIsCreated);

  //Data Writer

   File dir1 = new File("JBK");

   File file11 = new File(dir1,"Test.text");

    FileWriter fw = new FileWriter(file11,true);

    BufferedWriter bfw = new BufferedWriter(fw);

fw.write(65);

fw.write("\n");

fw.write("JBK");

fw.close();

System.out.println("data store !!!");

}

}


69) What is difference between fileinputstream and fileoutputstream?

-> 

   FileInputstream :This class reads the data from a specific file (byte by byte). 

                   -It is usually used to read the contents of a file with raw bytes, such as images.

   Fileoutputstream:This writes data into a specific file or, file descriptor (byte by byte). 

                   -It is usually used to write the contents of a file with raw bytes, such as images.


70) What is stream in java? Can you define?

->

     -Stream is continuous flow of bytes which makes input and output operations feasible and faster. 

     -It is called stream because it facilitates a continuous flow of data. 

     -An Input/Output stream is an input source or output destination which represents various types of sources. 

     -Java uses the concept of stream to make I/O operation fast. 

     -All the classes required for I/O operation are given  in java.io package.


71) What are types of streams ? explain character and byte stream?

-> They are two type :

   1)Byte stream is used to perform input and output operations of 8-bit bytes. 

   2)Character stream is used to perform input and output operations of 16-bit Unicode.


72) what is use of file class in java?

-> File class is inbuilt class.

  -it is used for the file handling.

  -it is used for getting path or renameing a file deleting file.

  -it is method of exist(),rename().


73) What is serialization?

-> Serialization is a mechanism of converting the state of an object into a other source is called serialization.

   - it use for the transfer data in different systems.


74) What is deserialization?

-> Deserialization is the reverse process where the we read serialize the file and convert it to object.


75) What is difference between Array and Collection?

->

  1)Size : Arrays are fixed in size i.e once the array with the specific size is declared then we can't alter its size afterward.

           The collection is dynamic in size i.e based on requirement size  could be get altered even after its declaration.

  2)Memory Consumption: Arrays due to fast execution consumes more memory and has better performance.

                        Collections, on the other hand, consume less memory but also have low  performance as compared to Arrays.

  3)Data type : Arrays can hold the only the same type of data in its collection i.e only homogeneous data types elements are allowed in case of arrays.

                Collection, on the other hand, can hold both homogeneous and heterogeneous elements.

  4)Primitives storage : Arrays can hold both object and primitive type data. 

                         On the other hand, collection can hold only object types but not the primitive type of data.

  5)Performance: Arrays due to its storage and internal implementation better in performance. 

                  Collection on the other hand with respect to performance is not recommended to use.


76) What is difference between Arraylist and Vector and LinkedList?

-> 

  1) ArrayList: The ArrayList extends the AbstractList and implements the List interface. 

              - It is usually slower than the other arrays, but is useful where you need to manipulate a lot in programs.

              - Uses Dynamic array for storing the elements.

              - Duplicate elements are allowed.

              - Maintains insertion order.

              - Methods are not synchronised.

              - Random access as it works on index basis.

              - Manipulation is slow because lot of shifting needs to be done.This means that if the ArrayList has 1000 elements and we remove the 50th element, 

                then the 51st element tries to acquire that 50th position and likewise all elements. So, moving every element consumes a lot of time.

 

  2) Vector: The vector class ‘implements a growable array of objects.Similar to an array, it contains components that can be accessed using an integer index'.

           - The vector may expand or contract as per the requirements.

           - All methods are synchronised.

           - It is slower than an Arraylist.

           - Vector is thread-safe as it has synchronised methods.

           - It has capacity concept. The default capacity is 10.

           - It doubles when it reaches its threshold.

           - Size methods returns the number of elements present.

           - Capacity method returns the capacity which doubles after reaching the default capacity, which is 10.

           - Vector can be iterated by simple for loop, Iterator, ListIterator and Enumeration.


  3) LinkedList: LinkedList class uses a doubly linked list to store the elements.It provides a linked-list data structure.

               - It inherits the AbstractList class and implements List and Deque interfaces.

               - LinkedList class can contain duplicate elements.

               - LinkedList class maintains insertion order.

               - LinkedList class is non synchronized.

               - LinkedList class, manipulation is fast because no shifting needs to occur.

               - LinkedList class can be used as a list,stack or queue.


77) What is difference between ArrayList and HashSet?

->   ArrayList implements List interface while HashSet implements Set interface in Java.

    -ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order.

    -ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.


78) What is difference between List , Set and Map?

->  The list maintains insertion order. Set do not maintain any insertion order. The map also does not maintain any insertion order. 

   -The list interface allows duplicate elements.Set does not allow duplicate elements. The map does not allow duplicate elements.

   -We can add any number of null values. But in set almost only one null value. The map allows a single null key at most and any number of null values.


79) Can u iterate arraylist by using Iterator? Explain in with program.

->  

     The iterator can be used to iterate through the ArrayList where in the iterator is the implementation of the Iterator interface. Some of the important 

     methods declared by the  Iterator interface are hasNext() and next().


     import java.util.ArrayList;  

  public class ArrayListIteratorExample1  

    {  

  ArrayList<String>arrlist = new ArrayList<String>();  

  arrlist.add("d");  

  arrlist.add("dd");  

  arrlist.add("ddd");  

  arrlist.add("dddd");  

  arrlist.add("ddddd");  

  System.out.println(arrlist);    // [d, dd, ddd, dddd, ddddd]  

  

  Iterator<String> iterator = arrlist.iterator();  

  while (iterator.hasNext())  

    {  

  String i = iterator.next();  

  System.out.println(i);  

  

    }  

    }  


80) Can u iterate arraylist by using ListIterator? Explain in with program.

->  ArrayList class is used to return a list iterator over the elements in this list (in proper sequence). 


          import java.util.ArrayList;  

    public class ArrayListListIteratorExample1  

         {  

    ArrayList<String> arrlist = new ArrayList<String>();  

    arrlist.add("d");  

    arrlist.add("dd");  

    arrlist.add("ddd");  

    arrlist.add("dddd");  

    arrlist.add("ddddd");  

    System.out.println(arrlist);    // [d, dd, ddd, dddd, ddddd]  

  

    ListIterator<String> iterator = arrlist.listIterator(2);  

    while (iterator.hasNext())  

          {  

    String i = iterator.next();  

    System.out.println(i);  

          }  

          }  


81) Can u iterate arraylist by using for each? Explain in with program.

->  

       The forEach() method is not the same as the for-each loop. We can use the Java for-each loop to iterate through each element of the arraylist.

       

       import java.util.ArrayList;

   class Main {

        public static void main(String[] args) {

        // create an ArrayList

        ArrayList<Integer> numbers = new ArrayList<>();

   

   // add elements to the ArrayList

       numbers.add(3);

       numbers.add(4);

       numbers.add(5);

       numbers.add(6);

       System.out.println("ArrayList: " + numbers);

   System.out.print("Updated ArrayList: ");


       // multiply each element by themselves

      // to compute the square of the number

      for(int e:number){

              System.out.println(e);


  }

}


82) Can u iterate HashMap ? Explain in with program.

-> yes,using for loop

   

   import java.util.HashMap;

   import java.util.Map;

    

   public class GFG {

    public static void main(String[] args)

      {

        Map<String, String> foodTable= new HashMap<String, String>();

        foodTable.put("A", "Angular");

        foodTable.put("J", "Java");

        foodTable.put("P", "Python");

        foodTable.put("H", "Hibernate");

 

        for (Map.Entry<String, String> set:foodTable.entrySet()) {

 

            System.out.println(set.getKey() + " = " + set.getValue());

        }

    }

}


83) What u know about legacy classes in collection hierarchy?

-> 

    -classes and interfaces that formed the collections framework in the older version of Java are known as Legacy

    -All the legacy classes are synchronized. The java.util package defines the following legacy classes:

      -HashTable

      -Stack

      -Dictionary

      -Properties

      -Vector


84) What comes under list then set and then map explain each of them?

-> 

      - List allows to store duplicate elements in java. 

      - Set does not allow to store duplicate elements in java. 

      - Map stores data in form of key-value pair it does not allow to store duplicate keys but allows duplicate values in java.


85) What is difference for each and for loop? Explain in with program.

->

  -The for loop is a control structure for specifying iteration that allows code to be repeatedly executed.The foreach loop is a control structure for traversing

   items in an array or a collection.

  -A for loop can be used to retrieve a particular set of elements.The foreach loop cannot be used to retrieve a particular set of elements.

  -The for loop is harder to read and write than the foreach loop.The foreach loop is easier to read and write than the for loop.

  -The for loop is used as a general purpose loop.The foreach loop is used for arrays and collections.


86) What is difference iterator and ListIterator?

-> - we can get the iterator consor by iterator() method. Iterator itr = l.iterator();

     we can get the listiterator consor by listiterator() method.ListIterator li=l.listIterator();

   - Iterator consar can be used with any collection object.

     ListIterator consor can be used with List implemented classes i.e Arraylist,LinkList,vector,stack.

   - Using Iterator we can access the elements of collection only in forward direction using the hasNext() & next() methods.

     Using ListIterator we can access the elements in the forward direction using hasNext() and next() methods and in reverse direction using hasPrevious()

     and previous() methods.

   - You cannot add elements to collection.

     You can add the elements collection.

   - You cannot replace the existing elements with new elements. 

     You can replace the existing elements with a new element by using void set(E e).

   - Using Iterator you cannot access the indexes of elements of collection.

     Using ListIterator you can access indexes of elements of collection using nextIndex()and previous Index() methods.

   - Using Iterator you can remove the elements of a collection.

     Using ListIterator you can also remove the elements of collection.


87) What is difference between Collection and Collections?

-> 

                                Collection                                                                 Collections

         - It is an interface.                                                                    - It is a utility class.

         - It is utilized to represent a group of individual objects in the form of a single unit. -It specifies several utility methods that are used to

                                                                                                         work on the collection.

         - The Collection is an interface that includes a static method since the launch of Java8.     -It contains static methods only.

           The Interface can contain default and abstract methods.

         - It extends the iterable interface.                                                      -It extends the Object class.



88) What is difference between TreeSet , HashSet and LinkedHashSet?

->

  -HashSet internally uses HashMap for storing objects.

   LinkedHashSet uses LinkedHashMap internally to store objects.

   TreeSet uses TreeMap internally to store objects.


  -If you don’t want to maintain insertion order but want to store unique objects then use the Hashset.

   If you want to maintain the insertion order of elements then you can use LinkedHashSet. 

   If you want to sort the elements according to some Comparator then use TreeSet.

  

  -HashSet does not maintain insertion order.

   LinkedHashSet maintains the insertion order of objects.

   While TreeSet orders the elements according to supplied Comparator. 

   By default, objects will be placed according to their natural ascending order.

  

  -HashSet gives O(1) complexity for insertion, removing, and retrieving objects.

   LinkedHashSet gives insertion, removing, and retrieving operations performance in order O(1).

   TreeSet gives the performance of order O(log(n)) for insertion, removing, and retrieving operations.

  

  -The performance of HashSet is better when compared to LinkedHashSet and TreeSet.

   The performance of LinkedHashSet is slower than TreeSet. 

   It is almost similar to HashSet but slower because LinkedHashSet internally maintains LinkedList to maintain the insertion order of elements

   TreeSet performance is better than LinkedHashSet except for insertion and removal operations because it has to sort the elements after each insertion and 

   removal operation.

  

  -HashSet uses equals() and hashCode() methods to compare the objects.

   LinkedHashSet uses equals() and hashCode() methods to compare it’s objects.

   TreeSet uses compare() and compareTo() methods to compare the objects.

  

  -HashSet allows only one null value. 

   LinkedHashSet allows only one null value.

   TreeSet does not permit null value. 

   If you insert null value into TreeSet,it will throw NullPointerException.

  

  -Syntax: HashSet obj = new HashSet();

           LinkedHashSet obj = new LinkedHashSet(); 

           TreeSet obj = new TreeSet();


89) What is difference between HashMap, Treemap, LinkedhashMap, Hashtable?

-> 

  HashMap: A HashMap is class which implements the Map interface.

           It stores values based on key.

           It is unordered, which means that the key must be unique.

           It may have null key-null value.

           For adding elements in HashMap we use the put method.

           Return type of put method is Object.

           It returns the previous value associated with key or null if there was no mapping for key.


 TreeMap: The TreeMap is a class which implements  map interface which is the sub- interface of SortedMap.

          It stores values based on key.

          It is ordered but in an Ascending manner.

          Keys should be unique.

          It cannot have null key at run time but can have null values because the interpreter will not understand how to sort null with other values.

 

 LinkedHashMap: A LinkedHashMap is a ‘hastable and linked list implementation of the map interface with a predictable iteration order.

                It is the same as HashMap except it maintains an insertion order i.e. ordered

                

 Hashtable: Hashtable is a class which implements Map interface and extends Dictionary class.

           It stores values based on key.

           It is unordered and the key should be unique.

           It cannot have null keys or null values.

           It gives runtime error if we try to add any null keys or values but will not show an error at compile time.

           It has synchronised methods and slower than hashmap.


90) What are generics in collection?

->  The generic collections are type-safe and checked at compile-time. 

    These generic collections allow the datatypes to pass as parameters to classes. 

    These Compiler is responsible for checking the compatibility of the types.



91) What is runtime exception and compile time exceptions?

92) What is checked Exception and unchecked exception?

-> 

  -Compile-Time Exceptions: These are also known as "checked exceptions."

                            All exceptions which are not runtime exceptions are compile time exceptions.They are checked at compile time.

                            If thrown from any method, they must be handled by caller of the method otherwise it gives compile time error.

                            If any method throws runtime exception, then the caller is not restricted to handle that exception.


  -Runtime Exceptions: These are also known as "unchecked exceptions" or "unchecked runtime exceptions."

                       Runtime exceptions occur during the execution of the program, not during compilation.

                       This exception occurs at runtime. Actually, even checked exception occurs at runtime.

                       If any method thrown runtime exception, then the caller is not restricted to handle that exception.



93) Give me examples of compile time exceptions.

->  

package com.javabykiran.Exception; 

public class RuntimeEx {

    void m1() throws ClassNotFoundException {

  }

    void m2(){

      m1(); // Error as m1 throws compile time exception

  }

}


94) Give me examples of run time exceptions.

-

>package com.javabykiran.Exception; 

  public class RuntimeEx {

    void m1() throws NullPointerException { 

    }

    void m2(){

      m1(); // no error as m1 throws 

      //runtime exception

   }

}


95) What is use of try block?

->  to write risky java code.

    try block will execute always.


96) What is use of catch block?

->  to handle the Exception by declaring the type of exception within the parameter. 

    The declared exception must be the parent class exception

    alternate code for exception.

    only if there is a exception try.


97) What is use of finally block?

->  It is always executed whether or not the exceptions are handled.

    To close the resources.

    this block is use to clean up activities.


98) Can we write multiple catch blocks for every try block? If yes, then what care we need to take?

-> yes,

  -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.


99) What is difference between throw and throws?

100) Explain throw and throws each with 3 points?

-> 

  -The 'throw' keyword is used to explicitly throw an exception from within a block of code or a method. 

   The 'throws' keyword is used in the method signature to declare the exceptions that a method can potentially throw.

  -The 'throw' keyword can only throw a single exception at a time.

   The 'throws' keyword allows for the declaration of multiple exceptions that a function could throw.

  -The 'throw' keyword is followed by the instance exception to be thrown.

   The 'throws' keyword is followed by the names of the exception classes.

  -The 'throw' keyword should be used within the body of a method.

   The 'throws' keyword should be used within the method signature.


101) Do you know any annotation in java? Please explain at least 2 annotations.

->

  1) @Override - When we want to override a method of Superclass, we should use this annotation to inform compiler that we are overriding a method. 

                 So when superclass method is removed or changed, compiler will show error message.

                 Learn why we should always use java override annotation while overriding a method.


  2) FunctionalInterface - This annotation was introduced in Java 8 to indicate that the interface is intended to be a functional interface.


102) What is a syntax of one dimensional array?

->   Syntax:  datatype[]varname = new datatype[size];

              varname[index] = value;


103) What is a syntax of two dimensional array?

->  data_type[][] array_name = new data_type[rows][columns];


104) Can you reverse an array ? explain with program.

->

   yes,using the for loop.


 import java.util.*;

import java.util.stream.*;

public class Main

{

    public static void main(String[] args) {

    Integer[] intArray = {10,20,30,40,50,60,70,80,90};

     

  //print array starting from first element

    System.out.println("Original Array:");

    for(int i=0;i<intArray.length;i++)

         System.out.print(intArray[i] + "  ");

     

    System.out.println();

     

    //print array starting from last element

    System.out.println("Original Array printed in reverse order:");

         for(int i=intArray.length-1;i>=0;i--)

         System.out.print(intArray[i] + "  ");

    }

}



105) Can you iterate array by using for each loop? How?

->     

          public class ForEachLoopExample {

    public static void main(String[] args) {

        // Sample array

        int[] numbers = {1, 2, 3, 4, 5};


        // Using for-each loop to iterate through the array

        System.out.println("Iterating through the array using for-each loop:");

        for (int num : numbers) {

            System.out.print(num + " ");

        }

    }

}



The array numbers is defined with integers.

The for-each loop is used to iterate through each element of the array. 

The syntax of the for-each loop is for (elementType variable : array), where elementType is the type of elements in the array, variable is the variable that takes the value of each element in each iteration, and array is the array you want to iterate through.

Inside the loop, the variable num takes the value of each element in the array, and it is printed to the console.


106) How to create a String object?

->       we can create string  object  4 ways :

     1)By using new keyword.

     2)By using string literal.

     3)By using stringBuffer.

     4)By using stringBuilder.


107) What is difference between equals method of object class and String class?

->    The equals() Method of the Object will check reference of object i.e addreess.Whereas equals method of string will check contents of string with 

      character sequence


108) What is difference between == and equals method of String class?

->    "==" compares the memory location of two objects, while "equals" compares the contents of two objects.


109) Tell me 5 methods of String class and explain each one of them with program?

-> 

   1)length(): Returns the length (number of characters) of the string.

               String str = "Hello, World!";

               int length = str.length(); 

               System.out.println("Length of the string: " + length);

  

   2)charAt(int index):Returns the character at the specified index.

                       String str = "Java";

                       char character = str.charAt(1); // Returns the character at index 1 (zero-based)

                       System.out.println("Character at index 1: " + character);


   3)substring(int beginIndex):Returns a substring starting from the specified index.

                               String str = "Programming";

                               String subStr = str.substring(3); // Returns "gramming"

                               System.out.println("Substring from index 3: " + subStr);


   4)substring(int beginIndex, int endIndex):Returns a substring starting from the beginIndex and ending at the specified endIndex (exclusive).           

                                             String str = "Java Programming";

                                             String subStr = str.substring(5, 16); // Returns "Programming"

                                             System.out.println("Substring from index 5 to 15: " + subStr);


  5)concat(String str): Concatenates the specified string to the end of this string.

                        String str1 = "Hello";

                        String str2 = "World";

                        String result = str1.concat(", " + str2); // Returns "Hello, World"

                        System.out.println("Concatenated string: " + result);


   6)indexOf(String str):Returns the index within the string of the first occurrence of the specified substring.

                         String str = "Java is fun and Java is powerful";

                         int index = str.indexOf("Java"); // Returns the index of the first occurrence of "Java"

                         System.out.println("Index of 'Java': " + index);


  7)toLowerCase() / toUpperCase():Returns a new string with all characters in lowercase / uppercase.

                                  String str = "Hello, World!";

                                  String lowerCase = str.toLowerCase();

                                  String upperCase = str.toUpperCase();

                                  System.out.println("Lowercase: " + lowerCase);

                                  System.out.println("Uppercase: " + upperCase);


   8)replace(char oldChar, char newChar):Returns a new string resulting from replacing all occurrences of oldChar with newChar.

                                         String str = "Hello, Java!";

                                         String newStr = str.replace('o', '0'); // Replaces 'o' with '0'

                                         System.out.println("New string: " + newStr);


110) What is string pool concept in java?

-> String Pool in Java is a special storage space in Java Heap memory where string literals are stored. 

   It is also known by the names - String Constant Pool or String Intern Pool.

   String one copy storage. 

   Whenever a string literal is created, the JVM first checks the String Constant Pool before creating a new String object corresponding to it.


111) Difference between String, StringBuffer and the StringBuilder.

->   

   -String is store in the string pool memory.StringBuffer and StringBuilder are store in the heap memory.

   -String is immutable and StringBuffer and StringBuilder are mutable.

   -String is syncronized and StringBuffer and StringBuilder are non syncronized.

   -String performance is slow and StringBuffer slower then the stringbuilder and faster then the string. stringbuilder faster then the stringbuffer. 


112) How to create a simple thread in java?

->  Thread are acive the two way

     1)by using the Runnable interface.

     2)by using the thread class.  


113) Define thread?

->  Every executable program is called thread.

    Thread is lightweight subprocess, the smallest unit of processing path of execution.

    it is used for parallel programming.

    multiple thread are execute the same time is called the multithreading.

    thread are independent,because occur exception at one thread.it does not affect other threads.


114) What is difference between thread and process?

->   

   -Threads share the same address space, but In the process each process allocate the a seprate memory area.

   -Threads is lightweight subprocess,the smallest unit of processing.and process is heavyweight.

   -Threads in the cast of commenication between the thread is low,but cost of cummenication between the high.

   -New threads are easily created whereas new processes require duplication of the parent process.


115) Can you explain lifecycle of Thread?

->   The different states of threads are as follows:

     1)New : When a thread is instantiated it is in 'New' state until the 'start()' method is called on the 'thread' instance. 

             In this state the thread is not considered to be alive.


     2)Runnable : The thread enters into this state after the 'start()' method is called in the thread instance. 

                  The thread may enter into the 'Runnable' state from 'Running' state. 

                  In this state the thread is considered to be alive.


     3)Running : When the thread scheduler picks up the thread from the 'Runnable' thread's pool, the thread starts running and the thread is said to be in

                'Running' state.


     4)Waiting/Blocked/Sleeping : In these states the thread is said to be alive but not runnable. 

                                  The thread switches to this state because of various reasons like when 'wait()' method is called or 'sleep()' method has been 

                                  called on the running thread or thread might be waiting for some input/output resource so blocked.


     5)Dead : When the thread finishes its execution i.e. the 'run()' method execution completes, it is said to be in 'dead' state.

             A 'dead' state cannot be started again. 

            If a 'start()' method is invoked on a dead thread a runtime exception will occur.


116) Can you write statements for jdbc connectivity?

->  A  JDBC program comprises the following FIVE steps:


   STEP 1: Register the driver class.

           The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.

   STEP 2: Create the connection database.

           The getConnection() method of DriverManager class is used to establish connection with the database.

   STEP 3: the Statement and Connection created.

           The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with 

           the database.

   STEP 4: Write a SQL query and execute the query .

           The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used

           to get all the records of a table.

   STEP 5: Close the Statement and Connection .

           By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close 

           the connection.


117) Can you explain difference between preparedstatement and statement?

-> -The Statement interface provides methods to execute queries with the database.

        -The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.

   -A standard Statement is used for creating a Java representation for a literal SQL statement and for executing it on the database.

   -A PreparedStatement is a precompiled Statement.

   -A Statement has to verify its metadata in the database every time.

   -But, the prepared statement has to verify its metadata in the database only once.

   -If we execute the SQL statement, it will go to the STATEMENT.

   -But, if we want to execute a single SQL statement for the multiple number of times, it’ll go to the PreparedStatement.


118) Can you explain How to retrieve data from database in java. Please explain all steps.

->   STEP 1: Allocate a Connection object, for connecting to the database server. 

     STEP 2: Allocate a Statement object, under the Connection created earlier, for holding a SQL command. 

     STEP 3: Write a SQL query and execute the query, via the Statement and Connection created. 

     STEP 4: Process the query result.


119) What is SQL?

->  SQL stands for Structured Query Language, and it is a domain-specific programming language used for managing and manipulating relational databases.

    SQL is widely used for querying and updating data in relational database management systems (RDBMS). 

    It provides a standardized way to interact with databases, making it possible to create, retrieve, update, and delete data.


120) What is DDL , DML and DCL?

-> 

   1) Data Definition Language (DDL): DDL commands are used to define and manage the structure of the database, including creating and modifying tables, 

                                      specifying constraints, and defining relationships. Common DDL commands include CREATE, ALTER, and DROP.

                                       CREATE TABLE table_name (

                                                column1 datatype,

                                                column2 datatype,

                                                PRIMARY KEY (column1)

                                        );


   2)Data Manipulation Language (DML): DML commands are used to manipulate data within the database.

                                       Common DML commands include INSERT, UPDATE, and DELETE.


                                       INSERT INTO table_name (column1, column2) VALUES (value1, value2);

   

   3)Data Control Language(DCL) :consists of statements that control security and concurrent access to table data. 

                                 DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions, and other controls of the database system. 

                                                                                           GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;  

                                                                                            REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;  



121) What is RDBMS?

->  RDBMS stands for Relational Database Management System.

   -RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

   -The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.

   -Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model. 

   

122) Can you write select query with where condition?

->  A SELECT query with a WHERE condition is used to retrieve data from a database based on specified criteria. 

    

     SELECT column1, column2, column3

    FROM your_table

    WHERE condition;

    Replace column1, column2, and column3 with the actual column names you want to retrieve, your_table with the name of your table, and condition with the 

    criteria that the data must meet. 


123) Can you write update query with where condition?

->  An UPDATE query with a WHERE condition is used to modify existing records in a database based on specified criteria. Here's a basic example: 

    UPDATE your_table

    SET column1 = new_value1, column2 = new_value2

    WHERE condition;

    Replace your_table with the actual name of your table, column1, column2 with the column names you want to update, new_value1, new_value2 with the new values 

    you want to set, and condition with the criteria that the records must meet to be updated. 


124) Can you write delete query with where condition?

->  Certainly! A DELETE query with a WHERE condition is used to remove records from a table based on specified criteria.   

    DELETE FROM your_table

    WHERE condition;

    Replace your_table with the actual name of your table and condition with the criteria that the records must meet to be deleted.


125) Can you write insert query?

-> Certainly! An INSERT query is used to add new records to a table. Here's a basic example:

   INSERT INTO your_table (column1, column2, column3)

   VALUES (value1, value2, value3);

  Replace your_table with the actual name of your table, column1, column2, and column3 with the column names you want to insert values into, and value1, value2,

  and   value3 with the actual values you want to insert.


126) What is primary Key?

-> A primary key is a field or a combination of fields in a database table that uniquely identifies each record in the table. 

  Its main characteristics are:

  Uniqueness: Each value in the primary key must be unique across all records in the table. No two records can have the same primary key value.

  Non-null: The primary key value cannot be NULL, meaning it must have a value for every record in the table.

  Unchanging: The values in the primary key should not be modified once they are assigned. If changes are necessary, it's usually better to create a new record 

              with a new primary key.


127) What is foreign Key?

-> A foreign key is a field or a set of fields in a database table that refers to the primary key of another table.

  It establishes a link between the data in two tables, creating a relationship between them. 

  The primary purpose of a foreign key is to maintain referential integrity between the tables.


128) Can you explain memory management in java?

->  Memory management in Java is an automatic and integral part of the Java Virtual Machine (JVM), which is responsible for running Java applications.

    Java uses a garbage collection mechanism to automatically allocate and deallocate memory, relieving developers from manual memory management tasks.


Comments

Popular posts from this blog

Primary/Main features of Java

HTTrack ऑफलाइन वेबसाइट डाउनलोडर क्या है ?

Which language is used for Java?