Beyond basic Java -- Java Implementations/Servlets/JSPs/JDBC/JavaDocs

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What is Groovy?

Groovy is a dynamic object-oriented programming language for the Java virtual machine (JVM) that can be used anywhere Java is used. The language can be used to combine Java modules, extend existing Java applications and write new applications. Groovy can serve as a scripting language for developers new to the Java platform and can also be useful for veteran Java developers interested in enhancing the expediency and flexibility of that language. Groovy has a Java-like syntax and works seamlessly with Java bytecode. Many of the language's features resemble those of Perl, Python, Ruby and Smalltalk. Other features include: Easy learning curve Support for domain-specific languages Compact syntax Support for dynamic typing Powerful processing primitives Ease of Web application development Support for unit testing. The Groovy concept was introduced in 2003 by James Strachan. Beta versions were made available from 2004 to 2006. Version 1.0 was released in January 2007 and version 1.1 was released in December 2007. Groovy is going through standardization under Java Specification Request (JSR) 241. The project manager is Guillaume Laforge.

What are the five SOLID principles?

In Java, SOLID principles are an object-oriented approach that are applied to software structure design. It is conceptualized by Robert C. Martin (also known as Uncle Bob). These five principles have changed the world of object-oriented programming, and also changed the way of writing software. It also ensures that the software is modular, easy to understand, debug, and refactor. 1. Single Responsibility Principle (SRP) 2. Open-Closed Principle (OCP) 3. Liskov Substitution Principle (LSP) 4. Interface Segregation Principle (ISP) 5. Dependency Inversion Principle (DIP)

What is the JVM?

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent). It is: A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies. An implementation Its implementation is known as JRE (Java Runtime Environment). Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.

What is the difference between Java bytecode and machine code?

Java bytecode is a binary data format that includes loading information and execution instructions for the Java virtual machine. In that sense, Java bytecode is a special kind of binary code. ... Java bytecode is not a binary code in that sense. It is not processor-specific. Byte code is an intermediate code between the source code and machine code. It is a low-level code that is the result of the compilation of a source code which is written in a high-level language. It is processed by a virtual machine like Java Virtual Machine (JVM). Byte code is a non-runnable code after it is translated by an interpreter into machine code then it is understandable by the machine. It is compiled to run on JVM, any system having JVM can run it irrespective of their operating system. That's why Java is platform-independent. Byte code is referred to as a Portable code. Machine Code: Machine code is a set of instructions that is directly machine-understandable and it is processed by the Central Processing Unit (CPU). Machine code is in binary (0's and 1's) format which is completely different from the byte code and source code. It is regarded as the most lowest-level representation of the source code. Machine code is obtained after compilation or interpretation. It is also called machine language. The below figure illustrates the example of how Java source code is converted to Byte code and then to machine code : 01.Byte Code consisting of binary, hexadecimal, macro instructions like (new, add, swap, etc) and it is not directly understandable by the CPU. It is designed for efficient execution by software such as a virtual machine.intermediate-level Machine code consisting of binary instructions that are directly understandable by the CPU. 02. Byte code is considered as the intermediate-level code. Machine Code is considered as the low-level code. 03. Byte code is a non-runnable code generated after compilation of source code and it relies on an interpreter to get executed. Machine code is a set of instructions in machine language or in binary format and it is directly executed by CPU. 04. Byte code is executed by the virtual machine then the Central Processing Unit. Machine code is not executed by a virtual machine it is directly executed by CPU. 05. Byte code is less specific towards machine than the machine code. Machine code is more specific towards machine than the byte code. 06. It is platform-independent as it is dependent on the virtual machine and the system having a virtual machine can be executed irrespective of the platform. It is not platform independent because the object code of one platform can not be run on the same Operating System. Object varies depending upon system architecture and native instructions associated with the machine. 07. All the source code need not be converted into byte code for execution by CPU. Some source code written by any specific high-level language is converted into byte code then byte code to object code for execution by CPU.All the source code must be converted into machine code before it is executed by the CPU.

What is Javadocs?

JavaDoc tool is a document generator tool in Java programming language for generating standard documentation in HTML format. It generates API documentation. It parses the declarations and documentation in a set of source files describing classes, methods, constructors and fields. Before using JavaDoc tool, you must include JavaDoc comments /**....................*/ providing information about classes, methods and constructors etc. For creating a good and understandable document API for any java file you must write better comments for every class, method, constructor. The JavaDoc comments are different from the normal comments because of the extra asterisk at the beginning of the comment. It may contain the HTML tags as well. // Single-Line Comment /* * Multiple-Line comment */ /** * JavaDoc comment */ By writing a number of comments, it does not affect the performance of the Java program as all the comments are removed at compile time. JavaDoc Format: - It has two parts: - a description which is followed by block tags. Some Integrated Development Environments (IDE) automatically generate the JavaDoc file like NetBeans, IntelliJ IDEA, Eclipse etc. Generation of JavaDoc: - To create a JavaDoc you do not need to compile the java file. To create the Java documentation API, you need to write Javadoc followed by file name. javadoc file_name or javadoc package_name After successful execution of the above command, a number of HTML files will be created, open the file named index to see all the information about classes. JavaDoc Tags TAG PARAMETER DESCRIPTION @author author_name Describes an author @param desciption provide information about method parameter or the input it takes @see reference generate a link to other element of the document @version version-name provide version of the class, interface or enum. @return desciption provide the return value To generate JavaDoc in Eclipse: - Select "Generate JavaDoc" option from Project menu and a wizard will appear. Specify the location for the JavaDoc file on your computer, by default it will be in the C drive. Select the project and then the packages for which you want to create the JavaDoc file. After this on the right side, select the classes for which you want to generate the JavaDoc, by default all the classes will be selected. Then you can also specify for which classes the JavaDoc will be generated by selecting the visibility. Select the destination location where the generated JavaDoc will be placed. Then click Next or Finish.If you select Next in the next window you can select the Document title and other basic options. Example 1: - package exa; import java.util.Scanner; /** * * @author Yash */ public class Example { /** * This is a program for adding two numbers in java. * @param args */ public static void main(String[] args) { /** * This is the main method * which is very important for * execution for a java program. */ int x, y; Scanner sc = new Scanner(System.in); /** * Declared two variables x and y. * And taking input from the user * by using Scanner class. * */ x = sc.nextInt(); y = sc.nextInt(); /** * Storing the result in variable sum * which is of the integer type. */ int sum = x + y; /** * Using standard output stream * for giving the output. * @return null */ System.out.println("Sum is: " + sum); } }

log4j

log4j has three main components: loggers: Responsible for capturing logging information. appenders: Responsible for publishing logging information to various preferred destinations. layouts: Responsible for formatting logging information in different styles. History of log4j Started in early 1996 as tracing API for the E.U. SEMPER (Secure Electronic Marketplace for Europe) project. After countless enhancements and several incarnations, the initial API has evolved to become log4j, a popular logging package for Java. The package is distributed under the Apache Software License, a full-fledged open source license certified by the open source initiative. The latest log4j version, including its full-source code, class files, and documentation can be found at http://logging.apache.org/log4j/. log4j Features It is thread-safe. It is optimized for speed. It is based on a named logger hierarchy. It supports multiple output appenders per logger. It supports internationalization. It is not restricted to a predefined set of facilities. Logging behavior can be set at runtime using a configuration file. It is designed to handle Java Exceptions from the start. It uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL. The format of the log output can be easily changed by extending the Layout class. The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface. It is fail-stop. However, although it certainly strives to ensure delivery, log4j does not guarantee that each log statement will be delivered to its destination. Pros and Cons of Logging Logging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application's runtime information. Logging does have its drawbacks also. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate these concerns, log4j is designed to be reliable, fast and extensible. Since logging is rarely the main focus of an application, the log4j API strives to be simple to understand and to use.

JVM architecture

see image

What are Core Java, Enterprise Java, Java SE, Java EE, and J2EE?

1. Core Java usually refers to Java SE which consists of the a. Java Language b. the JVM c. the JDK (which itself contains the compiler some tools and a pretty large library) 2. Enterprise Java refers to Java applications written for enterprises; the leading technology here is 3. Java EE which consists of a. a set of APIs (EJB, JMS, JPA, JTA, JSF etc.) b. the application servers (Glassfish, Tomcat, JBoss/WildFly etc.) which implement these APIs (or a part of them) 4. Java SE is used for general purpose programming and almost anything written in Java is based on the Core Java. Java SE stands for Java standard edition and is normally for developing desktop applications, forms the core/base API. 5. J2EE is the API built on top of the SE API to provide the tools necessary to do large scale projects more easily. Java EE stands for Java enterprise edition for applications which run on servers, for example web sites. Java is OOP language. Using java you can write standalone command line programs. When combined with tooling libs like Swing you can build GUI based desktop application. J2EE is a set of specifications which targets the enterprise technologies like JMS, WS, Servlets, JSP, EJB's etc. Most of these specification are implemented using Java. Using J2EE technology stack you can write complex business application.

What are four reasons for using SOLID principles?

1. It reduces the dependencies so that a block of code can be changed without affecting the other code blocks. 2. The principles intended to make design easier, understandable. 3. By using the principles, the system is maintainable, testable, scalable, and reusable. 4. It avoids the bad design of the software.

What is included in the JDK?

1. Java Runtime Environment (JRE) 2. Interpreter (java), 3. a compiler (javac) 4. an archiver (jar) 5. a documentation generator (javadoc) 6. some other development tools

What are the two basic steps in compiling and running Java source code?

1. The compiler converts source code into machine code then bytecode. 2. The JVM processes the bytecode

What is a war file and what is a jar file?

A war file is a Web Application Archive which runs inside an application server. A war file is a special jar file that is used to package a web application to make it easy to deploy it on an application server. A jar is a Java Application Archive that runs a desktop application on a user's machine.

This will explain 3 simple steps to use Reactive programming in your application (in Java) (see image).

Step-1 Create observable that emits the data: Here database is an observable which emits the data. In our case, it emits the strings. just() is an operator. Which basically emits the data provided in the argument one by one. (We are going to look into the operators in detail in our upcoming articles. So, don't worry about them.) Step -2 Create observer that consumes data: In above code snippet observer is an observer that consumes the data emitted by the database observable. It processes the data received and also handles error inside it. Step-3 Manage concurrency : At the last step, we define our schedulers that manage the concurrency. subscribeOn(Schedulers.newThread()) tells database observable to run on background thread. observeOn(AndroidSchedulers.mainThread()) tells observer to run on the main thread. This is basic code for reactive programming. Observable<String> database = Observable //Observable. This will emit the data .just(new String[]{"1", "2", "3", "4"}); //Operator Observer<String> observer = new Observer<String>() { @Override public void onCompleted() { //... } @Override public void onError(Throwable e) { //... } @Override public void onNext(String s) { //... } }; database.subscribeOn(Schedulers.newThread()) //Observable runs on new background thread. .observeOn(AndroidSchedulers.mainThread()) //Observer will run on main UI thread. .subscribe(observer); //Subscribe the observer

What is the relationship between JRE and JVM?

The JRE contains the JVM plus class libraries (such as System) The JRE is an implementation of the JVM, which is a processor NOTE: The image shows how the JDK, JRE, and JVM exist in relation to each other, but they do not show time order of steps ... the compiler goes first. Also, the interpreter is part of JVM???

Liskov Substitution Principle and example

The Liskov Substitution Principle (LSP) was introduced by Barbara Liskov. It applies to inheritance in such a way that the derived classes must be completely substitutable for their base classes. In other words, if class A is a subtype of class B, then we should be able to replace B with A without interrupting the behavior of the program. It extends the open-close principle and also focuses on the behavior of a superclass and its subtypes. We should design the classes to preserve the property unless we have a strong reason to do otherwise. Let's understand the principle through an example. Student.java public class Student { private double height; private double weight; public void setHeight(double h) { height = h; } public void setWeight(double w) { weight= w; } ... } public class StudentBMI extends Student { public void setHeight(double h) { super.setHeight(h); super.setWeight(w); } public void setWeight(double h) { super.setHeight(h); super.setWeight(w); } } The above classes violated the Liskov substitution principle because the StudentBMI class has extra constraints i.e. height and weight that must be the same. Therefore, the Student class (base class) cannot be replaced by StudentBMI class (derived class). Hence, substituting the class Student with StudentBMI class may result in unexpected behavior.

Open-Closed Principle with example

The application or module entities the methods, functions, variables, etc. The open-closed principle states that according to new requirements the module should be open for extension but closed for modification. The extension allows us to implement new functionality to the module. Let's understand the principle through an example. Suppose, VehicleInfo is a class and it has the method vehicleNumber() that returns the vehicle number. VehicleInfo.java public class VehicleInfo { public double vehicleNumber(Vehicle vcl) { if (vcl instanceof Car) { return vcl.getNumber(); if (vcl instanceof Bike) { return vcl.getNumber(); } } If we want to add another subclass named Truck, simply, we add one more if statement that violates the open-closed principle. The only way to add the subclass and achieve the goal of principle by overriding the vehicleNumber() method, as we have shown below. VehicleInfo.java public class VehicleInfo { public double vehicleNumber() { //functionality } } public class Car extends VehicleInfo { public double vehicleNumber() { return this.getValue(); } public class Car extends Truck { public double vehicleNumber() { return this.getValue(); } Similarly, we can add more vehicles by making another subclass extending from the vehicle class. the approach would not affect the existing application.

What is bytecode?

The code that results from the compilation of Java source code into machine code.

What is javac?

The compiler for Java

Interface Segregation Principle with example

The principle states that the larger interfaces split into smaller ones. Because the implementation classes use only the methods that are required. We should not force the client to use the methods that they do not want to use. The goal of the interface segregation principle is similar to the single responsibility principle. Let's understand the principle through an example. Suppose, we have created an interface named Conversion having three methods intToDouble(), intToChar(), and charToString(). public interface Conversion { public void intToDouble(); public void intToChar(); public void charToString(); } The above interface has three methods. If we want to use only a method intToChar(), we have no choice to implement the single method. To overcome the problem, the principle allows us to split the interface into three separate ones. public interface ConvertIntToDouble { public void intToDouble(); } public interface ConvertIntToChar { public void intToChar(); } public interface ConvertCharToString { public void charToString(); } Now we can use only the method that is required. Suppose, we want to convert the integer to double and character to string then, we will use only the methods intToDouble() and charToString(). public class DataTypeConversion implements ConvertIntToDouble, ConvertCharToString { public void intToDouble() { //conversion logic } public void charToString() { //conversion logic } }

Dependency Inversion Principle with example

The principle states that we must use abstraction (abstract classes and interfaces) instead of concrete implementations. High-level modules should not depend on the low-level module but both should depend on the abstraction. Because the abstraction does not depend on detail but the detail depends on abstraction. It decouples the software. Let's understand the principle through an example. public class WindowsMachine { //functionality } It is worth, if we have not keyboard and mouse to work on Windows. To solve this problem, we create a constructor of the class and add the instances of the keyboard and monitor. After adding the instances, the class looks like the following: public class WindowsMachine { public final keyboard; public final monitor; public WindowsMachine() { monitor = new monitor(); //instance of monitor class keyboard = new keyboard(); //instance of keyboard class } } Now we can work on the Windows machine with the help of a keyboard and mouse. But we still face the problem. Because we have tightly coupled the three classes together by using the new keyword. It is hard o test the class windows machine. To make the code loosely coupled, we decouple the WindowsMachine from the keyboard by using the Keyboard interface and this keyword. Keyboard.java public interface Keyboard { //functionality } WindowsMachine.java public class WindowsMachine { private final Keyboard keyboard; private final Monitor monitor; public WindowsMachine(Keyboard keyboard, Monitor monitor) { this.keyboard = keyboard; this.monitor = monitor; } } In the above code, we have used the dependency injection to add the keyboard dependency in the WindowsMachine class. Therefore, we have decoupled the classes.

How to solve the producer consumer problem, in Java specifically?

The producer consumer problem can be resolved using semaphores. The codes for the producer and consumer process are given as follows − Producer Process The code that defines the producer process is given below − do { . . PRODUCE ITEM . wait(empty); wait(mutex); . . PUT ITEM IN BUFFER . signal(mutex); signal(full); } while(1); In the above code, mutex, empty and full are semaphores. Here mutex is initialized to 1, empty is initialized to n (maximum size of the buffer) and full is initialized to 0. The mutex semaphore ensures mutual exclusion. The empty and full semaphores count the number of empty and full spaces in the buffer. After the item is produced, wait operation is carried out on empty. This indicates that the empty space in the buffer has decreased by 1. Then the wait operation is carried out on mutex so that consumer process cannot interfere. After the item is put in the buffer, signal operation is carried out on mutex and full. The former indicates that consumer process can now act and the latter shows that the buffer is full by 1. Consumer Process The code that defines the consumer process is given below: do { wait(full); wait(mutex); . . . REMOVE ITEM FROM BUFFER . signal(mutex); signal(empty); . . CONSUME ITEM . } while(1); The wait operation is carried out on full. This indicates that items in the buffer have decreased by 1. Then wait operation is carried out on mutex so that producer process cannot interfere. Then the item is removed from buffer. After that, signal operation is carried out on mutex and empty. The former indicates that consumer process can now act and the latter shows that the empty space in the buffer has increased by 1. https://crunchify.com/java-producer-consumer-example-handle-concurrent-read-write/ // function solution(arr){ // let finalInt = 0; // for(let i = 0; i<arr.length; i++){ // if (!arr.includes(arr[i] + 1)){ // if (arr[i] !== Math.abs(arr[i])){ // finalInt = 1; // } else { // finalInt = arr[i] + 1; // } // } // } // return finalInt; // } // solution([-3, -5])

Single Responsibility Principle with example

The single responsibility principle states that every Java class must perform a single functionality. Implementation of multiple functionalities in a single class mashup the code and if any modification is required may affect the whole class. It precise the code and the code can be easily maintained. Let's understand the single responsibility principle through an example. Suppose, Student is a class having three methods namely printDetails(), calculatePercentage(), and addStudent(). Hence, the Student class has three responsibilities to print the details of students, calculate percentages, and database. By using the single responsibility principle, we can separate these functionalities into three separate classes to fulfill the goal of the principle. Student.java public class Student { public void printDetails(); { //functionality of the method } pubic void calculatePercentage(); { //functionality of the method } public void addStudent(); { //functionality of the method } } The above code snippet violates the single responsibility principle. To achieve the goal of the principle, we should implement a separate class that performs a single functionality only. Student.java public class Student { public void addStudent(); { //functionality of the method } } PrintStudentDetails.java public class PrintStudentDetails { public void printDetails(); { //functionality of the method } } Percentage.java public class Percentage { public void calculatePercentage(); { //functionality of the method } } Hence, we have achieved the goal of the single responsibility principle by separating the functionality into three separate classes.

How is the JVM cross-platform?

There are interpreters for it for different platforms: 1. Macs 2. Windows 3. Linux

What does the JVM do?

Whenever you write java command on the command prompt to run the java class, an instance of JVM is created. The JVM performs following operations: 1. Loads code 2. Verifies code 3. Executes code 4. Provides runtime environment JVM provides definitions for the: 1. Memory area 2. Class file format 3. Register set 4. Garbage-collected heap 5. Fatal error reporting etc. 1) Classloader Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the classfiles from classpath. By default, classpath is set to current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader. //Let's see an example to print the classloader name public class ClassLoaderExample { public static void main(String[] args) { // Let's print the classloader name of current class. //Application/System classloader will load this class Class c=ClassLoaderExample.class; System.out.println(c.getClassLoader()); //If we print the classloader name of String, it will print null because it is an //in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader System.out.println(String.class.getClassLoader()); } } Test it Now Output: sun.misc.Launcher$AppClassLoader@4e0e2f2a null These are the internal classloaders provided by Java. If you want to create your own classloader, you need to extend the ClassLoader class. 2) Class(Method) Area Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods. 3) Heap It is the runtime data area in which objects are allocated. 4) Stack Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes. 5) Program Counter Register PC (program counter) register contains the address of the Java virtual machine instruction currently being executed. 6) Native Method Stack It contains all the native methods used in the application. 7) Execution Engine It contains: A virtual processor Interpreter: Read bytecode stream then execute the instructions. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU. 8) Java Native Interface Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries.


संबंधित स्टडी सेट्स

Ch 29 Management of Patients with Nonmalignant Hematologic Disorders

View Set

Psych Nursing Anxiety Disorders PrepU

View Set

Unit 3: Boolean Expression and if Statements Quizzes

View Set

Contracts - GA Salesperson Exam Prep Edge: National & State Portions

View Set

Section 5.1 Pure Substances and MIxtures

View Set

Psych Videbeck Chapter 20: Eating Disorders

View Set

How do some marketers make use of the concept of stimulus generalization?

View Set