Introductory Concepts in Java Flashcards
Who created Java?
Sun Microsystems
Describe the Structure of a call
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"); } }
What is the main method in Java
It is the method that Java first looks for when to run a program
How do you add single line comments in Java?
Use two forward slashes to start a comment //
How do you do a multi-line comment?
It begins with a /* and ends with a */
What are variables in Java?
Variables are used to store data
what are 5 types of variables?
1 - String 2 - Int 3 - Float 4 - Char 5 - Boolean
How do you declare a variable in Java?
The basic syntax for declaring a variable is Data Type Name of Variable = Value of Variable
A specific String Variable String firstName = “Doug”;
What happens when you add the keyword final to the start of a variable?
It makes it no longer possible to change the value of the variable
How do you display the value of the variable?
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.
What is the best way to declare multiple variables with the same type?
Use a comma separated list
String firstName = “Bob”, firstName2 = “Mary”, firstName3 =”Terry”;
what are some tips to naming variables?
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
What are the two groups of variables?
1 - Primitive
2- Non-Primitive
What are the primitive data types?
1- Byte 2- Short 3 - Int 4 - Long 5 - Float 6 - Double 7 - Boolean 8 - Char
What are the non-primitive types?
1 - String
2 - Array
3 - Class
What are the two groups of the number data type?
1 - Integer
2 - Floating Point Types
What are the two values of the boolean data type?
1 - True
2 - False
What is the char Data type?
1 - It represents one character and is surrounded by quotes.
For example
Char myChar = “b”;
What is type casting in Java?
It is going from one value to another value in primitive type.
What are the two types of casting?
1 - Widening
2 - Narrowing
What are the groups for operators in Java?
1 - Arithmetic 2 - Assignment 3 - Comparison 4 - Logical 5 - Bitwise
What is the syntax to designate a String data type?
String name = “Bob”;
What are some of the most popular String Methods?
1 - toUpperCase()
2 - toLowerCase()
3 - indexOf()
What is the Math Class?
The math class has many built in Math Methods that help perform many different Math functions.
What are some of the built in Math Methods?
1- Max() 2- Min() 3 - sqrt() 4- abs() 5 random()
What is the syntax for the Boolean data type?
boolean isTrue = true;
What is the syntax for conditional statements in Java?
if(parameter){ code block }else if(parameter){ code block }else { code block }
What is a ternary operator?
It is a short-hand way of writing a if else conditional statement.
What is the syntax for the ternary operator?
int score = 9;
String outcome = (score < 10) ? “You lose!” : “You win!”;
What is a switch statement?
A switch statement is a conditional statement that can be used when there are many cases.
What is the syntax for the switch statement?
switch(expression) { case x: // code block break; case y: // code block break; default: // code block }
Why is it important to add a break statement after the code block?
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.
What is the default keyword in the Switch statement?
It will run if not of the other conditions are valid.
What is a while loop?
It is a custom code block to execute a block of code until a specific condition is reached
What is the syntax for the while loop?
while (condition) { // code block to be executed }
What is the difference between a while loop and a do/while loop?
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
What is the syntax for a do/while loop?
do { // code block to be executed } while (condition);
What is a for loop?
It is used to run a code block when it is known how many times you want to loop through a block of code.
What is the syntax for a for loop?
for (statement 1; statement 2; statement 3) { // code block to be executed }
What is a break statement in a for loop?
It breaks out of a loop when a condition is met
What is the syntax for the break statement?
for (int i = 0; i < 10; i++) { if (i == 4) { break; } System.out.println(i); }
What is the syntax for an array?
String[] cars;
int[] myNum = {10, 20, 30, 40};
What are the steps of a java program?
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
What is the primary function of the Java Virtual Machine?
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
Where is the bytecode saved after it is compiled?
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.
What is the function of the Java Compiler?
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.
What are the 4 main concepts of Object Oriented Program in Java?
4 main concepts of Object Oriented programming are:
Abstraction
Encapsulation
Inheritance
Polymorphism
Why is Java considered a simple language?
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.
Why is Java a reliable or robust language?
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.
Describe Java is distributed
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.
What is multi threading in Java?
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.
What does portable mean with Java?
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.
What is another definition of static?
static: We do not need to create object for static methods to run. They can run itself.
What is the variable naming convention for Java?
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.
What are the three types of variables?
1) Local variable 2) Static (or class) variable 3) Instance variable
What is the syntax for a ternary operator?
variable num1 = (expression) ? value if true : value if false
What is a constructor?
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 does the constructor work?
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.
What are the three constructor types?
Default, No-arg constructor and Parameterized.
What is constructor overloading?
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.
Constructor Recap
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).
What is the difference between a method and constructor?
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
What is the static key word?
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
what is a child class?
The class that extends the features of another class is known as child class, sub class or derived class
What is a parent class?
The class whose properties and functionalities are used(inherited) by another class is known as parent class, super class or Base class
What is the relationship with constructors and inheritance?
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
What is aggregation?
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.
Why we need aggregation?
It is to help reuse code over and over again
What is association?
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
What is the difference between composition, association, and aggregation?
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.
What is the super keyword?
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.
What are the three ways to overload a method?
1 - The amount of parameters
2- data types of parameters
3 - order or data types of parameter
What is method overriding?
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.
what is polymorphism?
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.
what are the types of polymorphism?
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
Why can’t we create a class of the abstract class?
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.
Rules of Abstract Classes and methods
Abstract methods don’t have body, they just have method signature as shown above.
- 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.
- 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.
What is encapsulation?
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 to encapsulate in Java?
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
What are the advantages of encapsulation?
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
What are packages?
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
Advantages of using packages
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
What are the four access modifiers?
. default
- private
- protected
- public
What is an exception?
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
Why an exception occurs?
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
What are the advantages of exception?
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.
What is the difference between an error and exception?
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
What are the types of exceptions?
Checked exceptions
2)Unchecked exceptions
What are some of the common exceptions?
Example 1: Arithmetic exception
Example 2: ArrayIndexOutOfBounds Exception
Example 3: NumberFormat Exception
Example 4: StringIndexOutOfBound Exception
Example 5: NullPointer Exception
What is a thread?
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
What is multithreading?
The process of executing multiple threads simultaneously is known as multithreading.
Summary of Multithreading
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.
- 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.
- 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
Multitasking vs Multithreading vs Multiprocessing vs parallel processing
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 to create a thread?
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 to create a file in Java?
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
What are two ways to read files?
1 - Buffered Input Stream
2 - Buffered Reader
What are some Java 8 features?
Java 8 – Lambda Expression
- Java 8 – Method references
- Java 8 – Functional interfaces
- Java 8 – Interface changes: Default and static methods
- Java 8 – Streams
- Java 8 – Stream filter
- Java 8 – forEach()
- Java 8 – Collectors class with example
- Java 8 – StringJoiner class with example
- Java 8 – Optional class with example
- Java 8 – Arrays Parallel Sort
What are some Java 9 features?
. JShell
- JPMS (Java Platform Module System)
- JLink (Java Linker)
- Http/2 client
- Process API updates
- Private Methods Inside Interface
- Try with resources enhancements
- 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
What is a servlet?
Servlet is a java program that runs inside JVM on the web server. It is used for developing dynamic web applications.
What are the advantages of the servlet?
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.
what are the main features of a servlet?
- 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. - 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. - 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 do you implement a servlet?
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.
What is the http Servlet?
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.
What is JSP?
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
Where does the servlet sit on the request process?
Before the database
What two packages build servlets?
javax. servlet(Basic)
javax. servlet.http(Advance)
What is DBMS?
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.
What is the purpose of Database System?
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.
What is an ENUM?
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.
What is a good example of an ENUM?
Days of Week,Months etc.. it would be constants that don’t change
What are Java annotations?
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).
What are some built in annotations?
@Override
@Deprecated
@SuppressWarnings
What are regular Expressions?
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 to delete a file in Java?
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 do you rename a file?
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"); } } }
What is JSON?
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.
What is the syntax for JSON?
var chaitanya = { "firstName" : "Chaitanya", "lastName" : "Singh", "age" : "28" };
What is polymorphism?
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.
What is the JVM?
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.
What is inheritance?
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.
What is abstraction?
Hiding internal details and showing functionality is known as abstraction. For example phone call, we don’t know the internal processing.
What is encapsulation?
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
What is coupling?
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.
What is cohesion?
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.
What is association?
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.
What is aggregation?
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.
What is composition?
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.
What are some naming conventions for Classes?
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
What is a naming convention for Interfaces?
It should start with the uppercase letter.
It should be an adjective such as Runnable, Remote, ActionListener.
Use appropriate words, instead of acronyms
What is a naming convention for methods?
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().
What is a naming convention for variables?
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.
What is a naming convention for packages?
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.
What is a naming convention for constants?
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.
A class in Java typically contains?
Fields Methods Constructors Blocks Nested class and interface
What does the new keyword due in Java?
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
What are three ways to initialize an object?
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
What is an anonymous object?
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.
When is the constructor called in a class?
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.
Can a constructor use overloading?
Yes
Can constructor perform other tasks instead of initialization?
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.
What is the static keyword?
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
Why is Static important?
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.
What is a Java Static Method?
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.
Q) Why is the Java main method static?
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.
Q) Can we execute a program without main() method?
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.
What are the uses for this keyword?
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.
What is inheritance?
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
What is the syntax for inheritance?
class Subclass-name extends Superclass-name { //methods and fields }
What is aggregation?
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
What is the syntax for aggregation?
class Employee{ int id; String name; Address address;//Address is a class ... }
What are two ways to overload a method?
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
What is the super keyword?
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.
When do you use the super keyword?
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.
What are the instance initializer block?
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.
Where are the three places in Java to perform operations?
There are three places in java where you can perform operations:
method
constructor
block
Where can the final keyword be made?
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.
What happens when you make a method final?
If you make any method as final, you cannot override it.
What happens if you make a class final?
If you make any class as final, you cannot extend it.
What is polymorphism?
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.
What is the java instanceOf?
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.
What is abstraction?
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.
What are some things to remember with abstraction?
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.
What is a factory method?
A factory method is a method that returns the instance of the class. We will learn about the factory method later.
What is an interface?
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.
What is encapsulation?
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.
What is a java bean?
The Java Bean class is the example of a fully encapsulated class.
What are some advantages of encapsulation?
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.
What is the object class?
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.
What is object cloning?
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:
What are the advantages of object cloning?
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.
What are the disadvantages of object cloning?
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.
What is the java math class?
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.
What is the wrapper class?
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
What is the
next →← prev
Java Strictfp Keyword?
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