diff --git "a/Clara-Training-Data - Sheet1 (1).csv" "b/Clara-Training-Data - Sheet1 (1).csv" new file mode 100644--- /dev/null +++ "b/Clara-Training-Data - Sheet1 (1).csv" @@ -0,0 +1,28656 @@ +Question,Answer +Who are you?,I am Clara an AI Java chatbot created to help you learn Java. Ask me anything Java related and I'll do my best to answer it. +What is Java?,"Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming language. +Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his team changed the name from Oak to Java. " +Can you provide an example of Java Hello World program?,"Let's have a quick look at Java programming example. A detailed description of Hello Java example is available in next page. + +Simple.java: + +class Simple{ + public static void main(String args[]){ + System.out.println(""Hello Java""); + } +} +" +Could you provide examples of applications or platforms that leverage Java for their development?,"According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them are as follows: +- Desktop Applications such as acrobat reader, media player, antivirus, etc. +- Web Applications such as irctc.co.in, javatpoint.com, etc. +- Enterprise Applications such as banking applications. +- Mobile +- Embedded System +- Smart Card +- Robotics +- Games, etc. +" +What are the Types of Java Applications?,"There are mainly 4 types of applications that can be created using Java programming: + + +1) Standalone Application + +Standalone applications are also known as desktop applications or window-based applications. These are traditional software that we need to install on every machine. +Examples of standalone applications are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications. + +2) Web Application + +An application that runs on the server side and creates a dynamic page is called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in Java. + +3) Enterprise Application + +An application that is distributed in nature, such as banking applications, etc. is called an enterprise application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for creating enterprise applications. + +4) Mobile Application + +An application which is created for mobile devices is called a mobile application. Currently, Android and Java ME are used for creating mobile applications. +" +What are the Java Platforms / Editions ?,"There are 4 platforms or editions of Java: +1) Java SE (Java Standard Edition) + +It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc. + +2) Java EE (Java Enterprise Edition) + +It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc. + +3) Java ME (Java Micro Edition) + +It is a micro platform that is dedicated to mobile applications. + +4) JavaFX + +It is used to develop rich internet applications. It uses a lightweight user interface API. " +Can you elaborate the History of Java ?,"The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced technology for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was best suited for internet programming. Later, Java technology was incorporated by Netscape. + +The principles for creating Java programming were ""Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic"". Java was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early '90s. + +Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are given significant points that describe the history of Java. + +1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team. +2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes. +3) Firstly, it was called ""Greentalk"" by James Gosling, and the file extension was .gt. +4) After that, it was called Oak and was developed as a part of the Green project. +" +"Why Java was named as ""Oak""?","5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany, Romania, etc. + +6) In 1995, Oak was renamed as ""Java"" because it was already a trademark by Oak Technologies. " +"Why Java Programming named ""Java""?","7) Why had they chose the name Java for Java language? The team gathered to choose a new name. The suggested words were ""dynamic"", ""revolutionary"", ""Silk"", ""jolt"", ""DNA"", etc. They wanted something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say. + +According to James Gosling, ""Java was one of the top choices along with Silk"". Since Java was so unique, most of the team members preferred Java than other names. + +8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office. + +9) Notice that Java is just a name, not an acronym. + +10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995. + +11) In 1995, Time magazine called Java one of the Ten Best Products of 1995. + +12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added to the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile applications, cards, etc. Each new version adds new features in Java. " +Can you outline the evolution of Java versions from its initial release to the current stable release?,"Many java versions have been released till now. The current stable release of Java is Java SE 10. + +1) JDK Alpha and Beta (1995) +2) JDK 1.0 (23rd Jan 1996) +3) JDK 1.1 (19th Feb 1997) +4) J2SE 1.2 (8th Dec 1998) +5) J2SE 1.3 (8th May 2000) +6) J2SE 1.4 (6th Feb 2002) +7) J2SE 5.0 (30th Sep 2004) +8) Java SE 6 (11th Dec 2006) +9) Java SE 7 (28th July 2011) +10) Java SE 8 (18th Mar 2014) +11) Java SE 9 (21st Sep 2017) +12) Java SE 10 (20th Mar 2018) +13) Java SE 11 (September 2018) +14) Java SE 12 (March 2019) +15) Java SE 13 (September 2019) +16) Java SE 14 (Mar 2020) +17) Java SE 15 (September 2020) +18) Java SE 16 (Mar 2021) +19) Java SE 17 (September 2021) +20) Java SE 18 (to be released by March 2022) + +Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version is release in March month and an odd version released in September month. +" +What are the Features of Java?,"The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords. + +A list of the most important features of the Java language is given below. + +1) Simple +2) Object-Oriented +3) Portable +4) Platform independent +5) Secured +6) Robust +7) Architecture neutral +8) Interpreted +9) High Performance +10) Multithreaded +11) Distributed +12) Dynamic +" +Is Java easy to learn?,"Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because: + +-Java syntax is based on C++ (so easier for programmers to learn it after C++). +-Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. +-There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java." +Is Java Object-oriented?,"Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior. + +Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. + +Basic concepts of OOPs are: + +1) Object +2) Class +3) Inheritance +4) Polymorphism +5) Abstraction +6) Encapsulation +" +Is Java Platform Independent?,"Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in which a program runs. + +There are two types of platforms software-based and hardware-based. Java provides a software-based platform. + +The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other hardware-based platforms. It has two components: + +1) Runtime Environment +2) API(Application Programming Interface) + +Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA). +" +Is Java Secured?,"Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because: + +-No explicit pointer +-Java Programs run inside a virtual machine sandbox +-Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources. +-Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects. +-Security Manager: It determines what resources a class can access such as reading and writing to the local disk. + +Java language provides these securities by default. Some security can also be provided by an application developer explicitly through SSL, JAAS, Cryptography, etc. " +Is Java Robust?,"The English mining of Robust is strong. Java is robust because: + +-It uses strong memory management. +-There is a lack of pointers that avoids security problems. +-Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. +-There are exception handling and the type checking mechanism in Java. All these points make Java robust. " +Is Java Architecture-neutral?,"Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed. + +In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java. " +Is Java Portable?,Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. +What is the level of performance of Java?,"Java is faster than other traditional interpreted programming languages because Java bytecode is ""close"" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc." +Is Java Distributed?,Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet. +Is Java Multi-threaded?,"A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc." +Is Java Dynamic?,"Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. + +Java supports dynamic compilation and automatic memory management (garbage collection). " +Can you compare C++ to Java?,"There are many differences and similarities between the C++ programming language and Java. A list of top differences between C++ and Java are given below: + +Platform-independent: C++ is platform-dependent while Java is platform-independent. + +Mainly used for: C++ is mainly used for system programming while Java is mainly used for application programming. It is widely used in Windows-based, web-based, enterprise, and mobile applications. + +Design Goal: C++ was designed for systems and applications programming. It was an extension of the C programming language while Java was designed and created as an interpreter for printing systems but later extended as a support network computing. It was designed to be easy to use and accessible to a broader audience. + +Goto: C++ supports the goto statement while Java doesn't support the goto statement. + +Multiple inheritance: C++ supports multiple inheritance while Java doesn't support multiple inheritance through class. It can be achieved by using interfaces in java. + +Operator Overloading: C++ supports operator overloading while Java doesn't support operator overloading. + +Pointers: C++ supports pointers. You can write a pointer program in C++ while Java supports pointer internally. However, you can't write the pointer program in java. It means java has restricted pointer support in java. + +Compiler and Interpreter: C++ uses compiler only. C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependent while Java uses both compiler and interpreter. Java source code is converted into bytecode at compilation time. The interpreter executes this bytecode at runtime and produces output. Java is interpreted that is why it is platform-independent. + +Call by Value and Call by reference: C++ supports both call by value and call by reference while Java supports call by value only. There is no call by reference in java. + +Structure and Union: C++ supports structures and unions while Java doesn't support structures and unions. + +Thread Support: C++ doesn't have built-in support for threads. It relies on third-party libraries for thread support while Java has built-in thread support. + +Documentation comment: C++ doesn't support documentation comments while Java supports documentation comment (/** ... */) to create documentation for java source code. + +Virtual Keyword: C++ supports virtual keyword so that we can decide whether or not to override a function. Java has no virtual keyword. We can override all non-static methods by default. In other words, non-static methods are virtual by default. + +unsigned right shift >>> : C++ doesn't support >>> operator while Java supports unsigned right shift >>> operator that fills zero at the top for the negative numbers. For positive numbers, it works same like >> operator. + +Inheritance Tree: C++ always creates a new inheritance tree while Java always uses a single inheritance tree because all classes are the child of the Object class in Java. The Object class is the root of the inheritance tree in java. + +Hardware: C++ is nearer to hardware while Java is not so interactive with hardware. + +Object-oriented: C++ is an object-oriented language. However, in the C language, a single root hierarchy is not possible while Java is also an object-oriented language. However, everything (except fundamental types) is an object in Java. It is a single root hierarchy as everything gets derived from java.lang.Object. " +Can you provide a Java Hello World Example?,"The requirement for Java Hello World Example +For executing any Java program, the following software or application must be properly installed. + +Install the JDK if you don't have installed it, download the JDK and install it. +Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java +Create the Java program +Compile and run the Java program + +Creating Hello World Example + +Let's create the hello java program: + +class Simple{ + public static void main(String args[]){ + System.out.println(""Hello Java""); + } +} + +Save the above file as Simple.java. + +To compile: +javac Simple.java + +To execute: +java Simple + +Output: +Hello Java + +Compilation Flow: + +When we compile Java program using javac tool, the Java compiler converts the source code into byte code. +Parameters used in First Java Program + +Let's see what is the meaning of class, public, static, void, main, String[], System.out.println(). + +-class keyword is used to declare a class in Java. +-public keyword is an access modifier that represents visibility. It means it is visible to all. +-static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main() method is executed by the JVM, so it doesn't require creating an object to invoke the main() method. So, it saves memory. +-void is the return type of the method. It means it doesn't return any value. +-main represents the starting point of the program. +-String[] args or String args[] is used for command line argument. We will discuss it in coming section. +-System.out.println() is used to print statement. Here, System is a class, out is an object of the PrintStream class, println() is a method of the PrintStream class. We will discuss the internal working of System.out.println() statement in the coming section. + +To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories -> Notepad and write a simple program: + +Class simple{ +Public static void main(String args[]){ +System.out.println(“Hello Java”); +} +} + +write the simple program of Java in notepad and saved it as Simple.java. In order to compile and run the above program, you need to open the command prompt by start menu -> All Programs -> Accessories -> command prompt. + +To compile and run the above program, go to your current directory first; my current directory is c:\new. Write here: + +To compile: +javac Simple.java +To execute: +java Simple " +In how many ways we can write a Java program?,"There are many ways to write a Java program. The modifications that can be done in a Java program are given below: + +1) By changing the sequence of the modifiers, method prototype is not changed in Java. + +Let's see the simple code of the main method. + +static public void main(String args[]) + +2) The subscript notation in the Java array can be used after type, before the variable or after the variable. + +Let's see the different codes to write the main method. + +public static void main(String[] args) +public static void main(String []args) +public static void main(String args[]) + +3) You can provide var-args support to the main() method by passing 3 ellipses (dots) + +Let's see the simple code of using var-args in the main() method. We will learn about var-args later in the Java New Features chapter. + +public static void main(String... args) + + +4) Having a semicolon at the end of class is optional in Java. + +Let's see the simple code. + +class A{ +static public void main(String... args){ +System.out.println(""hello java4""); +} +}; + +" +What are the valid Java main() method signatures?,"public static void main(String[] args) +public static void main(String []args) +public static void main(String args[]) +public static void main(String... args) +static public void main(String[] args) +public static final void main(String[] args) +final public static void main(String[] args) +final strictfp public static void main(String[] args) +" +What are the invalid Java main() method signatures?,"public void main(String[] args) +static void main(String[] args) +public void static main(String[] args) +abstract public static void main(String[] args) " +"Resolving an error ""javac is not recognized as an internal or external command""?","If there occurs a problem like displayed in the below figure, you need to set a path. Since DOS doesn't recognize javac and java as internal or external command. To overcome this problem, we need to set a path. The path is not required in a case where you save your program inside the JDK/bin directory. However, it is an excellent approach to set the path. " +What happens at compile time?,"At compile time, the Java file is compiled by Java Compiler (It does not interact with OS) and converts the Java code into bytecode. " +What happens at runtime?,"At runtime, the following steps are performed: + +Class File →Classloader→Bytecode Verified→Interpreter→Runtime→Hardware + +Classloader: It is the subsystem of JVM that is used to load class files. + +Bytecode Verifier: Checks the code fragments for illegal code that can violate access rights to objects. + +Interpreter: Read bytecode stream then execute the instructions. " +Can you save a Java source file by another name than the class name?,"Yes, if the class is not public. + +To compile: +javac Hard.java +To execute: +java Simple + +Observe that, we have compiled the code with file name but running the program with class name. Therefore, we can save a Java program other than class name. " +How to set path in Java?,"The path is required to be set for using tools such as javac, java, etc. +If you are saving the Java source file inside the JDK/bin directory, the path is not required to be set because all the tools will be available in the current directory. +However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path of JDK. +1.Temporary +2.Permanent" +How to set the Temporary Path of JDK in Windows?,"To set the temporary path of JDK, you need to follow the following steps: + -Open the command prompt +-Copy the path of the JDK/bin directory +-Write in command prompt: set path=copied_path" +"What are the Difference between JDK, JRE, and JVM?","We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See the brief overview of JVM here. +If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see the differences between the JDK, JRE, and JVM. +JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs which are written in other languages and compiled to Java bytecode. +JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the JVM: specification, implementation, and instance. +The JVM performs the following main tasks: +-Loads code +-Verifies code +-Executes code +-Provides runtime environment +JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime. +JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. + +JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation: +-Standard Edition Java Platform +-Enterprise Edition Java Platform +-Micro Edition Java Platform +The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java Application." +What is JVM (Java Virtual Machine)?,"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). +1.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. +2.An implementation Its implementation is known as JRE (Java Runtime Environment). +3.Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created. +The JVM performs following operation: +-Loads code +-Verifies code +-Executes code +-Provides runtime environment +JVM provides definitions for the: +-Memory area +-Class file format +-Register set +Garbage-collected heap +Fatal error reporting etc." +Can you help me understand JVM Architecture?,"Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine 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()); + } +} + + +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. +" +What is Java Variables?,"A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type. +Variable is a name of memory location. There are three types of variables in java: local, instance and static. +There are two types of data types in Java: primitive and non-primitive. +" +What are the Types of Variables in Java?,"There are three types of variables in Java: +-local variable +-instance variable +-static variable" +Can you provide an Example to understand the types of variables in java?,"1) Local Variable +A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. +A local variable cannot be defined with ""static"" keyword. +2) Instance Variable +A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static. +It is called an instance variable because its value is instance-specific and is not shared among instances. +3) Static variable +A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory." +Can you provide Java Variable Example: Add Two Numbers?,"public class Simple{ +public static void main(String[] args){ +int a=10; +int b=10; +int c=a+b; +System.out.println(c); +} +} +Output: 20" +Can you provide Java Variable Example: Widening?,"public class Simple{ +public static void main(String[] args){ +int a=10; +float f=a; +System.out.println(a); +System.out.println(f); +}} +Output: 10 +10.0" +Can you provide Java Variable Example: Narrowing (Typecasting)?,"public class Simple{ +public static void main(String[] args){ +float f=10.5f; +//int a=f;//Compile time error +int a=(int)f; +System.out.println(f); +System.out.println(a); +}} +Output: 10.5 +10" +Can you provide Java Variable Example: Overflow?,"class Simple{ +public static void main(String[] args){ +//Overflow +int a=130; +byte b=(byte)a; +System.out.println(a); +System.out.println(b); +}} +Output: 130 +-126" +Can you provide Java Variable Example: Adding Lower Type?,"class Simple{ +public static void main(String[] args){ +byte a=10; +byte b=10; +//byte c=a+b;//Compile Time Error: because a+b=20 will be int +byte c=(byte)(a+b); +System.out.println(c); +}} +Output: 20" +What is Data Types in Java?,"Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java: +1.Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. +2.Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays." +What is Java Primitive Data Types?,"In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language. +There are 8 types of primitive data types: +-boolean data type +-byte data type +-char data type +-short data type +-int data type +-long data type +-float data type +-double data type" +Why char uses 2 byte in java and what is \u0000 ?,"It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode system. To get detail explanation about Unicode visit next page. + " +Why java uses Unicode System?,"Before Unicode, there were many language standards: +ASCII (American Standard Code for Information Interchange) for the United States. +ISO 8859-1 for Western European Language. +KOI-8 for Russian. +GB18030 and BIG-5 for chinese, and so on." +What is Operators in Java?,"Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc. +There are many types of operators in Java which are given below: +-Unary Operator, +-Arithmetic Operator, +-Shift Operator, +-Relational Operator, +-Bitwise Operator, +-Logical Operator, +-Ternary Operator and +-Assignment Operator." +What are the Java Operator Precedence?,"Java Operator Precedence + +Operator type: Unary +Category: postfix + Precedence: expr++ expr-- +Category: prefix + Precedence: ++expr --expr +expr -expr ~ ! + +Operator type: Arithmetic +Category: multiplicative + Precedence: * / % +Category: additive + Precedence: + - + +Operator type: Shift +Category: shift + Precedence: << >> >>> + +Operator type: Relational +Category: comparison + Precedence: < > <= >= instanceof +Category: equality + Precedence: == != + +Operator type: Bitwise +Category: bitwise AND + Precedence: & +Category: bitwise exclusive OR + Precedence: ^ +Category: bitwise inclusive OR + Precedence: | + +Operator type: Logical +Category: logical AND + Precedence: && +Category: logical OR + Precedence: || + +Operator type: Ternary +Category: ternary + Precedence: ? : + +Operator type: Assignment +Category: assignment + Precedence: = += -= *= /= %= &= ^= |= <<= >>= >>>= + " +What is Java Unary Operator?,"The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.: +-incrementing/decrementing a value by one +-negating an expression +-inverting the value of a boolean" +Can you provide an example of Java Unary Operator?,"public class OperatorExample{ +public static void main(String args[]){ +int x=10; +System.out.println(x++);//10 (11) +System.out.println(++x);//12 +System.out.println(x--);//12 (11) +System.out.println(--x);//10 +}} +Output: +10 +12 +12 +10" +Can you provide an example of Java Unary Operator ++ and -- ?,"public class OperatorExample{ +public static void main(String args[]){ +int a=10; +int b=10; +System.out.println(a++ + ++a);//10+12=22 +System.out.println(b++ + b++);//10+11=21 +}} +Output: +22 +21" +Can you provide an example of Java Unary Operator ~ and ! ?,"public class OperatorExample{ +public static void main(String args[]){ +int a=10; +int b=-10; +boolean c=true; +boolean d=false; +System.out.println(~a);//-11 (minus of total positive value which starts from 0) +System.out.println(~b);//9 (positive of total minus, positive starts from 0) +System.out.println(!c);//false (opposite of boolean value) +System.out.println(!d);//true +}} +Output: +-11 +9 +false +true" +What is Java Arithmetic Operators?,"Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations." +Can you provide an example of Java Arithmetic Operator?,"public class OperatorExample{ +public static void main(String args[]){ +int a=10; +int b=5; +System.out.println(a+b);//15 +System.out.println(a-b);//5 +System.out.println(a*b);//50 +System.out.println(a/b);//2 +System.out.println(a%b);//0 +}} +Output: +15 +5 +50 +2 +0" +Can you provide an example of Java Arithmetic Operator Expression?,"public class OperatorExample{ +public static void main(String args[]){ +System.out.println(10*10/5+3-1*4/2); +}} +Output: +21" +What is Java Left Shift Operator?,"The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times. +" +Can you provide an example of Java Left Shift Operator Example ?,"public class OperatorExample{ +public static void main(String args[]){ +System.out.println(10<<2);//10*2^2=10*4=40 +System.out.println(10<<3);//10*2^3=10*8=80 +System.out.println(20<<2);//20*2^2=20*4=80 +System.out.println(15<<4);//15*2^4=15*16=240 +}} +Output: +40 +80 +80 +240" +What is Java Right Shift Operator?,The Java right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand. +Can you provide an example of Java Right Shift Operator?,"public OperatorExample{ +public static void main(String args[]){ +System.out.println(10>>2);//10/2^2=10/4=2 +System.out.println(20>>2);//20/2^2=20/4=5 +System.out.println(20>>3);//20/2^3=20/8=2 +}} +Output: +2 +5 +2" +Can you provide an example of Java Shift Operator >> vs >>> ?,"public class OperatorExample{ +public static void main(String args[]){ + //For positive number, >> and >>> works same + System.out.println(20>>2); + System.out.println(20>>>2); + //For negative number, >>> changes parity bit (MSB) to 0 + System.out.println(-20>>2); + System.out.println(-20>>>2); +}} +Output: +5 +5 +-5 +1073741819" +Can you provide an example of Java AND Operator Logical && and Bitwise &?,"The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true. + +The bitwise & operator always checks both conditions whether first condition is true or false. + +public class OperatorExample{ +public static void main(String args[]){ +int a=10; +int b=5; +int c=20; +System.out.println(ab||ab|ab||a++b|a++ 20) { +System.out.println(""x + y is greater than 20""); +} +} +} +Output: +x + y is greater than 20" +Can you provide an example of if-else statement in Java?,"The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false. +Syntax: +if(condition) { +statement 1; //executes when condition is true +} +else{ +statement 2; //executes when condition is false +} +public class Student { +public static void main(String[] args) { +int x = 10; +int y = 12; +if(x+y < 10) { +System.out.println(""x + y is less than 10""); +} else { +System.out.println(""x + y is greater than 20""); +} +} +} +Output: +x + y is greater than 20" +"What is if-else-if ladder in Java? +","The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain. + +Syntax of if-else-if statement is given below. + +if(condition 1) { +statement 1; //executes when condition 1 is true +} +else if(condition 2) { +statement 2; //executes when condition 2 is true +} +else { +statement 2; //executes when all the conditions are false +} +public class Student { +public static void main(String[] args) { +String city = ""Delhi""; +if(city == ""Meerut"") { +System.out.println(""city is meerut""); +}else if (city == ""Noida"") { +System.out.println(""city is noida""); +}else if(city == ""Agra"") { +System.out.println(""city is agra""); +}else { +System.out.println(city); +} +} +} +Output: +Delhipublic class Student { +public static void main(String[] args) { +String city = ""Delhi""; +if(city == ""Meerut"") { +System.out.println(""city is meerut""); +}else if (city == ""Noida"") { +System.out.println(""city is noida""); +}else if(city == ""Agra"") { +System.out.println(""city is agra""); +}else { +System.out.println(city); +} +} +} +Output: +Delhi" +What is Nested if-statement in Java?,"In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement. + +Syntax of Nested if-statement is given below. +if(condition 1) { +statement 1; //executes when condition 1 is true +if(condition 2) { +statement 2; //executes when condition 2 is true +} +else{ +statement 2; //executes when condition 2 is false +} +} In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement. + +Syntax of Nested if-statement is given below. + +if(condition 1) { +statement 1; //executes when condition 1 is true +if(condition 2) { +statement 2; //executes when condition 2 is true +} +else{ +statement 2; //executes when condition 2 is false +} +} +public class Student { +public static void main(String[] args) { +String address = ""Delhi, India""; + +if(address.endsWith(""India"")) { +if(address.contains(""Meerut"")) { +System.out.println(""Your city is Meerut""); +}else if(address.contains(""Noida"")) { +System.out.println(""Your city is Noida""); +}else { +System.out.println(address.split("","")[0]); +} +}else { +System.out.println(""You are not living in India""); +} +} +} +Output: +Delhi" +What is Switch Statement in Java?,"In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program. +Points to be noted about switch statement: +-The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java +-Cases cannot be duplicate +-Default statement is executed when any of the case doesn't match the value of expression. It is optional. +-Break statement terminates the switch block when the condition is satisfied. +-It is optional, if not used, next case is executed. +-While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value." +"What is for loop in Java? +","in Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code. + +for(initialization, condition, increment/decrement) { +//block of statements +} +public class Calculattion { +public static void main(String[] args) { +// TODO Auto-generated method stub +int sum = 0; +for(int j = 1; j<=10; j++) { +sum = sum + j; +} +System.out.println(""The sum of first 10 natural numbers is "" + sum); +} +} +Output: +The sum of first 10 natural numbers is 55" +What is for-each loop in Java?,"Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given below. + +for(data_type var : array_name/collection_name){ +//statements +} +Consider the following example to understand the functioning of the for-each loop in Java. +public class Calculation { +public static void main(String[] args) { +// TODO Auto-generated method stub +String[] names = {""Java"",""C"",""C++"",""Python"",""JavaScript""}; +System.out.println(""Printing the content of the array names:\n""); +for(String name:names) { +System.out.println(name); +} +} +} +Output: +Printing the content of the array names: +Java +C +C++ +Python +JavaScript" +What is while loop in Java?,"The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop. + +It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed. + +The syntax of the while loop is given below. +The syntax of the while loop is given below. + +while(condition){ +//looping statements +} +public class Calculation { +public static void main(String[] args) { +// TODO Auto-generated method stub +int i = 0; +System.out.println(""Printing the list of first 10 even numbers \n""); +while(i<=10) { +System.out.println(i); +i = i + 2; +} +} +} +Output: +Printing the list of first 10 even numbers +0 +2 +4 +6 +8 +10" +"What is do-while loop in Java? +","The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of iteration is not known and we have to execute the loop at least once, we can use do-while loop. +It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below. +do +{ +//statements +} while (condition);" +What is Jump Statements?,"Consider the following example to understand the functioning of the do-while loop in Java. +Calculation.java +public class Calculation { +public static void main(String[] args) { +// TODO Auto-generated method stub +int i = 0; +System.out.println(""Printing the list of first 10 even numbers \n""); +do { +System.out.println(i); +i = i + 2; +}while(i<=10); +} +} +Output: +Printing the list of first 10 even numbers +0 +2 +4 +6 +8 +10" +What isJava break statement?,"As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop. +The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch statement. +The break statement example with for loop +Consider the following example in which we have used the break statement with the for loop. +BreakExample.java +public class BreakExample { +public static void main(String[] args) { +// TODO Auto-generated method stub +for(int i = 0; i<= 10; i++) { +System.out.println(i); +if(i==6) { +break; +} +} +} +} +Output: +0 +1 +2 +3 +4 +5 +6" +What is Java continue statement?,"Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the loop immediately. +Consider the following example to understand the functioning of the continue statement in Java. +public class ContinueExample { +public static void main(String[] args) { +// TODO Auto-generated method stub +for(int i = 0; i<= 2; i++) { +for (int j = i; j<=5; j++) { +if(j == 4) { +continue; +} +System.out.println(j); +} +} +} + +} +Output: +0 +1 +2 +3 +5 +1 +2 +3 +5 +2 +3 +5" +What is Java If-else Statement?,"The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java. +-if statement +-if-else statement +-if-else-if ladder +-nested if statement" +What is Java if Statement?,"The Java if statement tests the condition. It executes the if block if condition is true. + +Syntax: + +if(condition){ +//code to be executed +} +Example: +//Java Program to demonstate the use of if statement. +public class IfExample { +public static void main(String[] args) { + //defining an 'age' variable + int age=20; + //checking the age + if(age>18){ + System.out.print(""Age is greater than 18""); + } +} +} +Output: +Age is greater than 18" +What is Java if-else Statement?,"The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed. + +Syntax: + +if(condition){ +//code if condition is true +}else{ +//code if condition is false +} +Example: + +//A Java Program to demonstrate the use of if-else statement. +//It is a program of odd and even number. +public class IfElseExample { +public static void main(String[] args) { + //defining a variable + int number=13; + //Check if the number is divisible by 2 or not + if(number%2==0){ + System.out.println(""even number""); + }else{ + System.out.println(""odd number""); + } +} +} +Output: +odd number" +How to use Ternary Operator in Java?,"We can also use ternary operator (? :) to perform the task of if...else statement. It is a shorthand way to check the condition. If the condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned. +Example: +public class IfElseTernaryExample { +public static void main(String[] args) { + int number=13; + //Using ternary operator + String output=(number%2==0)?""even number"":""odd number""; + System.out.println(output); +} +} +Output: +odd number" +What is Java if-else-if ladder Statement?,"The if-else-if ladder statement executes one condition from multiple statements. +Syntax: +if(condition1){ +//code to be executed if condition1 is true +}else if(condition2){ +//code to be executed if condition2 is true +} +else if(condition3){ +//code to be executed if condition3 is true +} +... +else{ +//code to be executed if all the conditions are false +} +Example: +//Java Program to demonstrate the use of If else-if ladder. +//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+. +public class IfElseIfExample { +public static void main(String[] args) { + int marks=65; + + if(marks<50){ + System.out.println(""fail""); + } + else if(marks>=50 && marks<60){ + System.out.println(""D grade""); + } + else if(marks>=60 && marks<70){ + System.out.println(""C grade""); + } + else if(marks>=70 && marks<80){ + System.out.println(""B grade""); + } + else if(marks>=80 && marks<90){ + System.out.println(""A grade""); + }else if(marks>=90 && marks<100){ + System.out.println(""A+ grade""); + }else{ + System.out.println(""Invalid!""); + } +} +} +Output: +C grade" +What is Java Nested if statement?,"The nested if statement represents the if block within another if block. Here, the inner if block condition executes only when outer if block condition is true. +Syntax: + +if(condition){ + //code to be executed + if(condition){ + //code to be executed + } +} +Example: + +//Java Program to demonstrate the use of Nested If Statement. +public class JavaNestedIfExample { +public static void main(String[] args) { + //Creating two variables for age and weight + int age=20; + int weight=80; + //applying condition on age and weight + if(age>=18){ + if(weight>50){ + System.out.println(""You are eligible to donate blood""); + } + } +}} +Output: +You are eligible to donate blood" +What is Java Switch Statement?,"The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement. + +In other words, the switch statement tests the equality of a variable against multiple values. +" +Can you provide an example of Switch Example in java?,"SwitchExample.java + +public class SwitchExample { +public static void main(String[] args) { + //Declaring a variable for switch expression + int number=20; + //Switch expression + switch(number){ + //Case statements + case 10: System.out.println(""10""); + break; + case 20: System.out.println(""20""); + break; + case 30: System.out.println(""30""); + break; + //Default case statement + default:System.out.println(""Not in 10, 20 or 30""); + } +} +} +Output: +20" +Can you provide an example of Switch Month Example in java?,"//Java Program to demonstrate the example of Switch statement +//where we are printing month name for the given number +public class SwitchMonthExample { +public static void main(String[] args) { + //Specifying month number + int month=7; + String monthString=""""; + //Switch statement + switch(month){ + //case statements within the switch block + case 1: monthString=""1 - January""; + break; + case 2: monthString=""2 - February""; + break; + case 3: monthString=""3 - March""; + break; + case 4: monthString=""4 - April""; + break; + case 5: monthString=""5 - May""; + break; + case 6: monthString=""6 - June""; + break; + case 7: monthString=""7 - July""; + break; + case 8: monthString=""8 - August""; + break; + case 9: monthString=""9 - September""; + break; + case 10: monthString=""10 - October""; + break; + case 11: monthString=""11 - November""; + break; + case 12: monthString=""12 - December""; + break; + default:System.out.println(""Invalid Month!""); + } + //Printing month of the given number + System.out.println(monthString); +} +} +Output: +7 - July" +Can you provide an example of Switch Vowel Example in java?,"SwitchVowelExample.java + +public class SwitchVowelExample { +public static void main(String[] args) { + char ch='O'; + switch(ch) + { + case 'a': + System.out.println(""Vowel""); + break; + case 'e': + System.out.println(""Vowel""); + break; + case 'i': + System.out.println(""Vowel""); + break; + case 'o': + System.out.println(""Vowel""); + break; + case 'u': + System.out.println(""Vowel""); + break; + case 'A': + System.out.println(""Vowel""); + break; + case 'E': + System.out.println(""Vowel""); + break; + case 'I': + System.out.println(""Vowel""); + break; + case 'O': + System.out.println(""Vowel""); + break; + case 'U': + System.out.println(""Vowel""); + break; + default: + System.out.println(""Consonant""); + } +} +} +Output: + +Vowel" +Is Java Switch Statement is fall-through?,"Java Switch Statement is fall-through +The Java switch statement is fall-through. It means it executes all statements after the first match if a break statement is not present." +Can you provide an example of Java Switch Statement with String?,"Example: + +SwitchExample2.java +//Java Switch Example where we are omitting the +//break statement +public class SwitchExample2 { +public static void main(String[] args) { + int number=20; + //switch expression with int value + switch(number){ + //switch cases without break statements + case 10: System.out.println(""10""); + case 20: System.out.println(""20""); + case 30: System.out.println(""30""); + default:System.out.println(""Not in 10, 20 or 30""); + } +} +} +Output: +20 +30 +Not in 10, 20 or 30" +What is Java Nested Switch Statement?,"We can use switch statement inside other switch statement in Java. It is known as nested switch statement. + +Example: + +NestedSwitchExample.java + +//Java Program to demonstrate the use of Java Nested Switch +public class NestedSwitchExample { + public static void main(String args[]) + { + //C - CSE, E - ECE, M - Mechanical + char branch = 'C'; + int collegeYear = 4; + switch( collegeYear ) + { + case 1: + System.out.println(""English, Maths, Science""); + break; + case 2: + switch( branch ) + { + case 'C': + System.out.println(""Operating System, Java, Data Structure""); + break; + case 'E': + System.out.println(""Micro processors, Logic switching theory""); + break; + case 'M': + System.out.println(""Drawing, Manufacturing Machines""); + break; + } + break; + case 3: + switch( branch ) + { + case 'C': + System.out.println(""Computer Organization, MultiMedia""); + break; + case 'E': + System.out.println(""Fundamentals of Logic Design, Microelectronics""); + break; + case 'M': + System.out.println(""Internal Combustion Engines, Mechanical Vibration""); + break; + } + break; + case 4: + switch( branch ) + { + case 'C': + System.out.println(""Data Communication and Networks, MultiMedia""); + break; + case 'E': + System.out.println(""Embedded System, Image Processing""); + break; + case 'M': + System.out.println(""Production Technology, Thermal Engineering""); + break; + } + break; + } + } +} +Output: + +Data Communication and Networks, MultiMedia" +What is Java Enum in Switch Statement?,"Java allows us to use enum in switch statement. Java enum is a class that represent the group of constants. (immutable such as final variables). We use the keyword enum and put the constants in curly braces separated by comma. + +Example: + +JavaSwitchEnumExample.java + +//Java Program to demonstrate the use of Enum +//in switch statement +public class JavaSwitchEnumExample { + public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat } + public static void main(String args[]) + { + Day[] DayNow = Day.values(); + for (Day Now : DayNow) + { + switch (Now) + { + case Sun: + System.out.println(""Sunday""); + break; + case Mon: + System.out.println(""Monday""); + break; + case Tue: + System.out.println(""Tuesday""); + break; + case Wed: + System.out.println(""Wednesday""); + break; + case Thu: + System.out.println(""Thursday""); + break; + case Fri: + System.out.println(""Friday""); + break; + case Sat: + System.out.println(""Saturday""); + break; + } + } + } +} +Output: + +Sunday +Monday +Twesday +Wednesday +Thursday +Friday +Saturday" +What is Java Wrapper in Switch Statement?,"Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement. + +Example: + +WrapperInSwitchCaseExample.java + +//Java Program to demonstrate the use of Wrapper class +//in switch statement +public class WrapperInSwitchCaseExample { + public static void main(String args[]) + { + Integer age = 18; + switch (age) + { + case (16): + System.out.println(""You are under 18.""); + break; + case (18): + System.out.println(""You are eligible for vote.""); + break; + case (65): + System.out.println(""You are senior citizen.""); + break; + default: + System.out.println(""Please give the valid age.""); + break; + } + } +} +Output: + +You are eligible for vote." +What is Loops in Java?,"The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop. +There are three types of for loops in Java. + +-Simple for Loop +-For-each or Enhanced for Loop +-Labeled for Loop " +Can you provide an example of Java Simple for Loop?,"A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts: + +Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition. +Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition. +Increment/Decrement: It increments or decrements the variable value. It is an optional condition. +Statement: The statement of the loop is executed each time until the second condition is false. + + +Syntax: + +for(initialization; condition; increment/decrement){ +//statement or code to be executed +} + +Example: + +ForExample.java +//Java Program to demonstrate the example of for loop +//which prints table of 1 +public class ForExample { +public static void main(String[] args) { + //Code of Java for loop + for(int i=1;i<=10;i++){ + System.out.println(i); + } +} +} + +Output: +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +" +What is Java Nested for Loop?,"If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes. + +Example: +NestedForExample.java +public class NestedForExample { +public static void main(String[] args) { +//loop of i +for(int i=1;i<=3;i++){ +//loop of j +for(int j=1;j<=3;j++){ + System.out.println(i+"" ""+j); +}//end of i +}//end of j +} +} + +Output: +1 1 +1 2 +1 3 +2 1 +2 2 +2 3 +3 1 +3 2 +3 3 + +Pyramid Example 1: +PyramidExample.java +public class PyramidExample { +public static void main(String[] args) { +for(int i=1;i<=5;i++){ +for(int j=1;j<=i;j++){ + System.out.print(""* ""); +} +System.out.println();//new line +} +} +} + +Output: +* +* * +* * * +* * * * +* * * * * + +Pyramid Example 2: +PyramidExample2.java +public class PyramidExample2 { +public static void main(String[] args) { +int term=6; +for(int i=1;i<=term;i++){ +for(int j=term;j>=i;j--){ + System.out.print(""* ""); +} +System.out.println();//new line +} +} +} + +Output: +* * * * * * +* * * * * +* * * * +* * * +* * +* + " +"What is Java for-each Loop? +","The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. + +It works on the basis of elements and not the index. It returns element one by one in the defined variable. + +Syntax: + +for(data_type variable : array_name){ +//code to be executed +} + +Example: + +ForEachExample.java + + +//Java For-each loop example which prints the +//elements of the array +public class ForEachExample { +public static void main(String[] args) { + //Declaring an array + int arr[]={12,23,44,56,78}; + //Printing array using for-each loop + for(int i:arr){ + System.out.println(i); + } +} +} + +Output: + +12 +23 +44 +56 +78 + " +What is Java Labeled For Loop?,"We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop. + +Syntax: + +labelname: +for(initialization; condition; increment/decrement){ +//code to be executed +} + +Example: +LabeledForExample.java +//A Java program to demonstrate the use of labeled for loop +public class LabeledForExample { +public static void main(String[] args) { + //Using Label for outer and for loop + aa: + for(int i=1;i<=3;i++){ + bb: + for(int j=1;j<=3;j++){ + if(i==2&&j==2){ + break aa; + } + System.out.println(i+"" ""+j); + } + } +} +} + +Output: +1 1 +1 2 +1 3 +2 1 + + +If you use break bb;, it will break inner loop only which is the default behaviour of any loop. + + +LabeledForExample2.java + +public class LabeledForExample2 { +public static void main(String[] args) { + aa: + for(int i=1;i<=3;i++){ + bb: + for(int j=1;j<=3;j++){ + if(i==2&&j==2){ + break bb; + } + System.out.println(i+"" ""+j); + } + } +} +} + +Output: + +1 1 +1 2 +1 3 +2 1 +3 1 +3 2 +3 3 + " +What is Java Infinitive for Loop?,"If you use two semicolons ;; in the for loop, it will be infinitive for loop. + +Syntax: + +for(;;){ +//code to be executed +} + + +Example: + +ForExample.java + +//Java program to demonstrate the use of infinite for loop +//which prints an statement +public class ForExample { +public static void main(String[] args) { + //Using no condition in for loop + for(;;){ + System.out.println(""infinitive loop""); + } +} +} + +Output: + +infinitive loop +infinitive loop +infinitive loop +infinitive loop +infinitive loop +ctrl+c + " +"Can you explain the differences between the Java for loop, while loop, and do-while loop?","Java for Loop vs while Loop vs do-while Loop + +For loop +Introduction : The Java for loop is a control flow statement that iterates a part of the programs multiple times. +When to use : If the number of iteration is fixed, it is recommended to use for loop. +Syntax: for(init;condition;incr/decr){ +// code to be executed +} +Example : //for loop +for(int i=1;i<=10;i++){ +System.out.println(i); +} +Syntax for infinitive loop : for(;;){ +//code to be executed +} + +while loop +Introduction : The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition. +When to use : If the number of iteration is not fixed, it is recommended to use while loop. +Syntax: while(condition){ +//code to be executed +} +Example : //while loop +int i=1; +while(i<=10){ +System.out.println(i); +i++; +} +Syntax for infinitive loop : while(true){ +//code to be executed +} + +do-while loop +Introduction : The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition. +When to use : If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop. +Syntax: do{ +//code to be executed +}while(condition); +Example : //do-while loop +int i=1; +do{ +System.out.println(i); +i++; +}while(i<=10); +Syntax for infinitive loop : do{ +//code to be executed +}while(true); +" +What is Java While Loop?,"The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean condition is true. As soon as the Boolean condition becomes false, the loop automatically stops. + +The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is recommended to use the while loop. + +Syntax: + +while (condition){ +//code to be executed +I ncrement / decrement statement +} +The different parts of do-while loop: +1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. When the condition becomes false, we exit the while loop. +Example: +i <=100 +2. Update expression: Every time the loop body is executed, this expression increments or decrements loop variable. +Example: +i++; +" +What is Java Infinitive While Loop?,"If you pass true in the while loop, it will be infinitive while loop. + +Syntax: + +while(true){ +//code to be executed +} +Example: + +WhileExample2.java + +public class WhileExample2 { +public static void main(String[] args) { + // setting the infinite while loop by passing true to the condition + while(true){ + System.out.println(""infinitive while loop""); + } +} +} +Output: + +infinitive while loop +infinitive while loop +infinitive while loop +infinitive while loop +infinitive while loop +ctrl+c" +"What is Java do-while loop? +","The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use a do-while loop. + +Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while check the condition at the end of loop body. The Java do-while loop is executed at least once because condition is checked after loop body. + +Syntax: + +do{ +//code to be executed / loop body +//update statement +}while (condition); +The different parts of do-while loop: +1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. As soon as the condition becomes false, loop breaks automatically. +Example: +i <=100 +2. Update expression: Every time the loop body is executed, the this expression increments or decrements loop variable. +Example: +i++; +" +What is Java Infinitive do-while Loop?,"If you pass true in the do-while loop, it will be infinitive do-while loop. + +Syntax: + +do{ +//code to be executed +}while(true); +Example: + +DoWhileExample2.java + +public class DoWhileExample2 { +public static void main(String[] args) { + do{ + System.out.println(""infinitive do while loop""); + }while(true); +} +} +Output: + +infinitive do while loop +infinitive do while loop +infinitive do while loop +ctrl+c" +What is Java Break Statement?,"When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. + +The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. + +We can use Java break statement in all types of loops such as for loop, while loop and do-while loop. + +Syntax: + +jump-statement; +break; " +Can you provide an example of Java Break Statement with Loop?,"Example: + +BreakExample.java + +//Java Program to demonstrate the use of break statement +//inside the for loop. +public class BreakExample { +public static void main(String[] args) { + //using for loop + for(int i=1;i<=10;i++){ + if(i==5){ + //breaking the loop + break; + } + System.out.println(i); + } +} +} +Output: + +1 +2 +3 +4" +What is Java Break Statement with Inner Loop?,"It breaks inner loop only if you use break statement inside the inner loop. + +Example: +BreakExample2.java + +//Java Program to illustrate the use of break statement +//inside an inner loop +public class BreakExample2 { +public static void main(String[] args) { + //outer loop + for(int i=1;i<=3;i++){ + //inner loop + for(int j=1;j<=3;j++){ + if(i==2&&j==2){ + //using break statement inside the inner loop + break; + } + System.out.println(i+"" ""+j); + } + } +} +} +Output: + +1 1 +1 2 +1 3 +2 1 +3 1 +3 2 +3 3 +" +Can you provide an example of Java Break Statement with Labeled For Loop?,"We can use break statement with a label. The feature is introduced since JDK 1.5. So, we can break any loop in Java now whether it is outer or inner loop. + +Example: + +BreakExample3.java + +//Java Program to illustrate the use of continue statement +//with label inside an inner loop to break outer loop +public class BreakExample3 { +public static void main(String[] args) { + aa: + for(int i=1;i<=3;i++){ + bb: + for(int j=1;j<=3;j++){ + if(i==2&&j==2){ + //using break statement with label + break aa; + } + System.out.println(i+"" ""+j); + } + } +} +} +Output: + +1 1 +1 2 +1 3 +2 1 " +Can you provide an example of Java Break Statement in while loop?,"BreakWhileExample.java + +//Java Program to demonstrate the use of break statement +//inside the while loop. +public class BreakWhileExample { +public static void main(String[] args) { + //while loop + int i=1; + while(i<=10){ + if(i==5){ + //using break statement + i++; + break;//it will break the loop + } + System.out.println(i); + i++; + } +} +} +Output: + +1 +2 +3 +4 + +" +Can you provide an example of Java Break Statement in do-while loop?,"BreakDoWhileExample.java + +//Java Program to demonstrate the use of break statement +//inside the Java do-while loop. +public class BreakDoWhileExample { +public static void main(String[] args) { + //declaring variable + int i=1; + //do-while loop + do{ + if(i==5){ + //using break statement + i++; + break;//it will break the loop + } + System.out.println(i); + i++; + }while(i<=10); +} +} +Output: + +1 +2 +3 +4" +What is Java Continue Statement?,"The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately. It can be used with for loop or while loop. + +The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop only. + +We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop. + +Syntax: +jump-statement; +continue; " +Can you provide an example of Java Continue Statement Example?,"ContinueExample.java + +//Java Program to demonstrate the use of continue statement +//inside the for loop. +public class ContinueExample { +public static void main(String[] args) { + //for loop + for(int i=1;i<=10;i++){ + if(i==5){ + //using continue statement + continue;//it will skip the rest statement + } + System.out.println(i); + } +} +} +Output: + +1 +2 +3 +4 +6 +7 +8 +9 +10" +Can you provide an example of Java Continue Statement with Inner Loop?,"It continues inner loop only if you use the continue statement inside the inner loop. +ContinueExample2.java + +//Java Program to illustrate the use of continue statement +//inside an inner loop +public class ContinueExample2 { +public static void main(String[] args) { + //outer loop + for(int i=1;i<=3;i++){ + //inner loop + for(int j=1;j<=3;j++){ + if(i==2&&j==2){ + //using continue statement inside inner loop + continue; + } + System.out.println(i+"" ""+j); + } + } +} +} +Output: + +1 1 +1 2 +1 3 +2 1 +2 3 +3 1 +3 2 +3 3" +Can you provide an example of Java Continue Statement with Labelled For Loop?,"We can use continue statement with a label. This feature is introduced since JDK 1.5. So, we can continue any loop in Java now whether it is outer loop or inner. + +Example: + +ContinueExample3.java + +//Java Program to illustrate the use of continue statement +//with label inside an inner loop to continue outer loop +public class ContinueExample3 { +public static void main(String[] args) { + aa: + for(int i=1;i<=3;i++){ + bb: + for(int j=1;j<=3;j++){ + if(i==2&&j==2){ + //using continue statement with label + continue aa; + } + System.out.println(i+"" ""+j); + } + } +} +} +Output: + +1 1 +1 2 +1 3 +2 1 +3 1 +3 2 +3 3" +Can you provide an example of Java Continue Statement in while loop?,"ContinueWhileExample.java + +//Java Program to demonstrate the use of continue statement +//inside the while loop. +public class ContinueWhileExample { +public static void main(String[] args) { + //while loop + int i=1; + while(i<=10){ + if(i==5){ + //using continue statement + i++; + continue;//it will skip the rest statement + } + System.out.println(i); + i++; + } +} +} +Output: + +1 +2 +3 +4 +6 +7 +8 +9 +10" +Can you provide an example of Java Continue Statement in do-while Loop?,"ContinueDoWhileExample.java + +//Java Program to demonstrate the use of continue statement +//inside the Java do-while loop. +public class ContinueDoWhileExample { +public static void main(String[] args) { + //declaring variable + int i=1; + //do-while loop + do{ + if(i==5){ + //using continue statement + i++; + continue;//it will skip the rest statement + } + System.out.println(i); + i++; + }while(i<=10); +} +} +Output: + +1 +2 +3 +4 +6 +7 +8 +9 +10" +What is Java Comments?,"The Java comments are the statements in a program that are not executed by the compiler and interpreter. + " +Why do we use comments in a code?,"-Comments are used to make the program more readable by adding the details of the code. +-It makes easy to maintain the code and to find the errors easily. +-The comments can be used to provide information or explanation about the variable, method, class, or any statement. +-It can also be used to prevent the execution of program code while testing the alternative code. + + +" +What are the Types of Java Comments?,"There are three types of comments in Java. + +1) Single Line Comment +2 ) Multi Line Comment +3) Documentation Comment + + +" +What is Java Single Line Comment?,"The single-line comment is used to comment only one line of the code. It is the widely used and easiest way of commenting the statements. + +Single line comments starts with two forward slashes (//). Any text in front of // is not executed by Java. + +Syntax: + +//This is single line comment + +Let's use single line comment in a Java program. + +CommentExample1.java +public class CommentExample1 { +public static void main(String[] args) { +int i=10; // i is a variable with value 10 +System.out.println(i); //printing the variable i +} +} + +Output: +10 " +What is Java Multi Line Comment?,"The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line comments there). + +Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java. + +Syntax: + +/* +This +is +multi line +comment +*/ + +Let's use multi-line comment in a Java program. + +CommentExample2.java + +public class CommentExample2 { +public static void main(String[] args) { +/* Let's declare and + print variable in java. */ + int i=10; + System.out.println(i); +/* float j = 5.9; + float k = 4.4; + System.out.println( j + k ); */ +} +} + +Output: +10 +" +What is Java Documentation Comment?,"Documentation comments are usually used to write large programs for a project or software application as it helps to create documentation API. These APIs are needed for reference, i.e., which classes, methods, arguments, etc., are used in the code. + +To create documentation API, we need to use the javadoc tool. The documentation comments are placed between /** and */. + +Syntax: + +/** +* +*We can use various tags to depict the parameter +*or heading or author name +*We can also use HTML tags +* +*/ + + + +" +What is javadoc tags?,"javadoc tags +Some of the commonly used tags in documentation comments: + +Tag: {@docRoot} +Syntax: {@docRoot} +Description: to depict relative path to root directory of generated document from any page. + +Tag: @author +Syntax: @author name - text +Description: To add the author of the class + +Tag: @code +Syntax: {@code text} +Description: To show the text in code font without interpreting it as html markup or nested javadoc tag. + +Tag: @version +Syntax: @version version-text +Description: To specify ""Version"" subheading and version-text when -version option is used. + +Tag: @since +Syntax: @since release +Description: To add ""Since"" heading with since text to generated documentation. + +Tag: @param +Syntax: @param parameter-name description +Description: To add a parameter with given name and description to 'Parameters' section. + +Tag: @return +Syntax: @return description +Description: Required for every method that returns something (except void) + +Let's use the Javadoc tag in a Java program. + +Calculate.java + +import java.io.*; + +/** + *

Calculation of numbers

+ * This program implements an application + * to perform operation such as addition of numbers + * and print the result + *

+ * Note: Comments make the code readable and + * easy to understand. + * + * @author Anurati + * @version 16.0 + * @since 2021-07-06 + */ + + public class Calculate{ + /** + * This method calculates the summation of two integers. + * @param input1 This is the first parameter to sum() method + * @param input2 This is the second parameter to the sum() method. + * @return int This returns the addition of input1 and input2 + */ + public int sum(int input1, int input2){ + return input1 + input2; + } + /** + * This is the main method uses of sum() method. + * @param args Unused + * @see IOException + */ + public static void main(String[] args) { + Calculate obj = new Calculate(); + int result = obj.sum(40, 20); + + System.out.println(""Addition of numbers: "" + result); + } + } + +Compile it by javac tool: + +Create Document +Create documentation API by javadoc tool +Now, the HTML files are created for the Calculate class in the current directory, i.e., abcDemo. Open the HTML files, and we can see the explanation of Calculate class provided through the documentation comment. +" +"Are Java comments executable? ","As we know, Java comments are not executed by the compiler or interpreter, however, before the lexical transformation of code in compiler, contents of the code are encoded into ASCII in order to make the processing easy. + +Test.java + +public class Test{ + public static void main(String[] args) { + //the below comment will be executed +// \u000d System.out.println(""Java comment is executed!!""); + } +} + + +The above code generate the output because the compiler parses the Unicode character \u000d as a new line before the lexical transformation, and thus the code is transformed as shown below: + +Test.java + +public class Test{ + public static void main(String[] args) { + //the below comment will be executed +// +System.out.println(""Java comment is executed!!""); + } +} +Thus, the Unicode character shifts the print statement to next line and it is executed as a normal Java code. +" +Can you provide a list of Java Programs | Java Programming Examples?,"Java programs are frequently asked in the interview. These programs can be asked from control statements, array, string, oops etc. Java basic programs like fibonacci series, prime numbers, factorial numbers and palindrome numbers are frequently asked in the interviews and exams. All these programs are given with the maximum examples and output. If you are new to Java programming, we will recommend you to read our Java tutorial first. Let's see the list of Java programs. +-Java Basic Programs +-Java Number Programs +-Java Array Programs +-Java Matrix Programs +-Java String Programs +-Java Searching and Sorting Programs +-Java Conversion Programs +-Pattern programs +-Singly Linked List Programs +-Circular Linked List Programs +-Doubly Linked List Programs +-Tree Programs" +Can you provide a list of Java Basic Programs?,"1) Fibonacci Series in Java +2) Prime Number Program in Java +3) Palindrome Program in Java +4) Factorial Program in Java +5) Armstrong Number in Java +6) How to Generate Random Number in Java +7) How to Print Pattern in Java +8) How to Compare Two Objects in Java +9) How to Create Object in Java +10) How to Print ASCII Value in Java" +Can you provide a list of Java Number Programs?,"1) How to Reverse a Number in Java +2) Java Program to convert Number to Word +3) Automorphic Number Program in Java +4) Peterson Number in Java +5) Sunny Number in Java +6) Tech Number in Java +7) Fascinating Number in Java +8) Keith Number in Java +9) Neon Number in Java +10) Spy Number in Java +11) ATM program Java +12) Autobiographical Number in Java +13) Emirp Number in Java +14) Sphenic Number in Java +15) Buzz Number Java +16) Duck Number Java +17) Evil Number Java +18) ISBN Number Java +19) Krishnamurthy Number Java +20) Bouncy Number in Java +21) Mystery Number in Java +22) Smith Number in Java +23) Strontio Number in Java +24) Xylem and Phloem Number in Java +25) nth Prime Number Java +26) Java Program to Display Alternate Prime Numbers +27) Java Program to Find Square Root of a Number Without sqrt Method +28) Java Program to Swap Two Numbers Using Bitwise Operator +29) Java Program to Find GCD of Two Numbers +30) Java Program to Find Largest of Three Numbers +31) Java Program to Find Smallest of Three Numbers Using Ternary Operator +32) Java Program to Check if a Number is Positive or Negative +33) Java Program to Check if a Given Number is Perfect Square +34) Java Program to Display Even Numbers From 1 to 100 +35) Java Program to Display Odd Numbers From 1 to 100 +36) Java Program to Find Sum of Natural Numbers" +Can you provide a list of Java Array Programs?,"1) Java Program to copy all elements of one array into another array +2) Java Program to find the frequency of each element in the array +3) Java Program to left rotate the elements of an array +4) Java Program to print the duplicate elements of an array +5) Java Program to print the elements of an array +6) Java Program to print the elements of an array in reverse order +7) Java Program to print the elements of an array present on even position +8) Java Program to print the elements of an array present on odd position +9) Java Program to print the largest element in an array +10) Java Program to print the smallest element in an array +11) Java Program to print the number of elements present in an array +12) Java Program to print the sum of all the items of the array +13) Java Program to right rotate the elements of an array +14) Java Program to sort the elements of an array in ascending order +15) Java Program to sort the elements of an array in descending order +16) Java Program to Find 3rd Largest Number in an array +17) Java Program to Find 2nd Largest Number in an array +18) Java Program to Find Largest Number in an array +19) Java to Program Find 2nd Smallest Number in an array +20) Java Program to Find Smallest Number in an array +21) Java Program to Remove Duplicate Element in an array +22) Java Program to Print Odd and Even Numbers from an array +23) How to Sort an Array in Java" +Can you provided a list of Java Matrix Programs?,"1) Java Matrix Programs +2) Java Program to Add Two Matrices +3) Java Program to Multiply Two Matrices +4) Java Program to subtract the two matrices +5) Java Program to determine whether two matrices are equal +6) Java Program to display the lower triangular matrix +7) Java Program to display the upper triangular matrix +8) Java Program to find the frequency of odd & even numbers in the given matrix +9) Java Program to find the product of two matrices +10) Java Program to find the sum of each row and each column of a matrix +11) Java Program to find the transpose of a given matrix +12) Java Program to determine whether a given matrix is an identity matrix +13) Java Program to determine whether a given matrix is a sparse matrix +14) Java Program to Transpose matrix" +Can you provide a list of Java String Programs?,"1) Java Program to count the total number of characters in a string +2) Java Program to count the total number of characters in a string 2 +3) Java Program to count the total number of punctuation characters exists in a String +4) Java Program to count the total number of vowels and consonants in a string +5) Java Program to determine whether two strings are the anagram +6) Java Program to divide a string in 'N' equal parts. +7) Java Program to find all subsets of a string +8) Java Program to find the longest repeating sequence in a string +9) Java Program to find all the permutations of a string +10) Java Program to remove all the white spaces from a string +11) Java Program to replace lower-case characters with upper-case and vice-versa +12) Java Program to replace the spaces of a string with a specific character +13) Java Program to determine whether a given string is palindrome +14) Java Program to determine whether one string is a rotation of another +15) Java Program to find maximum and minimum occurring character in a string +16) Java Program to find Reverse of the string +17) Java program to find the duplicate characters in a string +18) Java program to find the duplicate words in a string +19) Java Program to find the frequency of characters +20) Java Program to find the largest and smallest word in a string +21) Java Program to find the most repeated word in a text file +22) Java Program to find the number of the words in the given text file +23) Java Program to separate the Individual Characters from a String +24) Java Program to swap two string variables without using third or temp variable. +25) Java Program to print smallest and biggest possible palindrome word in a given string +26) Reverse String in Java Word by Word +27) Reserve String without reverse() function" +Can you provide a list of Java Searching and Sorting Programs?,"1) Linear Search in Java +2) Binary Search in Java +3) Bubble Sort in Java +4) Selection Sort in Java +5) Insertion Sort in Java" +Can you provide a list of Java Conversion Programs?,"1) How to convert String to int in Java +2) How to convert int to String in Java +3) How to convert String to long in Java +4) How to convert long to String in Java +5) How to convert String to float in Java +6) How to convert float to String in Java +7) How to convert String to double in Java +8) How to convert double to String in Java +9) How to convert String to Date in Java +10) How to convert Date to String in Java +11) How to convert String to char in Java +12) How to convert char to String in Java +13) How to convert String to Object in Java +14) How to convert Object to String in Java +15) How to convert int to long in Java +16) How to convert long to int in Java +17) How to convert int to double in Java +18) How to convert double to int in Java +19) How to convert char to int in Java +20) How to convert int to char in Java +21) How to convert String to boolean in Java +22) How to convert boolean to String in Java +23) How to convert Date to Timestamp in Java +24) How to convert Timestamp to Date in Java +25) How to convert Binary to Decimal in Java +26) How to convert Decimal to Binary in Java +27) How to convert Hex to Decimal in Java +28) How to convert Decimal to Hex in Java +29) How to convert Octal to Decimal in Java +30) How to convert Decimal to Octal in Java" +Can you provide a list of Java Pattern programs?,"1) Java program to print the following spiral pattern on the console +2) Java program to print the following pattern +3) Java program to print the following pattern 2 +4) Java program to print the following pattern 3 +5) Java program to print the following pattern 4 +6) Java program to print the following pattern 5 +7) Java program to print the following pattern on the console +8) Java program to print the following pattern on the console 2 +9) Java program to print the following pattern on the console 3 +10) Java program to print the following pattern on the console 4 +11) Java program to print the following pattern on the console 5 +12) Java program to print the following pattern on the console 6 +13) Java program to print the following pattern on the console 7 +14) Java program to print the following pattern on the console 8 +15) Java program to print the following pattern on the console 9 +16) Java program to print the following pattern on the console 10 +17) Java program to print the following pattern on the console 11 +18) Java program to print the following pattern on the console 12" +Can you provide a list of Java Singly Linked List Programs?,"1) Singly linked list Examples in Java +2) Java Program to create and display a singly linked list +3) Java program to create a singly linked list of n nodes and count the number of nodes +4) Java program to create a singly linked list of n nodes and display it in reverse order +5) Java program to delete a node from the beginning of the singly linked list +6) Java program to delete a node from the middle of the singly linked list +7) Java program to delete a node from the end of the singly linked list +8) Java program to determine whether a singly linked list is the palindrome +9) Java program to find the maximum and minimum value node from a linked list +10) Java Program to insert a new node at the middle of the singly linked list +11) Java program to insert a new node at the beginning of the singly linked list +12) Java program to insert a new node at the end of the singly linked list +13) Java program to remove duplicate elements from a singly linked list +14) Java Program to search an element in a singly linked list" +Can you provide a list of Java Circular Linked List Programs?,"1) Java program to create and display a Circular Linked List +2) Java program to create a Circular Linked List of N nodes and count the number of nodes +3) Java program to create a Circular Linked List of n nodes and display it in reverse order +4) Java program to delete a node from the beginning of the Circular Linked List +5) Java program to delete a node from the end of the Circular Linked List +6) Java program to delete a node from the middle of the Circular Linked List +7) Java program to find the maximum and minimum value node from a circular linked list +8) Java program to insert a new node at the beginning of the Circular Linked List +9) Java program to insert a new node at the end of the Circular Linked List +10) Java program to insert a new node at the middle of the Circular Linked List +11) Java program to remove duplicate elements from a Circular Linked List +12) Java program to search an element in a Circular Linked List +13) Java program to sort the elements of the Circular Linked List" +Can you provide a list of Java Doubly Linked List Programs?,"1) Java program to convert a given binary tree to doubly linked list +2) Java program to create a doubly linked list from a ternary tree +3) Java program to create a doubly linked list of n nodes and count the number of nodes +4) Java program to create a doubly linked list of n nodes and display it in reverse order +5) Java program to create and display a doubly linked list +6) Java program to delete a new node from the beginning of the doubly linked list +7) Java program to delete a new node from the end of the doubly linked list +8) Java program to delete a new node from the middle of the doubly linked list +9) Java program to find the maximum and minimum value node from a doubly linked list +10) Java program to insert a new node at the beginning of the Doubly Linked list +10) Java program to insert a new node at the end of the Doubly Linked List +12) Java program to insert a new node at the middle of the Doubly Linked List +13) Java program to remove duplicate elements from a Doubly Linked List +14) Java program to rotate doubly linked list by N nodes +15) Java program to search an element in a doubly linked list +16) Java program to sort the elements of the doubly linked list" +Can you provide a list of Java Tree Programs?,"1) Java Program to calculate the Difference between the Sum of the Odd Level and the Even Level Nodes of a Binary Tree +2) Java program to construct a Binary Search Tree and perform deletion and In-order traversal +3) Java program to convert Binary Tree to Binary Search Tree +4) Java program to determine whether all leaves are at same level +5) Java program to determine whether two trees are identical +6) Java program to find maximum width of a binary tree +7) Java program to find the largest element in a Binary Tree +8) Java program to find the maximum depth or height of a tree +9) Java program to find the nodes which are at the maximum distance in a Binary Tree +10) Java program to find the smallest element in a tree +11) Java program to find the sum of all the nodes of a binary tree +12) Java program to find the total number of possible Binary Search Trees with N keys +13) Java program to implement Binary Tree using the Linked List +14) Java program to search a node in a Binary Tree" +What is the difference between an object-oriented programming language and object-based programming language?,"Object-based programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are examples of object-based programming languages. + " +What is Java Naming Convention?,"Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc. + +But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape. + +All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code. + + +" +What is the Advantage of Naming Conventions in Java?,"By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does. + +" +What are the Naming Conventions of the Different Identifiers?,"Naming Conventions of the Different Identifiers + +The following table shows the popular conventions used for the different identifiers. + +Identifiers Type: Class +Naming Rules: 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. +Examples: public class Employee +{ +//code snippet +} + + +Identifiers Type: Interface +Naming Rules: It should start with the uppercase letter. +It should be an adjective such as Runnable, Remote, ActionListener. +Use appropriate words, instead of acronyms. +Examples: interface Printable +{ +//code snippet +} + + +Identifiers Type: Method +Naming Rules: 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(). +Examples: class Employee +{ +// method +void draw() +{ +//code snippet +} +} + + +Identifiers Type: Variable +Naming Rules: 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. +Examples: class Employee +{ +// variable +int id; +//code snippet +} + + +Identifiers Type: Package +Naming Rules: 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. +Examples: //package +package com.javatpoint; +class Employee +{ +//code snippet +} + +Identifiers Type: Constant +Naming Rules: It 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. +Examples: class Employee +{ +//constant +static final int MIN_AGE = 18; +//code snippet +} +" +What is CamelCase in Java naming conventions?,"Java follows camel-case syntax for naming the class, interface, method, and variable. + +If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc." +What is Objects and Classes in Java?,"In this page, we will learn about Java objects and classes. In object-oriented programming technique, we design a program using objects and classes. + +An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only." +What is an object in Java?,"An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system. +An object has three characteristics: +-State: represents the data (value) of an object. +-Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc. +-Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely." +What is a class in Java?,"A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical. +A class in Java can contain: +-Fields +-Methods +-Constructors +-Blocks +-Nested class and interface" +What is Instance variable in Java?,A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable. +What is Method in Java?,"In Java, a method is like a function which is used to expose the behavior of an object. + +Advantage of Method +-Code Reusability +-Code Optimization" +What is new keyword in Java?,The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area. +Can you provide an example of Object and Class Example: main within the class in Java?,"In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value. + +Here, we are creating a main() method inside the class. +//Java Program to illustrate how to define a class and fields +//Defining a Student class. +class Student{ + //defining fields + int id;//field or data member or instance variable + String name; + //creating main method inside the Student class + public static void main(String args[]){ + //Creating an object or instance + Student s1=new Student();//creating an object of Student + //Printing values of the object + System.out.println(s1.id);//accessing member through reference variable + System.out.println(s1.name); + } +} +Output: + +0 +null" +Can you provide an example of Object and Class Example: main outside the class in Java?,"In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class. + +We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method. + +//Java Program to demonstrate having the main method in +//another class +//Creating Student class. +class Student{ + int id; + String name; +} +//Creating another class TestStudent1 which contains the main method +class TestStudent1{ + public static void main(String args[]){ + Student s1=new Student(); + System.out.println(s1.id); + System.out.println(s1.name); + } +} +Output: +0 +null" +What are the 3 Ways to initialize object?,"There are 3 ways to initialize object in Java. + +-By reference variable +-By method +-By constructor" +Can you provide an example of Object and Class Example: Initialization through reference in Java?,"1) Object and Class Example: Initialization through reference +Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable. +class Student{ + int id; + String name; +} +class TestStudent2{ + public static void main(String args[]){ + Student s1=new Student(); + s1.id=101; + s1.name=""Sonoo""; + System.out.println(s1.id+"" ""+s1.name);//printing members with a white space + } +} +Output: + +101 Sonoo" +Can you provide an example of Object and Class Example: Initialization through method in Java?,"2) Object and Class Example: Initialization through method +In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method. +class Student{ + int rollno; + String name; + void insertRecord(int r, String n){ + rollno=r; + name=n; + } + void displayInformation(){System.out.println(rollno+"" ""+name);} +} +class TestStudent4{ + public static void main(String args[]){ + Student s1=new Student(); + Student s2=new Student(); + s1.insertRecord(111,""Karan""); + s2.insertRecord(222,""Aryan""); + s1.displayInformation(); + s2.displayInformation(); + } +} +Output: + +111 Karan +222 Aryan" +Can you provide an example of Object and Class Initialization through a constructor in Java?,"We will learn about constructors in Java later. + +Let's see an example where we are maintaining records of employees. +class Employee{ + int id; + String name; + float salary; + void insert(int i, String n, float s) { + id=i; + name=n; + salary=s; + } + void display(){System.out.println(id+"" ""+name+"" ""+salary);} +} +public class TestEmployee { +public static void main(String[] args) { + Employee e1=new Employee(); + Employee e2=new Employee(); + Employee e3=new Employee(); + e1.insert(101,""ajeet"",45000); + e2.insert(102,""irfan"",25000); + e3.insert(103,""nakul"",55000); + e1.display(); + e2.display(); + e3.display(); +} +} +Output: + +101 ajeet 45000.0 +102 irfan 25000.0 +103 nakul 55000.0" +What are the different ways to create an object in Java?,"There are many ways to create an object in java. They are: + +-By new keyword +-By newInstance() method +-By clone() method +-By deserialization +-By factory method etc." +What is 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. +If you have to use an object only once, an anonymous object is a good approach. + + For example: + +new Calculation();//anonymous object + +Calling method through a reference: + +Calculation c=new Calculation(); +c.fact(5); + +Calling method through an anonymous object + +new Calculation().fact(5); + +Let's see the full example of an anonymous object in Java. + +class Calculation{ + void fact(int n){ + int fact=1; + for(int i=1;i<=n;i++){ + fact=fact*i; + } + System.out.println(""factorial is ""+fact); +} +public static void main(String args[]){ + new Calculation().fact(5);//calling method with anonymous object +} +} + +Output: +Factorial is 120 + +" +How to create multiple objects by one type only in Java?,"We can create multiple objects by one type only as we do in case of primitives. + +Initialization of primitive variables: + +int a=10, b=20; + +Initialization of refernce variables: + +Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects + +Let's see the example: + +//Java Program to illustrate the use of Rectangle class which +//has length and width data members +class Rectangle{ + int length; + int width; + void insert(int l,int w){ + length=l; + width=w; + } + void calculateArea(){System.out.println(length*width);} +} +class TestRectangle2{ + public static void main(String args[]){ + Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects + r1.insert(11,5); + r2.insert(3,15); + r1.calculateArea(); + r2.calculateArea(); +} +} + + +Output: + +55 +45 + " +What is a method in Java?,"A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the reusability of code. We write a method once and use it many times. We do not require to write code again and again. It also provides the easy modification and readability of code, just by adding or removing a chunk of code. The method is executed only when we call or invoke it. + +The most important method in Java is the main() method. + + " +What is Method Declaration?,"The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments. It has six components that are known as method header. + +Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list. + +Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier: + +-Public: The method is accessible by all classes when we use public specifier in our application. +-Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined. +-Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package. +-Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only. + +Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword. + +Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name. + +Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank. + +Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces. + + + + +" +How to name a Method?,"While defining a method, remember that the method name must be a verb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example: + +Single-word method name: sum(), area() + +Multi-word method name: areaOfCircle(), stringComparision() + +It is also possible that a method has the same name as another method name in the same class, it is known as method overloading. + + " +What are the Types of Method?,"There are two types of methods in Java: + +-Predefined Method +-User-defined Method + + " +What is Predefined Method?,"In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. We can directly use these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related to the corresponding method runs in the background that is already stored in the library. + +Each and every predefined method is defined inside a class. Such as print() method is defined in the java.io.PrintStream class. It prints the statement that we write inside the method. For example, print(""Java""), it prints Java on the console. + +Let's see an example of the predefined method. +Demo.java +public class Demo +{ +public static void main(String[] args) +{ +// using the max() method of Math class +System.out.print(""The maximum number is: "" + Math.max(9,7)); +} +} + +Output: +The maximum number is: 9 + + +In the above example, we have used three predefined methods main(), print(), and max(). We have used these methods directly without declaration because they are predefined. The print() method is a method of PrintStream class that prints the result on the console. The max() method is a method of the Math class that returns the greater of two numbers. + + + +We can also see the method signature of any predefined method by using the link https://docs.oracle.com/. When we go through the link and see the max() method signature, we find the following: + +public static int max(int a, int b) returns the greater of two int values. +same value. + +Parameters: +a an argument. + +b +another argument. + +Returns: +the larger of a and b. + + +In the above method signature, we see that the method signature has access specifier public, non-access modifier static, return type int, method name max(), parameter list (int a, int b). In the above example, instead of defining the method, we have just invoked the method. This is the advantage of a predefined method. It makes programming less complicated. + +Similarly, we can also see the method signature of the print() method. + " +What is User-defined Method?,"The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement. +How to Create a User-defined Method +Let's create a user defined method that checks the number is even or odd. First, we will define the method. + +//user defined method +public static void findEvenOdd(int num) +{ +//method body +if(num%2==0) +System.out.println(num+"" is even""); +else +System.out.println(num+"" is odd""); +} + +We have defined the above method named findevenodd(). It has a parameter num of type int. The method does not return any value that's why we have used void. The method body contains the steps to check the number is even or odd. If the number is even, it prints the number is even, else prints the number is odd. + +How to Call or Invoke a User-defined Method + +Once we have defined a method, it should be called. The calling of a method in a program is simple. When we call or invoke a user-defined method, the program control transfer to the called method. + +import java.util.Scanner; +public class EvenOdd +{ +public static void main (String args[]) +{ +//creating Scanner class object +Scanner scan=new Scanner(System.in); +System.out.print(""Enter the number: ""); +//reading value from the user +int num=scan.nextInt(); +//method calling +findEvenOdd(num); +} + +In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer to the method and gives the output accordingly. + +Let's combine both snippets of codes in a single program and execute it. + +EvenOdd.java +import java.util.Scanner; +public class EvenOdd +{ +public static void main (String args[]) +{ +//creating Scanner class object +Scanner scan=new Scanner(System.in); +System.out.print(""Enter the number: ""); +//reading value from user +int num=scan.nextInt(); +//method calling +findEvenOdd(num); +} +//user defined method +public static void findEvenOdd(int num) +{ +//method body +if(num%2==0) +System.out.println(num+"" is even""); +else +System.out.println(num+"" is odd""); +} +} + +Output 1: +Enter the number: 12 +12 is even + +Output 2: +Enter the number: 99 +99 is odd +Let's see another program that return a value to the calling method. + +In the following program, we have defined a method named add() that sum up the two numbers. It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b, respectively. Therefore, the method adds the value of a and b and store it in the variable s and returns the sum. +Addition.java + +public class Addition +{ +public static void main(String[] args) +{ +int a = 19; +int b = 5; +//method calling +int c = add(a, b); //a and b are actual parameters +System.out.println(""The sum of a and b is= "" + c); +} +//user defined method +public static int add(int n1, int n2) //n1 and n2 are formal parameters +{ +int s; +s=n1+n2; +return s; //returning the sum +} +} + +Output: +The sum of a and b is= 24 + " +What is Static Method?,"A method that has static keyword is known as static method. In other words, a method that belongs to a class rather than an instance of a class is known as a static method. We can also create a static method by using the keyword static before the method name. + +The main advantage of a static method is that we can call it without creating an object. It can access static data members and also change the value of it. It is used to create an instance method. It is invoked by using the class name. The best example of a static method is the main() method. + +Example of static method + +Display.java + +public class Display +{ +public static void main(String[] args) +{ +show(); +} +static void show() +{ +System.out.println(""It is an example of static method.""); +} +} +Output: + +It is an example of a static method. + + " +What is Instance Method?,"The method of the class is known as an instance method. It is a non-static method defined in the class. Before calling or invoking the instance method, it is necessary to create an object of its class. Let's see an example of an instance method. + +InstanceMethodExample.java + +public class InstanceMethodExample +{ +public static void main(String [] args) +{ +//Creating an object of the class +InstanceMethodExample obj = new InstanceMethodExample(); +//invoking instance method +System.out.println(""The sum is: ""+obj.add(12, 13)); +} +int s; +//user-defined method because we have not used static keyword +public int add(int a, int b) +{ +s = a+b; +//returning the sum +return s; +} +} + +Output: +The sum is: 25 + + " +There are two types of instance method?,"There are two types of instance method: + +-Accessor Method +-Mutator Method + + " +What is Accessor Method in Java?,"The method(s) that reads the instance variable(s) is known as the accessor method. We can easily identify it because the method is prefixed with the word get. It is also known as getters. It returns the value of the private field. It is used to get the value of the private field +. +Example: + +public int getId() +{ +return Id; +} + + " +What is Mutator Method in Java?,"The method(s) read the instance variable(s) and also modify the values. We can easily identify it because the method is prefixed with the word set. It is also known as setters or modifiers. It does not return anything. It accepts a parameter of the same data type that depends on the field. It is used to set the value of the private field. + +Example: + +public void setRoll(int roll) +{ +this.roll = roll; +} + + " +Can you provide an Example of accessor and mutator method?,"Student.java + +public class Student +{ +private int roll; +private String name; +public int getRoll() //accessor method +{ +return roll; +} +public void setRoll(int roll) //mutator method +{ +this.roll = roll; +} +public String getName() +{ +return name; +} +public void setName(String name) +{ +this.name = name; +} +public void display() +{ +System.out.println(""Roll no.: ""+roll); +System.out.println(""Student name: ""+name); +} +} + + +" +What is Abstract Method in Java?,"The method that does not has method body is known as abstract method. In other words, without an implementation is known as abstract method. It always declares in the abstract class. It means the class itself must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract. + +Syntax +abstract void method_name(); + + " +Can you provide an Example of abstract method?,"Demo.java + +abstract class Demo //abstract class +{ +//abstract method declaration +abstract void display(); +} +public class MyClass extends Demo +{ +//method impelmentation +void display() +{ +System.out.println(""Abstract method?""); +} +public static void main(String args[]) +{ +//creating object of abstract class +Demo obj = new MyClass(); +//invoking abstract method +obj.display(); +} +} + +Output: +Abstract method... + + " +What is Factory method in Java?,"It is a method that returns an object to the class to which it belongs. All static methods are factory methods. For example, NumberFormat obj = NumberFormat.getNumberInstance(); + " +What is Constructors in Java?,"In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. + +It is a special type of method which is used to initialize the object. + +Every time an object is created using the new() keyword, at least one constructor is called. + +It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. + +There are two types of constructors in Java: no-arg constructor, and parameterized constructor. + +Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any. + + " +What are the Rules for creating Java constructor?,"There are two rules defined for the constructor. + +1) Constructor name must be the same as its class name +2) A Constructor must have no explicit return type +3) A Java constructor cannot be abstract, static, final, and synchronized + + +" +What are theTypes of Java constructors?,"There are two types of constructors in Java: + +1) Default constructor (no-arg constructor) +2) Parameterized constructor + + +" +What is the Java Default Constructor?,"A constructor is called ""Default Constructor"" when it doesn't have any parameter. +Syntax of default constructor: + +(){} +" +Can you provide an Example of default constructor?,"In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. + + + +//Java Program to create and call a default constructor + +class Bike1{ +//creating a default constructor +Bike1(){System.out.println(""Bike is created"");} +//main method +public static void main(String args[]){ +//calling a default constructor +Bike1 b=new Bike1(); +} +} + +Output: +Bike is create +" +Can you provide an Example of default constructor that displays the default values?,"//Let us see another example of default constructor +//which displays the default values +class Student3{ +int id; +String name; +//method to display the value of id and name +void display(){System.out.println(id+"" ""+name);} + +public static void main(String args[]){ +//creating objects +Student3 s1=new Student3(); +Student3 s2=new Student3(); +//displaying values of the object +s1.display(); +s2.display(); +} +} + +Output: +0 null +0 null + +" +What is Java Parameterized Constructor?,"A constructor which has a specific number of parameters is called a parameterized constructor. + +Why use the parameterized constructor? + +The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also. + + +" +Can you provide an Example of parameterized constructor in Java?,"In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. + +//Java Program to demonstrate the use of the parameterized constructor. + +class Student4{ + int id; + String name; + //creating a parameterized constructor + Student4(int i,String n){ + id = i; + name = n; + } + //method to display the values + void display(){System.out.println(id+"" ""+name);} + + public static void main(String args[]){ + //creating objects and passing values + Student4 s1 = new Student4(111,""Karan""); + Student4 s2 = new Student4(222,""Aryan""); + //calling method to display the values of object + s1.display(); + s2.display(); + } +} + +Output: +111 Karan +222 Aryan + + + " +What is Constructor Overloading in Java?,"In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. + +Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. + + +" +Can you provide an Example of Constructor Overloading?,"//Java program to overload constructors +class Student5{ + int id; + String name; + int age; + //creating two arg constructor + Student5(int i,String n){ + id = i; + name = n; + } + //creating three arg constructor + Student5(int i,String n,int a){ + id = i; + name = n; + age=a; + } + void display(){System.out.println(id+"" ""+name+"" ""+age);} + + public static void main(String args[]){ + Student5 s1 = new Student5(111,""Karan""); + Student5 s2 = new Student5(222,""Aryan"",25); + s1.display(); + s2.display(); + } +} + +Output: +111 Karan 0 +222 Aryan 25 + + + + +" +What is Java Copy Constructor?,"There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++. + +There are many ways to copy the values of one object into another in Java. They are: + +-By constructor +-By assigning the values of one object into another +-By clone() method of Object class + +In this example, we are going to copy the values of one object into another using Java constructor. +//Java program to initialize the values from one object to another object. +class Student6{ + int id; + String name; + //constructor to initialize integer and string + Student6(int i,String n){ + id = i; + name = n; + } + //constructor to initialize another object + Student6(Student6 s){ + id = s.id; + name =s.name; + } + void display(){System.out.println(id+"" ""+name);} + + public static void main(String args[]){ + Student6 s1 = new Student6(111,""Karan""); + Student6 s2 = new Student6(s1); + s1.display(); + s2.display(); + } +} + +Output: +111 Karan +111 Karan + + + + +" +How to copy values without constructor in Java?,"We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor. + +class Student7{ + int id; + String name; + Student7(int i,String n){ + id = i; + name = n; + } + Student7(){} + void display(){System.out.println(id+"" ""+name);} + + public static void main(String args[]){ + Student7 s1 = new Student7(111,""Karan""); + Student7 s2 = new Student7(); + s2.id=s1.id; + s2.name=s1.name; + s1.display(); + s2.display(); + } +} + +Output: +111 Karan +111 Karan + " +What is Java static keyword?,"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: + +1) Variable (also known as a class variable) +2) Method (also known as a class method) +3) Block +4) Nested class + + +" +What is Java static variable?,"If you declare any variable as static, it is known as a static variable. + +-The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. +-The static variable gets memory only once in the class area at the time of class loading. + +Advantages of static variable +It makes your program memory efficient (i.e., it saves memory). +Understanding the problem without static variable + +class Student{ + int rollno; + String name; + String college=""ITS""; +} + +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." +Can you provide an Example of static variable in Java?,"//Java Program to demonstrate the use of static variable +class Student{ + int rollno;//instance variable + String name; + static String college =""ITS"";//static variable + //constructor + Student(int r, String n){ + rollno = r; + name = n; + } + //method to display the values + void display (){System.out.println(rollno+"" ""+name+"" ""+college);} +} +//Test class to show the values of objects +public class TestStaticVariable1{ + public static void main(String args[]){ + Student s1 = new Student(111,""Karan""); + Student s2 = new Student(222,""Aryan""); + //we can change the college of all objects by the single line of code + //Student.college=""BBDIT""; + s1.display(); + s2.display(); + } +} + +Output: + +111 Karan ITS +222 Aryan ITS + +" +Can you provide an example Program of the counter without static variable in Java?,"In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in the count variable. + +//Java Program to demonstrate the use of an instance variable +//which get memory each time when we create an object of the class. + +class Counter{ +int count=0;//will get memory each time when the instance is created + +Counter(){ +count++;//incrementing value +System.out.println(count); +} + +public static void main(String args[]){ +//Creating objects +Counter c1=new Counter(); +Counter c2=new Counter(); +Counter c3=new Counter(); +} +} + +Output: + +1 +1 +1 + +" +Can you provid an example Program of counter by static variable in Java?,"static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value. + + +//Java Program to illustrate the use of static variable which +//is shared with all objects. + +class Counter2{ +static int count=0;//will get memory only once and retain its value + +Counter2(){ +count++;//incrementing the value of static variable +System.out.println(count); +} + +public static void main(String args[]){ +//creating objects +Counter2 c1=new Counter2(); +Counter2 c2=new Counter2(); +Counter2 c3=new Counter2(); +} +} + +Output: +1 +2 +3 + +" +What is 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." +Can you provide an Example of static method in Java?,"//Java Program to demonstrate the use of a static method. +class Student{ + int rollno; + String name; + static String college = ""ITS""; + //static method to change the value of static variable + static void change(){ + college = ""BBDIT""; + } + //constructor to initialize the variable + Student(int r, String n){ + rollno = r; + name = n; + } + //method to display values + void display(){System.out.println(rollno+"" ""+name+"" ""+college);} +} +//Test class to create and display the values of object +public class TestStaticMethod{ + public static void main(String args[]){ + Student.change();//calling change method + //creating objects + Student s1 = new Student(111,""Karan""); + Student s2 = new Student(222,""Aryan""); + Student s3 = new Student(333,""Sonoo""); + //calling display method + s1.display(); + s2.display(); + s3.display(); + } +} +Output: +111 Karan BBDIT + 222 Aryan BBDIT + 333 Sonoo BBDIT" +What is Java static block?,"-Is used to initialize the static data member. +-It is executed before the main method at the time of classloading." +What is static keyword in Java?,"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" +Can you provide an Example of static block in Java?,"class A2{ + static{System.out.println(""static block is invoked"");} + public static void main(String args[]){ + System.out.println(""Hello main""); + } +} +Output:static block is invoked + Hello main" +what are the Usage of Java this keyword?,"Here is given the 6 usage of java this keyword. + +1.this can be used to refer current class instance variable. +2.this can be used to invoke current class method (implicitly) +3.this() can be used to invoke current class constructor. +4.this can be passed as an argument in the method call. +5.this can be passed as argument in the constructor call. +6.this can be used to return the current class instance from the method." +What is this keywoard in Java?,"The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. " +" How to use ""this"" to invoke current class method in Java?","You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example +class A{ +void m(){System.out.println(""hello m"");} +void n(){ +System.out.println(""hello n""); +//m();//same as this.m() +this.m(); +} +} +class TestThis4{ +public static void main(String args[]){ +A a=new A(); +a.n(); +}} + +Output: + +hello n +hello m" + How to use this() : to invoke current class constructor?,"The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining. +Calling default constructor from parameterized constructor: + +class A{ +A(){System.out.println(""hello a"");} +A(int x){ +this(); +System.out.println(x); +} +} +class TestThis5{ +public static void main(String args[]){ +A a=new A(10); +}} +Output: + +hello a +10" +What is the Real usage of this() constructor call?,"The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword. + +class Student{ +int rollno; +String name,course; +float fee; +Student(int rollno,String name,String course){ +this.rollno=rollno; +this.name=name; +this.course=course; +} +Student(int rollno,String name,String course,float fee){ +this(rollno,name,course);//reusing constructor +this.fee=fee; +} +void display(){System.out.println(rollno+"" ""+name+"" ""+course+"" ""+fee);} +} +class TestThis7{ +public static void main(String args[]){ +Student s1=new Student(111,""ankit"",""java""); +Student s2=new Student(112,""sumit"",""java"",6000f); +s1.display(); +s2.display(); +}} +Output: + +111 ankit java 0.0 +112 sumit java 6000.0" +how to use this: to pass as an argument in the method in Java?,"The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example: + +class S2{ + void m(S2 obj){ + System.out.println(""method is invoked""); + } + void p(){ + m(this); + } + public static void main(String args[]){ + S2 s1 = new S2(); + s1.p(); + } +} +Output: + +method is invoked" +how to use this: to pass as argument in the constructor call in Java?,"We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example: + +class B{ + A4 obj; + B(A4 obj){ + this.obj=obj; + } + void display(){ + System.out.println(obj.data);//using data member of A4 class + } +} + +class A4{ + int data=10; + A4(){ + B b=new B(this); + b.display(); + } + public static void main(String args[]){ + A4 a=new A4(); + } +} +Output:10" +Can you provide an Example of this keyword that you return as a statement from the method in Java?,"class A{ +A getA(){ +return this; +} +void msg(){System.out.println(""Hello java"");} +} +class Test1{ +public static void main(String args[]){ +new A().getA().msg(); +} +} +Output: + +Hello java" +how to provee this keyword in java?,"Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same. + +class A5{ +void m(){ +System.out.println(this);//prints same reference ID +} +public static void main(String args[]){ +A5 obj=new A5(); +System.out.println(obj);//prints the reference ID +obj.m(); +} +} +Output: + +A5@22b3ea59 +A5@22b3ea59" +What is Inheritance in Java?,"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. + +Inheritance represents the IS-A relationship which is also known as a parent-child relationship. + + " +Why use inheritance in java?,"-For Method Overriding (so runtime polymorphism can be achieved). +-For Code Reusability. + + " +What are the Terms used in Inheritance?,"-Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. + +-Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. + +-Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. + +-Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. + + +" +What are The syntax of Java Inheritance?,"class Subclass-name extends Superclass-name +{ + //methods and fields +} + +The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of ""extends"" is to increase the functionality. +In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass. + + " +Whaht are the Types of inheritance in java?,"On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. + +In java programming, multiple and hybrid inheritance is supported through interface only. + +When one class inherits multiple classes, it is known as multiple inheritance. + " +Can you provide an Single Inheritance Example in Java?,"When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance. + + +class Animal{ +void eat(){System.out.println(""eating..."");} +} +class Dog extends Animal{ +void bark(){System.out.println(""barking..."");} +} +class TestInheritance{ +public static void main(String args[]){ +Dog d=new Dog(); +d.bark(); +d.eat(); +}} + +Output: +barking... +eating... + " +Can you provide an Multilevel Inheritance Example in Java?,"When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance. + +class Animal{ +void eat(){System.out.println(""eating..."");} +} +class Dog extends Animal{ +void bark(){System.out.println(""barking..."");} +} +class BabyDog extends Dog{ +void weep(){System.out.println(""weeping..."");} +} +class TestInheritance2{ +public static void main(String args[]){ +BabyDog d=new BabyDog(); +d.weep(); +d.bark(); +d.eat(); +}} + +Output: +weeping... +barking... +eating... + + " +Can you provide an Hierarchical Inheritance Example in Java?,"When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. + +class Animal{ +void eat(){System.out.println(""eating..."");} +} +class Dog extends Animal{ +void bark(){System.out.println(""barking..."");} +} +class Cat extends Animal{ +void meow(){System.out.println(""meowing..."");} +} +class TestInheritance3{ +public static void main(String args[]){ +Cat c=new Cat(); +c.meow(); +c.eat(); +//c.bark();//C.T.Error +}} + +Output: + +meowing... +eating... + + " +Why multiple inheritance is not supported in java?,"As we have explained in the inheritance chapter, 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. For example: + +interface Printable{ +void print(); +} +interface Showable{ +void print(); +} + +class TestInterface3 implements Printable, Showable{ +public void print(){System.out.println(""Hello"");} +public static void main(String args[]){ +TestInterface3 obj = new TestInterface3(); +obj.print(); + } +} + +Output: + +Hello" +Can you provide an Simple Example of Aggregation?,"In this example, we have created the reference of Operation class in the Circle class. + +class Operation{ + int square(int n){ + return n*n; + } +} + +class Circle{ + Operation op;//aggregation + double pi=3.14; + + double area(int radius){ + op=new Operation(); + int rsquare=op.square(radius);//code reusability (i.e. delegates the method call). + return pi*rsquare; + } + + + + public static void main(String args[]){ + Circle c=new Circle(); + double result=c.area(5); + System.out.println(result); + } +} + +Output:78.5 + " +When use Aggregation?,"-Code reuse is also best achieved by aggregation when there is no is-a relationship. +-Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice. +" +What is Method Overloading in Java?,"If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. + +If we have to perform only one operation, having same name of the methods increases the readability of the program. + +Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. + +So, we perform method overloading to figure out the program quickly." +What is the Advantage of method overloading?,"Method overloading increases the readability of the program. + +Different ways to overload the method +There are two ways to overload the method in java + +1.By changing number of arguments +2.By changing the data type" +Why Method Overloading is not possible by changing the return type of method only?,"In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur: + +class Adder{ +static int add(int a,int b){return a+b;} +static double add(int a,int b){return a+b;} +} +class TestOverloading3{ +public static void main(String[] args){ +System.out.println(Adder.add(11,11));//ambiguity +}} +Output: + +Compile Time Error: method add(int,int) is already defined in class Adder" +Can we overload java main() method?,"Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example: + +class TestOverloading4{ +public static void main(String[] args){System.out.println(""main with String[]"");} +public static void main(String args){System.out.println(""main with String"");} +public static void main(){System.out.println(""main without args"");} +} +Output: + +main with String[]" +What is Method Overloading and Type Promotion?,"One type is promoted to another implicitly if no matching datatype is found. + +To understand the concept, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int,long,float or double and so on. + " +Can you provide an Example of Method Overloading with TypePromotion in Java?,"class OverloadingCalculation1{ + void sum(int a,long b){System.out.println(a+b);} + void sum(int a,int b,int c){System.out.println(a+b+c);} + + public static void main(String args[]){ + OverloadingCalculation1 obj=new OverloadingCalculation1(); + obj.sum(20,20);//now second int literal will be promoted to long + obj.sum(20,20,20); + + } +} + +Output:40 + 60 + +" +Can you provide an Example of Method Overloading with Type Promotion if matching found in Java?,"If there are matching type arguments in the method, type promotion is not performed. + +class OverloadingCalculation2{ + void sum(int a,int b){System.out.println(""int arg method invoked"");} + void sum(long a,long b){System.out.println(""long arg method invoked"");} + + public static void main(String args[]){ + OverloadingCalculation2 obj=new OverloadingCalculation2(); + obj.sum(20,20);//now int arg sum() method gets invoked + } +} + +Output:int arg method invoked + +" +Can you provide an Example of Method Overloading with Type Promotion in case of ambiguity in Java?,"If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity. + +class OverloadingCalculation3{ + void sum(int a,long b){System.out.println(""a method invoked"");} + void sum(long a,int b){System.out.println(""b method invoked"");} + + public static void main(String args[]){ + OverloadingCalculation3 obj=new OverloadingCalculation3(); + obj.sum(20,20);//now ambiguity + } +} +Output:Compile Time Error" +What is Method Overriding in Java?,"If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. + +In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding." +What are the Usage of Java Method Overriding?,"-Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. +-Method overriding is used for runtime polymorphism" +What are the Rules for Java Method Overriding?,"1.The method must have the same name as in the parent class +2.The method must have the same parameter as in the parent class. +3.There must be an IS-A relationship (inheritance). +" +Can you provide an Example of method overriding in Java?,"In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there is method overriding. + +//Java Program to illustrate the use of Java Method Overriding +//Creating a parent class. +class Vehicle{ + //defining a method + void run(){System.out.println(""Vehicle is running"");} +} +//Creating a child class +class Bike2 extends Vehicle{ + //defining the same method as in the parent class + void run(){System.out.println(""Bike is running safely"");} + + public static void main(String args[]){ + Bike2 obj = new Bike2();//creating object + obj.run();//calling method + } +} +Output: + +Bike is running safely" +Can you provide a real example of Java Method Overriding in Java?,"Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest. + +//Java Program to demonstrate the real scenario of Java Method Overriding +//where three classes are overriding the method of a parent class. +//Creating a parent class. +class Bank{ +int getRateOfInterest(){return 0;} +} +//Creating child classes. +class SBI extends Bank{ +int getRateOfInterest(){return 8;} +} + +class ICICI extends Bank{ +int getRateOfInterest(){return 7;} +} +class AXIS extends Bank{ +int getRateOfInterest(){return 9;} +} +//Test class to create objects and call the methods +class Test2{ +public static void main(String args[]){ +SBI s=new SBI(); +ICICI i=new ICICI(); +AXIS a=new AXIS(); +System.out.println(""SBI Rate of Interest: ""+s.getRateOfInterest()); +System.out.println(""ICICI Rate of Interest: ""+i.getRateOfInterest()); +System.out.println(""AXIS Rate of Interest: ""+a.getRateOfInterest()); +} +} + +Output: +SBI Rate of Interest: 8 +ICICI Rate of Interest: 7 +AXIS Rate of Interest: 9 + + " +Can we override static method?,"No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later." +"Why can we not override static method? ","It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area. + +" +Can we override java main method?,"No, because the main is a static method." +What is the Difference between method Overloading and Method Overriding in java?,"There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below: + + +1) Method overloading is used to increase the readability of the program while Method overriding is used to provide the specific implementation of the method that is already provided by its super class. + +2) Method overloading is performed within class while Method overriding occurs in two classes that have IS-A (inheritance) relationship. + +3) In case of method overloading, parameter must be different while In case of method overriding, parameter must be same. + +4) Method overloading is the example of compile time polymorphism while Method overriding is the example of run time polymorphism. + +5) In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter while Return type must be same or covariant in method overriding. " +What is Covariant Return Type in Java?,"The covariant return type specifies that the return type may vary in the same direction as the subclass. + +Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type." +Can you provide an Simple example of Covariant Return Type in Java?," Let's take a simple example: +FileName: B1.java + +class A{ +A get(){return this;} +} + +class B1 extends A{ +@Override +B1 get(){return this;} +void message(){System.out.println(""welcome to covariant return type"");} + +public static void main(String args[]){ +new B1().get().message(); +} +} +Output: +welcome to covariant return type" +What is the Advantages of Covariant Return Type in Java?,"Following are the advantages of the covariant return type. + +1) Covariant return type assists to stay away from the confusing type casts in the class hierarchy and makes the code more usable, readable, and maintainable. + +2) In the method overriding, the covariant return type provides the liberty to have more to the point return types. + +3) Covariant return type helps in preventing the run-time ClassCastExceptions on returns. + +Let's take an example to understand the advantages of the covariant return type. " +How is Covariant return types implemented?,"Java doesn't allow the return type-based overloading, but JVM always allows return type-based overloading. JVM uses the full signature of a method for lookup/resolution. Full signature means it includes return type in addition to argument types. i.e., a class can have two or more methods differing only by return type. javac uses this fact to implement covariant return types. +Output: + +The number 1 is not the powerful number. +The number 2 is not the powerful number. +The number 3 is not the powerful number. +The number 4 is the powerful number. +The number 5 is not the powerful number. +The number 6 is not the powerful number. +The number 7 is not the powerful number. +The number 8 is the powerful number. +The number 9 is the powerful number. +The number 10 is not the powerful number. +The number 11 is not the powerful number. +The number 12 is not the powerful number. +The number 13 is not the powerful number. +The number 14 is not the powerful number. +The number 15 is not the powerful number. +The number 16 is the powerful number. +The number 17 is not the powerful number. +The number 18 is not the powerful number. +The number 19 is not the powerful number. +The number 20 is the powerful number." +What is Super Keyword in Java?,"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." +What are the Usage of Java super Keyword?,"1.super can be used to refer immediate parent class instance variable. +2.super can be used to invoke immediate parent class method. +3.super() can be used to invoke immediate parent class constructor. +" +Can you provide an example of super can be used to invoke parent class method in Java?,"The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden. + +class Animal{ +void eat(){System.out.println(""eating..."");} +} +class Dog extends Animal{ +void eat(){System.out.println(""eating bread..."");} +void bark(){System.out.println(""barking..."");} +void work(){ +super.eat(); +bark(); +} +} +class TestSuper2{ +public static void main(String args[]){ +Dog d=new Dog(); +d.work(); +}} +Output: + +eating... +barking..." +Can you provide an example of super is used to invoke parent class constructor in Java?,"The super keyword can also be used to invoke the parent class constructor. Let's see a simple example: +class Animal{ +Animal(){System.out.println(""animal is created"");} +} +class Dog extends Animal{ +Dog(){ +super(); +System.out.println(""dog is created""); +} +} +class TestSuper3{ +public static void main(String args[]){ +Dog d=new Dog(); +}} +Output: + +animal is created +dog is created" +Can you provide a super example: real use in Java?,"Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from child class. In such way, we are reusing the parent class constructor. + +class Person{ +int id; +String name; +Person(int id,String name){ +this.id=id; +this.name=name; +} +} +class Emp extends Person{ +float salary; +Emp(int id,String name,float salary){ +super(id,name);//reusing parent constructor +this.salary=salary; +} +void display(){System.out.println(id+"" ""+name+"" ""+salary);} +} +class TestSuper5{ +public static void main(String[] args){ +Emp e1=new Emp(1,""ankit"",45000f); +e1.display(); +}} +Output: + +1 ankit 45000" +What is Instance initializer block in Java?,"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." +Why use instance initializer block?,"Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to fill a complex array or error handling etc. " +Can you provide an Example of instance initializer block in Java?,"Let's see the simple example of instance initializer block that performs initialization. +class Bike7{ + int speed; + + Bike7(){System.out.println(""speed is ""+speed);} + + {speed=100;} + + public static void main(String args[]){ + Bike7 b1=new Bike7(); + Bike7 b2=new Bike7(); + } +} +Output:speed is 100 + speed is 100 + " +"What is invoked first, instance initializer block or constructor?","class Bike8{ + int speed; + + Bike8(){System.out.println(""constructor is invoked"");} + + {System.out.println(""instance initializer block invoked"");} + + public static void main(String args[]){ + Bike8 b1=new Bike8(); + Bike8 b2=new Bike8(); + } +} +Output:instance initializer block invoked + constructor is invoked + instance initializer block invoked + constructor is invoked" +What are the Rules for instance initializer block in Java?,"There are mainly three rules for the instance initializer block. They are as follows: +The instance initializer block is created when instance of the class is created. +The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call). +The instance initializer block comes in the order in which they appear." +Can you provide an example Program of instance initializer block that is invoked after super()?,"class A{ +A(){ +System.out.println(""parent class constructor invoked""); +} +} +class B2 extends A{ +B2(){ +super(); +System.out.println(""child class constructor invoked""); +} + +{System.out.println(""instance initializer block is invoked"");} + +public static void main(String args[]){ +B2 b=new B2(); +} +} +Output:parent class constructor invoked + instance initializer block is invoked + child class constructor invoked" +Can you provid an example of instance block in java?,"class A{ +A(){ +System.out.println(""parent class constructor invoked""); +} +} + +class B3 extends A{ +B3(){ +super(); +System.out.println(""child class constructor invoked""); +} + +B3(int a){ +super(); +System.out.println(""child class constructor invoked ""+a); +} + +{System.out.println(""instance initializer block is invoked"");} + +public static void main(String args[]){ +B3 b1=new B3(); +B3 b2=new B3(10); +} +} + Output: parent class constructor invoked + instance initializer block is invoked + child class constructor invoked + parent class constructor invoked + instance initializer block is invoked + child class constructor invoked 10" +What is Final Keyword In Java?,"The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: + +1.variable +2.method +3.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 is Java final variable?,"If you make any variable as final, you cannot change the value of final variable(It will be constant)." +Can you provide an Example of final variable in Java?,"There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed. +class Bike9{ + final int speedlimit=90;//final variable + void run(){ + speedlimit=400; + } + public static void main(String args[]){ + Bike9 obj=new Bike9(); + obj.run(); + } +}//end of class +Output:Compile Time Error" +What is Java final method?,"If you make any method as final, you cannot override it." +Can you provide an Example of final method in Java?,"class Bike{ + final void run(){System.out.println(""running"");} +} + +class Honda extends Bike{ + void run(){System.out.println(""running safely with 100kmph"");} + + public static void main(String args[]){ + Honda honda= new Honda(); + honda.run(); + } +} +Output:Compile Time Error" +What is Java final class?,"If you make any class as final, you cannot extend it." +Can you provide an Example of final class in Java?,"final class Bike{} + +class Honda1 extends Bike{ + void run(){System.out.println(""running safely with 100kmph"");} + + public static void main(String args[]){ + Honda1 honda= new Honda1(); + honda.run(); + } +} +Output:Compile Time Error" +Is final method inherited?," Yes, final method is inherited but you cannot override it. For Example: +class Bike{ + final void run(){System.out.println(""running..."");} +} +class Honda2 extends Bike{ + public static void main(String args[]){ + new Honda2().run(); + } +} +Output:running..." +What is blank or uninitialized final variable?,"A final variable that is not initialized at the time of declaration is known as blank final variable. + +If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. + +It can be initialized only in constructor. " +Can you provide an Example of blank final variable in Java?,"class Student{ +int id; +String name; +final String PAN_CARD_NUMBER; +... +} " +What is static blank final variable?,A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block. +Can you provide an Example of static blank final variable in Java?,"class A{ + static final int data;//static blank final variable + static{ data=50;} + public static void main(String args[]){ + System.out.println(A.data); + } +} " +Can we declare a constructor final?,"No, because constructor is never inherited." +What is Polymorphism in Java?,"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 Runtime Polymorphism in Java?,"Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. +In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. +Let's first understand the upcasting before Runtime Polymorphism. +Upcasting + +If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. + +class A{} +class B extends A{} +A a=new B();//upcasting + +For upcasting, we can use the reference variable of class type or an interface type. +For Example: + +interface I{} +class A{} +class B extends A implements I{} + +Here, the relationship of B class would be: + +B IS-A A +B IS-A I +B IS-A Object + +Since Object is the root class of all classes in Java, so we can write B IS-A Object. + + " +Can you provide an Example of Java Runtime Polymorphism?,"In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, the subclass method is invoked at runtime. + +Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism. + +class Bike{ + void run(){System.out.println(""running"");} +} +class Splendor extends Bike{ + void run(){System.out.println(""running safely with 60km"");} + + public static void main(String args[]){ + Bike b = new Splendor();//upcasting + b.run(); + } +} + + +Output: +running safely with 60km. + + + + " +Can you provide a Java Runtime Polymorphism Example: Bank?,"Consider a scenario where Bank is a class that provides a method to get the rate of interest. However, the rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest. + +class Bank{ +float getRateOfInterest(){return 0;} +} +class SBI extends Bank{ +float getRateOfInterest(){return 8.4f;} +} +class ICICI extends Bank{ +float getRateOfInterest(){return 7.3f;} +} +class AXIS extends Bank{ +float getRateOfInterest(){return 9.7f;} +} +class TestPolymorphism{ +public static void main(String args[]){ +Bank b; +b=new SBI(); +System.out.println(""SBI Rate of Interest: ""+b.getRateOfInterest()); +b=new ICICI(); +System.out.println(""ICICI Rate of Interest: ""+b.getRateOfInterest()); +b=new AXIS(); +System.out.println(""AXIS Rate of Interest: ""+b.getRateOfInterest()); +} +} + + +Output: + +SBI Rate of Interest: 8.4 +ICICI Rate of Interest: 7.3 +AXIS Rate of Interest: 9.7 + " +Can you provide an Java Runtime Polymorphism Example: Shape?,"class Shape{ +void draw(){System.out.println(""drawing..."");} +} +class Rectangle extends Shape{ +void draw(){System.out.println(""drawing rectangle..."");} +} +class Circle extends Shape{ +void draw(){System.out.println(""drawing circle..."");} +} +class Triangle extends Shape{ +void draw(){System.out.println(""drawing triangle..."");} +} +class TestPolymorphism2{ +public static void main(String args[]){ +Shape s; +s=new Rectangle(); +s.draw(); +s=new Circle(); +s.draw(); +s=new Triangle(); +s.draw(); +} +} +Output: + +drawing rectangle... +drawing circle... +drawing triangle..." +Can you provide a Java Runtime Polymorphism Example: Animal?,"class Animal{ +void eat(){System.out.println(""eating..."");} +} +class Dog extends Animal{ +void eat(){System.out.println(""eating bread..."");} +} +class Cat extends Animal{ +void eat(){System.out.println(""eating rat..."");} +} +class Lion extends Animal{ +void eat(){System.out.println(""eating meat..."");} +} +class TestPolymorphism3{ +public static void main(String[] args){ +Animal a; +a=new Dog(); +a.eat(); +a=new Cat(); +a.eat(); +a=new Lion(); +a.eat(); +}} +Output: +eating bread... +eating rat... +eating meat..." +What is Java Runtime Polymorphism with Data Member?,"A method is overridden, not the data members, so runtime polymorphism can't be achieved by data members. + +In the example given below, both the classes have a data member speedlimit. We are accessing the data member by the reference variable of Parent class which refers to the subclass object. Since we are accessing the data member which is not overridden, hence it will access the data member of the Parent class always. +" +What is Java Runtime Polymorphism with Multilevel Inheritance?,"Let's see the simple example of Runtime Polymorphism with multilevel inheritance. + +class Animal{ +void eat(){System.out.println(""eating"");} +} +class Dog extends Animal{ +void eat(){System.out.println(""eating fruits"");} +} +class BabyDog extends Dog{ +void eat(){System.out.println(""drinking milk"");} +public static void main(String args[]){ +Animal a1,a2,a3; +a1=new Animal(); +a2=new Dog(); +a3=new BabyDog(); +a1.eat(); +a2.eat(); +a3.eat(); +} +} +Output: + +eating +eating fruits +drinking Milk" +What is Static Binding and Dynamic Binding?,"Connecting a method call to the method body is known as binding. + +There are two types of binding + +1.Static Binding (also known as Early Binding). +2.Dynamic Binding (also known as Late Binding)." +Does variables have a type in Java?,"Each variable has a type, it may be primitive and non-primitive. +int data=30; " +"Does References have a type in Java? +","class Dog{ + public static void main(String args[]){ + Dog d1;//Here d1 is a type of Dog + } +} " +Doese Objects have a type in java?,"An object is an instance of particular java class,but it is also an instance of its superclass. +class Animal{} + +class Dog extends Animal{ + public static void main(String args[]){ + Dog d1=new Dog(); + } +} " +What is static binding?,"When type of the object is determined at compiled time(by the compiler), it is known as static binding. + +If there is any private, final or static method in a class, there is static binding." +Can you provide an Example of static binding in Java?,"class Dog{ + private void eat(){System.out.println(""dog is eating..."");} + + public static void main(String args[]){ + Dog d1=new Dog(); + d1.eat(); + } +} " +What is Dynamic binding ?,"When type of the object is determined at run-time, it is known as dynamic binding." +Can you provide an Example of dynamic binding in Java?,"class Animal{ + void eat(){System.out.println(""animal is eating..."");} +} + +class Dog extends Animal{ + void eat(){System.out.println(""dog is eating..."");} + + public static void main(String args[]){ + Animal a=new Dog(); + a.eat(); + } +} +Output:dog is eating..." +What is 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." +Can you provide a Simple example of java instanceof?,"Let's see the simple example of instance operator where it tests the current class. + +class Simple1{ + public static void main(String args[]){ + Simple1 s=new Simple1(); + System.out.println(s instanceof Simple1);//true + } +} +Output:true" +Can you provide Another example of java instanceof operator?,"class Animal{} +class Dog1 extends Animal{//Dog inherits Animal + + public static void main(String args[]){ + Dog1 d=new Dog1(); + System.out.println(d instanceof Animal);//true + } +} +" +Can you provide a example instanceof in java with a variable that have null value?,"If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below where we apply instanceof operator with the variable that have null value. + +class Dog2{ + public static void main(String args[]){ + Dog2 d=null; + System.out.println(d instanceof Dog2);//false + } +} +Output:false" +What is Downcasting with java instanceof operator?,"When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible. + +Dog d=new Animal();//Compilation error +If we perform downcasting by typecasting, ClassCastException is thrown at runtime. + +Dog d=(Dog)new Animal(); +//Compiles successfully but ClassCastException is thrown at runtime " +What is Possibility of downcasting with instanceof?,"Let's see the example, where downcasting is possible by instanceof operator. + +class Animal { } + +class Dog3 extends Animal { + static void method(Animal a) { + if(a instanceof Dog3){ + Dog3 d=(Dog3)a;//downcasting + System.out.println(""ok downcasting performed""); + } + } + + public static void main (String [] args) { + Animal a=new Dog3(); + Dog3.method(a); + } + + } +Output:ok downcasting performed" +How to downcast without the use of java instanceof,"Downcasting can also be performed without the use of instanceof operator as displayed in the following example: + +class Animal { } +class Dog4 extends Animal { + static void method(Animal a) { + Dog4 d=(Dog4)a;//downcasting + System.out.println(""ok downcasting performed""); + } + public static void main (String [] args) { + Animal a=new Dog4(); + Dog4.method(a); + } +} +Output:ok downcasting performed" +How to understand Real use of instanceof in java?,"Let's see the real use of instanceof keyword by the example given below. + +interface Printable{} +class A implements Printable{ +public void a(){System.out.println(""a method"");} +} +class B implements Printable{ +public void b(){System.out.println(""b method"");} +} + +class Call{ +void invoke(Printable p){//upcasting +if(p instanceof A){ +A a=(A)p;//Downcasting +a.a(); +} +if(p instanceof B){ +B b=(B)p;//Downcasting +b.b(); +} + +} +}//end of Call class + +class Test4{ +public static void main(String args[]){ +Printable p=new B(); +Call c=new Call(); +c.invoke(p); +} +} +Output: b method" +What is Abstract class in Java?,"A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body). + +Before learning the Java abstract class, let's understand the abstraction in Java first." +What is Abstraction in Java?,"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. +" +What is Abstract Method in Java?,"A method which is declared as abstract and does not have implementation is known as an abstract method. + +Example of abstract method + +abstract void printStatus();//no method body and abstract " +Can you provide an Example of Abstract class that has an abstract method?,"In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Honda class. + +abstract class Bike{ + abstract void run(); +} +class Honda4 extends Bike{ +void run(){System.out.println(""running safely"");} +public static void main(String args[]){ + Bike obj = new Honda4(); + obj.run(); +} +} +Output:running safely" +How to understand the real scenario of Abstract class in Java?,"In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle classes. + +Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the implementation class is provided by the factory method. + +A factory method is a method that returns the instance of the class. We will learn about the factory method later. + +In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked. + +File: TestAbstraction1.java + +abstract class Shape{ +abstract void draw(); +} +//In real scenario, implementation is provided by others i.e. unknown by end user +class Rectangle extends Shape{ +void draw(){System.out.println(""drawing rectangle"");} +} +class Circle1 extends Shape{ +void draw(){System.out.println(""drawing circle"");} +} +//In real scenario, method is called by programmer or user +class TestAbstraction1{ +public static void main(String args[]){ +Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method +s.draw(); +} +} +Output: drawing circle" +Can you provide Another example of Abstract class in java?,"abstract class Bank{ +abstract int getRateOfInterest(); +} +class SBI extends Bank{ +int getRateOfInterest(){return 7;} +} +class PNB extends Bank{ +int getRateOfInterest(){return 8;} +} + +class TestBank{ +public static void main(String args[]){ +Bank b; +b=new SBI(); +System.out.println(""Rate of Interest is: ""+b.getRateOfInterest()+"" %""); +b=new PNB(); +System.out.println(""Rate of Interest is: ""+b.getRateOfInterest()+"" %""); +}} +Output: Rate of Interest is: 7 % +Rate of Interest is: 8 %" +"Can you provide an example of Abstract class having constructor, data member and methods? +","An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and even main() method. + +File: TestAbstraction2.java + +//Example of an abstract class that has abstract and non-abstract methods + abstract class Bike{ + Bike(){System.out.println(""bike is created"");} + abstract void run(); + void changeGear(){System.out.println(""gear changed"");} + } +//Creating a Child class which inherits Abstract class + class Honda extends Bike{ + void run(){System.out.println(""running safely.."");} + } +//Creating a Test class which calls abstract and non-abstract methods + class TestAbstraction2{ + public static void main(String args[]){ + Bike obj = new Honda(); + obj.run(); + obj.changeGear(); + } +} + Output: bike is created + running safely.. + gear changed" +What is Interface in Java?,"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. + +Java Interface also represents the IS-A relationship. +It cannot be instantiated just like the abstract class. + +Since Java 8, we can have default and static methods in an interface. + +Since Java 9, we can have private methods in an interface." +Why use Java interface?,"There are mainly three reasons to use interface. They are given below. + +-It is used to achieve abstraction. +-By interface, we can support the functionality of multiple inheritance. +-It can be used to achieve loose coupling." +How to declare an interface?,"An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface." +Can you provide Java Interface Example?,"In this example, the Printable interface has only one method, and its implementation is provided in the A6 class. + +interface printable{ +void print(); +} +class A6 implements printable{ +public void print(){System.out.println(""Hello"");} + +public static void main(String args[]){ +A6 obj = new A6(); +obj.print(); + } +} +Output: Hello" +Can you provide Java Interface Example: Drawable?,"In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its implementation is provided by different implementation providers. Moreover, it is used by someone else. The implementation part is hidden by the user who uses the interface. + +File: TestInterface1.java + +//Interface declaration: by first user +interface Drawable{ +void draw(); +} +//Implementation: by second user +class Rectangle implements Drawable{ +public void draw(){System.out.println(""drawing rectangle"");} +} +class Circle implements Drawable{ +public void draw(){System.out.println(""drawing circle"");} +} +//Using interface: by third user +class TestInterface1{ +public static void main(String args[]){ +Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable() +d.draw(); +}} +Output: +drawing circle" +Can you provide Java Interface Example: Bank?,"Let's see another example of java interface which provides the implementation of Bank interface. + +File: TestInterface2.java + +interface Bank{ +float rateOfInterest(); +} +class SBI implements Bank{ +public float rateOfInterest(){return 9.15f;} +} +class PNB implements Bank{ +public float rateOfInterest(){return 9.7f;} +} +class TestInterface2{ +public static void main(String[] args){ +Bank b=new SBI(); +System.out.println(""ROI: ""+b.rateOfInterest()); +}} +Output: +ROI: 9.15" +"Multiple inheritance is not supported through class in java, but it is possible by an interface, why?","As we have explained in the inheritance chapter, 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. For example: + +interface Printable{ +void print(); +} +interface Showable{ +void print(); +} + +class TestInterface3 implements Printable, Showable{ +public void print(){System.out.println(""Hello"");} +public static void main(String args[]){ +TestInterface3 obj = new TestInterface3(); +obj.print(); + } +} +Output: + +Hello" +What is Interface inheritance?,"A class implements an interface, but one interface extends another interface." +Can you provide Java 8 Default Method in Interface?,"Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an example: +interface Drawable{ +void draw(); +default void msg(){System.out.println(""default method"");} +} +class Rectangle implements Drawable{ +public void draw(){System.out.println(""drawing rectangle"");} +} +class TestInterfaceDefault{ +public static void main(String args[]){ +Drawable d=new Rectangle(); +d.draw(); +d.msg(); +}} interface Drawable{ +void draw(); +default void msg(){System.out.println(""default method"");} +} +class Rectangle implements Drawable{ +public void draw(){System.out.println(""drawing rectangle"");} +} +class TestInterfaceDefault{ +public static void main(String args[]){ +Drawable d=new Rectangle(); +d.draw(); +d.msg(); +}} +Output: + +drawing rectangle +default method" +Can you provide Java 8 Static Method in Interface?,"ince Java 8, we can have static method in interface. Let's see an example: +interface Drawable{ +void draw(); +static int cube(int x){return x*x*x;} +} +class Rectangle implements Drawable{ +public void draw(){System.out.println(""drawing rectangle"");} +} + +class TestInterfaceStatic{ +public static void main(String args[]){ +Drawable d=new Rectangle(); +d.draw(); +System.out.println(Drawable.cube(3)); +}} +Output: + +drawing rectangle +27" + What is marker or tagged interface?,"An interface which has no member is known as a marker or tagged interface, for example, Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation. + +//How Serializable interface is written? +public interface Serializable{ +} " +What is Nested Interface in Java?,"Note: An interface can have another interface which is known as a nested interface. We will learn it in detail in the nested classes chapter. For example: + +interface printable{ + void print(); + interface MessagePrintable{ + void msg(); + } +} " +Can you provide an Example of abstract class and interface in Java?,"Let's see a simple example where we are using interface and abstract class both. +//Creating interface that has 4 methods +interface A{ +void a();//bydefault, public and abstract +void b(); +void c(); +void d(); +} + +//Creating abstract class that provides the implementation of one method of A interface +abstract class B implements A{ +public void c(){System.out.println(""I am C"");} +} + +//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods +class M extends B{ +public void a(){System.out.println(""I am a"");} +public void b(){System.out.println(""I am b"");} +public void d(){System.out.println(""I am d"");} +} + +//Creating a test class that calls the methods of A interface +class Test5{ +public static void main(String args[]){ +A a=new M(); +a.a(); +a.b(); +a.c(); +a.d(); +}} +Output: + + I am a + I am b + I am c + I am d" +What is Java Package?,"A java package is a group of similar types of classes, interfaces and sub-packages. + +Package in java can be categorized in two form, built-in package and user-defined package. + +There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. +" +What is the Advantage of Java Package?,"1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. + +2) Java package provides access protection. + +3) Java package removes naming collision. + +" +Can you provide Simple example of java package?,"The package keyword is used to create a package in java. + +//save as Simple.java +package mypack; +public class Simple{ + public static void main(String args[]){ + System.out.println(""Welcome to package""); + } +} " +How to access package from another package?,"There are three ways to access the package from outside the package. + +1.import package.*; +2.import package.classname; +3.fully qualified name." +What is Using packagename?,"If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. + +The import keyword is used to make the classes and interface of another package accessible to the current package." +Can you provide an Example of package that import the packagename?,"//save by A.java +package pack; +public class A{ + public void msg(){System.out.println(""Hello"");} +} +//save by B.java +package mypack; +import pack.*; + +class B{ + public static void main(String args[]){ + A obj = new A(); + obj.msg(); + } +} +Output:Hello" +What is Using packagename.classname?,If you import package.classname then only declared class of this package will be accessible. +Can you provide an Example of package by import package.classname?,"//save by A.java + +package pack; +public class A{ + public void msg(){System.out.println(""Hello"");} +} +//save by B.java +package mypack; +import pack.A; + +class B{ + public static void main(String args[]){ + A obj = new A(); + obj.msg(); + } +} +Output:Hello" +How the Using fully qualified name work?,"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. + +It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class." +Can you provide an Example of package by import fully qualified name?,"//save by A.java +package pack; +public class A{ + public void msg(){System.out.println(""Hello"");} +} +//save by B.java +package mypack; +class B{ + public static void main(String args[]){ + pack.A obj = new pack.A();//using fully qualified name + obj.msg(); + } +} +Output:Hello" +What is Subpackage in java?,Package inside the package is called the subpackage. It should be created to categorize the package further. +Can you provide an Example of Subpackage?,"package com.javatpoint.core; +class Simple{ + public static void main(String args[]){ + System.out.println(""Hello subpackage""); + } +} +To Compile: javac -d . Simple.java +To Run: java com.javatpoint.core.Simple +Output:Hello subpackage" +What are the Ways to load the class files or jar files?,"There are two ways to load the class files temporary and permanent. +-Temporary +By setting the classpath in the command prompt +By -classpath switch +-Permanent +By setting the classpath in the environment variables +By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder." +How to put two public classes in a package?,"If you want to put two public classes in a package, have two java source files containing one public class, but keep the package name same. For example: +//save as A.java + +package javatpoint; +public class A{} +//save as B.java + +package javatpoint; +public class B{} " +What is Access Modifiers in Java?,"There are two types of modifiers in Java: access modifiers and non-access modifiers. + +The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. +There are four types of Java access modifiers: + +1.Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. +2.Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. +3.Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. +4.Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. +There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only. + +" +What is Private?,"The private access modifier is accessible only within the class. + +Simple example of private access modifier + +In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is a compile-time error. + +class A{ +private int data=40; +private void msg(){System.out.println(""Hello java"");} +} + +public class Simple{ + public static void main(String args[]){ + A obj=new A(); + System.out.println(obj.data);//Compile Time Error + obj.msg();//Compile Time Error + } +} " +What is Default?,"If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public. + +Example of default access modifier + +In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package. + +//save by A.java +package pack; +class A{ + void msg(){System.out.println(""Hello"");} +} +//save by B.java +package mypack; +import pack.*; +class B{ + public static void main(String args[]){ + A obj = new A();//Compile Time Error + obj.msg();//Compile Time Error + } +} " +What is Protected?,"The protected access modifier is accessible within package and outside the package but through inheritance only. + +The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class. + +It provides more accessibility than the default modifer. + +Example of protected access modifier + +In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance. + +//save by A.java +package pack; +public class A{ +protected void msg(){System.out.println(""Hello"");} +} +//save by B.java +package mypack; +import pack.*; + +class B extends A{ + public static void main(String args[]){ + B obj = new B(); + obj.msg(); + } +} +Output:Hello" +What is Public?,"The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. + +Example of public access modifier + +//save by A.java + +package pack; +public class A{ +public void msg(){System.out.println(""Hello"");} +} +//save by B.java + +package mypack; +import pack.*; + +class B{ + public static void main(String args[]){ + A obj = new A(); + obj.msg(); + } +} +Output:Hello" +Can you provide an example of Java Access Modifiers with Method Overriding?,"If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive. + +class A{ +protected void msg(){System.out.println(""Hello java"");} +} + +public class Simple extends A{ +void msg(){System.out.println(""Hello java"");}//C.T.Error + public static void main(String args[]){ + Simple obj=new Simple(); + obj.msg(); + } +} " +What is Encapsulation in Java?,"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. + +The Java Bean class is the example of a fully encapsulated class." +What is the Advantage of Encapsulation in Java?,"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.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." +Can you provide Simple Example of Encapsulation in Java?,"Let's see the simple example of encapsulation that has only one field with its setter and getter methods. +//A Java class which is a fully encapsulated class. +//It has a private data member and getter and setter methods. +package com.javatpoint; +public class Student{ +//private data member +private String name; +//getter method for name +public String getName(){ +return name; +} +//A Java class to test the encapsulated class. +package com.javatpoint; +class Test{ +public static void main(String[] args){ +//creating instance of the encapsulated class +Student s=new Student(); +//setting value in the name member +s.setName(""vijay""); +//getting value of the name member +System.out.println(s.getName()); +} +} +Compile By: javac -d . Test.java +Run By: java com.javatpoint.Test +Output: + +vijay +//setter method for name +public void setName(String name){ +this.name=name +} +} " +What is Read-Only class?,"//A Java class which has only getter methods. +public class Student{ +//private data member +private String college=""AKG""; +//getter method for college +public String getCollege(){ +return college; +} +} " +What is Write-Only class?,"//A Java class which has only setter methods. +public class Student{ +//private data member +private String college; +//getter method for college +public void setCollege(String college){ +this.college=college; +} +} " +Can you provide Another Example of Encapsulation in Java?,"Let's see another example of encapsulation that has only four fields with its setter and getter methods. +//A Account class which is a fully encapsulated class. +//It has a private data member and getter and setter methods. +class Account { +//private data members +private long acc_no; +private String name,email; +private float amount; +//public getter and setter methods +public long getAcc_no() { + return acc_no; +} +public void setAcc_no(long acc_no) { + this.acc_no = acc_no; +} +public String getName() { + return name; +} +public void setName(String name) { + this.name = name; +} +public String getEmail() { + return email; +} +public void setEmail(String email) { + this.email = email; +} +public float getAmount() { + return amount; +} +public void setAmount(float amount) { + this.amount = amount; +} + +} +//A Java class to test the encapsulated class Account. +public class TestEncapsulation { +public static void main(String[] args) { + //creating instance of Account class + Account acc=new Account(); + //setting values through setter methods + acc.setAcc_no(7560504000L); + acc.setName(""Sonoo Jaiswal""); + acc.setEmail(""sonoojaiswal@javatpoint.com""); + acc.setAmount(500000f); + //getting values through getter methods + System.out.println(acc.getAcc_no()+"" ""+acc.getName()+"" ""+acc.getEmail()+"" ""+acc.getAmount()); +} +} +Output: + +7560504000 Sonoo Jaiswal sonoojaiswal@javatpoint.com 500000.0" +What is Java Arrays?,"Normally, an array is a collection of similar type of elements which has contiguous memory location. + +Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. + +Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on. + +Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator. + +In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java. + +Moreover, Java provides the feature of anonymous arrays which is not available in C/C++. + +Advantages + +-Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. +-Random access: We can get any data located at an index position. +Disadvantages +-Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used + + +" +What are the Types of Array in java?,"There are two types of array. + +-Single Dimensional Array +-Multidimensional Array + + +" +WHat is Single Dimensional Array in Java?," +Syntax to Declare an Array in Java + +dataType[] arr; (or) +dataType []arr; (or) +dataType arr[]; + +Instantiation of an Array in Java + +arrayRefVar=new datatype[size]; + + " +Can you provide an Example of Java Array?,"Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array. + +//Java Program to illustrate how to declare, instantiate, initialize +//and traverse the Java array. +class Testarray{ +public static void main(String args[]){ +int a[]=new int[5];//declaration and instantiation +a[0]=10;//initialization +a[1]=20; +a[2]=70; +a[3]=40; +a[4]=50; +//traversing array +for(int i=0;iarr[i]) + min=arr[i]; + +System.out.println(min); +} + +public static void main(String args[]){ +int a[]={33,3,4,5};//declaring and initializing an array +min(a);//passing array to method +}} + +Output: + +3 + + " +Can you provide the Anonymous Array in Java?,"Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the method. + +//Java Program to demonstrate the way of passing an anonymous array +//to method. +public class TestAnonymousArray{ +//creating a method which receives an array as a parameter +static void printArray(int arr[]){ +for(int i=0;i0){ + n3 = n1 + n2; + n1 = n2; + n2 = n3; + System.out.print("" ""+n3); + printFibo(count-1); + } + } + +public static void main(String[] args) { + int count=15; + System.out.print(n1+"" ""+n2);//printing 0 and 1 + printFibo(count-2);//n-2 because 2 numbers are already printed +} +} +Output: + +0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" +What is Call by Value and Call by Reference in Java?,"There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method." +Can you provide an Example of call by value in java?,"class Operation{ + int data=50; + + void change(int data){ + data=data+100;//changes will be in the local variable only + } + + public static void main(String args[]){ + Operation op=new Operation(); + + System.out.println(""before change ""+op.data); + op.change(500); + System.out.println(""after change ""+op.data); + + } +} +Output:before change 50 + after change 50 " +What is 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 arithmetic. +" +What is Legal code for strictfp keyword?,"The strictfp keyword can be applied on methods, classes and interfaces. + +strictfp class A{}//strictfp applied on class +strictfp interface M{}//strictfp applied on interface +class A{ +strictfp void m(){}//strictfp applied on method +} " +What is Illegal code for strictfp keyword?,"The strictfp keyword cannot be applied on abstract methods, variables or constructors. + +class B{ +strictfp abstract void m();//Illegal combination of modifiers +} +class B{ +strictfp int data=10;//modifier strictfp not allowed here +} +class B{ +strictfp B(){}//modifier strictfp not allowed here +} " +What is Creating API Document | javadoc tool?,"We can create document api in java by the help of javadoc tool. In the java file, we must use the documentation comment /**... */ to post information for the class, method, constructor, fields etc. +Let's see the simple class that contains documentation comment. + +package com.abc; +/** This class is a user-defined class that contains one methods cube.*/ +public class M{ + +/** The cube method prints cube of the given number */ +public static void cube(int n){System.out.println(n*n*n);} +} +To create the document API, you need to use the javadoc tool followed by java file name. There is no need to compile the javafile. + +On the command prompt, you need to write: +javadoc M.java +to generate the document api. Now, there will be created a lot of html files. Open the index.html file to get the information about the classes." +What is Java Command Line Arguments?,"The java command-line argument is an argument i.e. passed at the time of running the java program. + +The arguments passed from the console can be received in the java program and it can be used as an input. + +So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt." +Can you provide Simple example of command-line argument in java?,"In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt. +class CommandLineExample{ +public static void main(String args[]){ +System.out.println(""Your first argument is: ""+args[0]); +} +} +compile by > javac CommandLineExample.java +run by > java CommandLineExample sonoo +Output: Your first argument is: sonoo" +Can you provide an Example of command-line argument that prints all the values?,"In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop. +class A{ +public static void main(String args[]){ + +for(int i=0;i javac A.java +run by > java A sonoo jaiswal 1 3 abc +Output: sonoo + jaiswal + 1 + 3 + abc" +What are the Difference between object and class?,"There are many differences between object and class. A list of differences between object and class are given below: + +1) Object is an instance of a class while Class is a blueprint or template from which objects are created +2) Object is a real world entity such as pen, laptop, mobile, bed, keyboard, mouse, chair etc. while Class is a group of similar objects +3) Object is a physical entity while Object is a physical entity. +4) Object is created through new keyword mainly e.g. +Student s1=new Student(); while Class is declared using class keyword e.g. +class Student{} +5) Object is created many times as per requirement while Class is declared once. +6) Object allocates memory when it is created while Class doesn't allocated memory when it is created. +7) There are many ways to create object in java such as new keyword, newInstance() method, clone() method, factory method and deserialization while there is only one way to define class in java using class keyword + +Let's see some real life example of class and object in java to understand the difference well: + +Class: Human Object: Man, Woman +Class: Fruit Object: Apple, Banana, Mango, Guava wtc. +Class: Mobile phone Object: iPhone, Samsung, Moto +Class: Food Object: Pizza, Burger, Samosa + + " +Can you provide Java Method Overloading example?,"class OverloadingExample{ +static int add(int a,int b){return a+b;} +static int add(int a,int b,int c){return a+b+c;} +} " +Can you provide Java Method Overriding example?,"class Animal{ +void eat(){System.out.println(""eating..."");} +} +class Dog extends Animal{ +void eat(){System.out.println(""eating bread..."");} +} " +What is Java String?,"n Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: + +char[] ch={'j','a','v','a','t','p','o','i','n','t'}; +String s=new String(ch); +is same as: + +String s=""javatpoint""; +Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. + +The java.lang.String class implements Serializable, Comparable and CharSequence interfaces. +" +CharSequence Interface,"The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using these three classes. +The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes. + +We will discuss immutable string later. Let's first understand what String in Java is and how to create the String object." +What is String in Java?,"Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object." +How to create a string object?,"There are two ways to create String object: + +1.By string literal +2.By new keyword" +What is String Literal?,"Java String literal is created by using double quotes. For Example: + +String s=""welcome""; +Each time you create a string literal, the JVM checks the ""string constant pool"" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: + +String s1=""Welcome""; +String s2=""Welcome"";//It doesn't create a new instance + +In the above example, only one object will be created. Firstly, JVM will not find any string object with the value ""Welcome"" in string constant pool that is why it will create a new object. After that it will find the string with the value ""Welcome"" in the pool, it will not create a new object but will return the reference to the same instance." +By new keyword,"String s=new String(""Welcome"");//creates two objects and one reference variable +In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal ""Welcome"" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool)." +Can you provide Java String Example?,"public class StringExample{ +public static void main(String args[]){ +String s1=""java"";//creating string by Java string literal +char ch[]={'s','t','r','i','n','g','s'}; +String s2=new String(ch);//converting char array to string +String s3=new String(""example"");//creating Java string by new keyword +System.out.println(s1); +System.out.println(s2); +System.out.println(s3); +}} +Output: + +java +strings +example" +Java String class methods,"The java.lang.String class provides many useful methods to perform operations on sequence of char values. + + +char charAt(int index) - It returns char value for the particular index +int length() - It returns string length +static String format(String format, Object... args) - It returns a formatted string. +static String format(Locale l, String format, Object... args) - It returns formatted string with given locale +String substring(int beginIndex) - It returns substring for given begin index. +String substring(int beginIndex, int endIndex) - It returns substring for given begin index and end index. +boolean contains(CharSequence s) - It returns true or false after matching the sequence of char value. +static String join(CharSequence delimiter, CharSequence... elements) - It returns a joined string. +static String join(CharSequence delimiter, Iterable elements) - It returns a joined string. +boolean equals(Object another) - It checks the equality of string with the given object. +boolean isEmpty() - It checks if string is empty +String concat(String str) - It concatenates the specified string. +String replace(char old, char new) - It replaces all occurrences of the specified char value. +String replace(CharSequence old, CharSequence new) - It replaces all occurrences of the specified CharSequence. +static String equalsIgnoreCase(String another) - It compares another string. It doesn't check case. +String[] split(String regex) - It returns a split string matching regex. +String[] split(String regex, int limit) - It returns a split string matching regex and limit +String intern() - It returns an interned string. +int indexOf(int ch) - It returns the specified char value index. +int indexOf(int ch, int fromIndex) - It returns the specified char value index starting with given index +int indexOf(String substring) - It returns the specified substring index. +int indexOf(String substring, int fromIndex) - It returns the specified substring index starting with given index +String toLowerCase() - It returns a string in lowercase. +String toLowerCase(Locale l) - It returns a string in lowercase using specified locale. +String toUpperCase() - It returns a string in uppercase. +String toUpperCase(Locale l) - It returns a string in uppercase using specified locale. +String trim() - It removes beginning and ending spaces of this string. +static String valueOf(int value) - It converts given type into string. It is an overloaded method + " +What is Immutable String in Java?,"A String is an unavoidable type of variable while writing any application program. String references are used to store various attributes like username, password, etc. In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable. + +Once String object is created its data or state can't be changed but a new String object is created." +Testimmutablestring.java,"class Testimmutablestring{ + public static void main(String args[]){ + String s=""Sachin""; + s.concat("" Tendulkar"");//concat() method appends the string at the end + System.out.println(s);//will print Sachin because strings are immutable objects + } +} +Output: + +Sachin +" +Why String objects are immutable in Java?,"As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one object ""Sachin"". If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why String objects are immutable in Java. + +Following are some features of String which makes String objects immutable. + +1. ClassLoader: + +A ClassLoader in Java uses a String object as an argument. Consider, if the String object is modifiable, the value might be changed and the class that is supposed to be loaded might be different. + +To avoid this kind of misinterpretation, String is immutable. + +2. Thread Safe: + +As the String object is immutable we don't have to take care of the synchronization that is required while sharing an object across multiple threads. + +3. Security: + +As we have seen in class loading, immutable String objects avoid further errors by loading the correct class. This leads to making the application program more secure. Consider an example of banking software. The username and password cannot be modified by any intruder because String objects are immutable. This can make the application program more secure. + +4. Heap Space: + +The immutability of String helps to minimize the usage in the heap memory. When we try to declare a new String object, the JVM checks whether the value already exists in the String pool or not. If it exists, the same value is assigned to the new object. This feature allows Java to use the heap space efficiently." +Why String class is Final in Java?,The reason behind the String class being final is because no one can override the methods of the String class. So that it can provide the same features to the new String objects as well as to the old ones. +What is Java String compare?,"We can compare String in Java on the basis of content and reference. + +It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. + +There are three ways to compare String in Java: + +1.By Using equals() Method +2.By Using == Operator +3.By compareTo() Method" +How to use Java string compares By Using equals() Method?,"The String class equals() method compares the original content of the string. It compares values of string for equality. String class provides the following two methods: + +-public boolean equals(Object another) compares this string to the specified object. +-public boolean equalsIgnoreCase(String another) compares this string to another string, ignoring case." +How to use By Using compareTo() method?,"The String class compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string. + +Suppose s1 and s2 are two String objects. If: + +-s1 == s2 : The method returns 0. +-s1 > s2 : The method returns a positive value. +-s1 < s2 : The method returns a negative value." +What is String Concatenation in Java?,"In Java, String concatenation forms a new String that is the combination of multiple strings. There are two ways to concatenate strings in Java: + +1.By + (String concatenation) operator +2.By concat() method" +Can you provide String Concatenation by + (String concatenation) operator?,"Java String concatenation operator (+) is used to add strings. For Example: + +TestStringConcatenation1.java + +class TestStringConcatenation1{ + public static void main(String args[]){ + String s=""Sachin""+"" Tendulkar""; + System.out.println(s);//Sachin Tendulkar + } +} +Output: +Sachin Tendulkar" +How to concatenate string by concat() method?,"The String concat() method concatenates the specified string to the end of current string. Syntax: + +public String concat(String another) +Let's see the example of String concat() method. + +TestStringConcatenation3.java + +class TestStringConcatenation3{ + public static void main(String args[]){ + String s1=""Sachin ""; + String s2=""Tendulkar""; + String s3=s1.concat(s2); + System.out.println(s3);//Sachin Tendulkar + } +} The String concat() method concatenates the specified string to the end of current string. Syntax: + +public String concat(String another) +Let's see the example of String concat() method. + +TestStringConcatenation3.java + +class TestStringConcatenation3{ + public static void main(String args[]){ + String s1=""Sachin ""; + String s2=""Tendulkar""; + String s3=s1.concat(s2); + System.out.println(s3);//Sachin Tendulkar + } +} +Output: + +Sachin Tendulkar" +Can you provide String concatenation example using StringBuilder class?,"StringBuilder is class provides append() method to perform concatenation operation. The append() method accepts arguments of different types like Objects, StringBuilder, int, char, CharSequence, boolean, float, double. StringBuilder is the most popular and fastet way to concatenate strings in Java. It is mutable class which means values stored in StringBuilder objects can be updated or changed. + +StrBuilder.java +public class StrBuilder +{ + /* Driver Code */ + public static void main(String args[]) + { + StringBuilder s1 = new StringBuilder(""Hello""); //String 1 + StringBuilder s2 = new StringBuilder("" World""); //String 2 + StringBuilder s = s1.append(s2); //String 3 to store the result + System.out.println(s.toString()); //Displays result + } +} + +Output: +Hello World + +In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores the result of concatenation of s1 and s2 using append() method. + " +Can you provide String concatenation using format() method?,"String.format() method allows to concatenate multiple strings using format specifier like %s followed by the string values or objects. + + +StrFormat.java +public class StrFormat +{ + /* Driver Code */ + public static void main(String args[]) + { + String s1 = new String(""Hello""); //String 1 + String s2 = new String("" World""); //String 2 + String s = String.format(""%s%s"",s1,s2); //String 3 to store the result + System.out.println(s.toString()); //Displays result + } +} + +Output: +Hello World + +Here, the String objects s is assigned the concatenated result of Strings s1 and s2 using String.format() method. format() accepts parameters as format specifier followed by String objects or values. + + " +Can you provide an example of String concatenation using String.join() method (Java Version 8+)?,"The String.join() method is available in Java version 8 and all the above versions. String.join() method accepts arguments first a separator and an array of String objects. + +StrJoin.java: +public class StrJoin +{ + /* Driver Code */ + public static void main(String args[]) + { + String s1 = new String(""Hello""); //String 1 + String s2 = new String("" World""); //String 2 + String s = String.join("""",s1,s2); //String 3 to store the result + System.out.println(s.toString()); //Displays result + } +} + +Output: +Hello World + +In the above code snippet, the String object s stores the result of String.join("""",s1,s2) method. A separator is specified inside quotation marks followed by the String objects or array of String objects. + + +" +Can you provide an example of String concatenation using StringJoiner class (Java Version 8+)?,"StringJoiner class has all the functionalities of String.join() method. In advance its constructor can also accept optional arguments, prefix and suffix. + +StrJoiner.java +public class StrJoiner +{ + /* Driver Code */ + public static void main(String args[]) + { + StringJoiner s = new StringJoiner("", ""); //StringeJoiner object + s.add(""Hello""); //String 1 + s.add(""World""); //String 2 + System.out.println(s.toString()); //Displays result + } +} + +Output: +Hello, World + +In the above code snippet, the StringJoiner object s is declared and the constructor StringJoiner() accepts a separator value. A separator is specified inside quotation marks. The add() method appends Strings passed as arguments. + + " +Can you provide an example of String concatenation using Collectors.joining() method (Java (Java Version 8+)?,"The Collectors class in Java 8 offers joining() method that concatenates the input elements in a similar order as they occur. + +ColJoining.java + +import java.util.*; +import java.util.stream.Collectors; +public class ColJoining +{ + /* Driver Code */ + public static void main(String args[]) + { + List liststr = Arrays.asList(""abc"", ""pqr"", ""xyz""); //List of String array + String str = liststr.stream().collect(Collectors.joining("", "")); //performs joining operation + System.out.println(str.toString()); //Displays result + } +} + +Output: +abc, pqr, xyz + +Here, a list of String array is declared. And a String object str stores the result of Collectors.joining() method. + + " +What is Substring in Java?,"A part of String is called substring. In other words, substring is a subset of another String. Java String class provides the built-in substring() method that extract a substring from the given string by using the index values passed as an argument. In case of substring() method startIndex is inclusive and endIndex is exclusive. + +Suppose the string is ""computer"", then the substring will be com, compu, ter, etc. + +You can get substring from the given String object by one of the two methods: + +public String substring(int startIndex): +This method returns new String object containing the substring of the given string from specified startIndex (inclusive). The method throws an IndexOutOfBoundException when the startIndex is larger than the length of String or less than zero. + +public String substring(int startIndex, int endIndex): +This method returns new String object containing the substring of the given string from specified startIndex to endIndex. The method throws an IndexOutOfBoundException when the startIndex is less than zero or startIndex is greater than endIndex or endIndex is greater than length of String. + +In case of String: +-startIndex: inclusive +-endIndex: exclusive + +Let's understand the startIndex and endIndex by the code given below. + +String s=""hello""; +System.out.println(s.substring(0,2)); //returns he as a substring + +In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end index is exclusive). +" +Can you provide Example of Java substring() method?,"TestSubstring.java +public class TestSubstring{ + public static void main(String args[]){ + String s=""SachinTendulkar""; + System.out.println(""Original String: "" + s); + System.out.println(""Substring starting from index 6: "" +s.substring(6));//Tendulkar + System.out.println(""Substring starting from index 0 to 6: ""+s.substring(0,6)); //Sachin + } +} + +Output: +Original String: SachinTendulkar +Substring starting from index 6: Tendulkar +Substring starting from index 0 to 6: Sachin + +The above Java programs, demonstrates variants of the substring() method of String class. The startindex is inclusive and endindex is exclusive. + + " +Can you provide an example of using String.split() method?,"The split() method of String class can be used to extract a substring from a sentence. It accepts arguments in the form of a regular expression. + +TestSubstring2.java +import java.util.*; + +public class TestSubstring2 +{ + /* Driver Code */ + public static void main(String args[]) + { + String text= new String(""Hello, My name is Sachin""); + /* Splits the sentence by the delimeter passed as an argument */ + String[] sentences = text.split(""\\.""); + System.out.println(Arrays.toString(sentences)); + } +} + +Output: +[Hello, My name is Sachin] + +In the above program, we have used the split() method. It accepts an argument \\. that checks a in the sentence and splits the string into another string. It is stored in an array of String objects sentences. + + " +What are Java String Class Methods?,"The java.lang.String class provides a lot of built-in methods that are used to manipulate string in Java. By the help of these methods, we can perform operations on String objects such as trimming, concatenating, converting, comparing, replacing strings etc. + + +Java String is a powerful concept because everything is treated as a String if you submit any form in window based, web based or mobile application. + + + + " +Can you provide example of Java String toUpperCase() and toLowerCase() method?,"The Java String toUpperCase() method converts this String into uppercase letter and String toLowerCase() method into lowercase letter. + +Stringoperation1.java + +public class Stringoperation1 +{ +public static void main(String ar[]) +{ +String s=""Sachin""; +System.out.println(s.toUpperCase());//SACHIN +System.out.println(s.toLowerCase());//sachin +System.out.println(s);//Sachin(no change in original) +} +} + +Output: + +SACHIN +sachin +Sachin + + + " +Can you provide example of Java String trim() method?,"The String class trim() method eliminates white spaces before and after the String +. +Stringoperation2.java +public class Stringoperation2 +{ +public static void main(String ar[]) +{ +String s="" Sachin ""; +System.out.println(s);// Sachin +System.out.println(s.trim());//Sachin +} +} + +Output: +Sachin +Sachin + + " +Can you provide an example of Java String startsWith() and endsWith() method?,"The method startsWith() checks whether the String starts with the letters passed as arguments and endsWith() method checks whether the String ends with the letters passed as arguments. + +Stringoperation3.java +public class Stringoperation3 +{ +public static void main(String ar[]) +{ +String s=""Sachin""; + System.out.println(s.startsWith(""Sa""));//true + System.out.println(s.endsWith(""n""));//true +} +} + +Output: +true +true + + + +" +Can you provide an example of Java String charAt() Method?,"The String class charAt() method returns a character at specified index. + +Stringoperation4.java +public class Stringoperation4 +{ +public static void main(String ar[]) +{ +String s=""Sachin""; +System.out.println(s.charAt(0));//S +System.out.println(s.charAt(3));//h +} +} + +Output: +S +h + + + " +Can you provide an example of Java String length() Method?,"The String class length() method returns length of the specified String. + +Stringoperation5.java +public class Stringoperation5 +{ +public static void main(String ar[]) +{ +String s=""Sachin""; +System.out.println(s.length());//6 +} +} + +Output: +6 + + " +Can you provide an example of Java String intern() Method?,"A pool of strings, initially empty, is maintained privately by the class String. +When the intern method is invoked, if the pool already contains a String equal to this String object as determined by the equals(Object) method, then the String from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. + +Stringoperation6.java +public class Stringoperation6 +{ +public static void main(String ar[]) +{ +String s=new String(""Sachin""); +String s2=s.intern(); +System.out.println(s2);//Sachin +} +} + +Output: +Sachin + + + +" +Can you provide an example of Java String valueOf() Method?,"The String class valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into String. + +Stringoperation7.java +public class Stringoperation7 +{ +public static void main(String ar[]) +{ +int a=10; +String s=String.valueOf(a); +System.out.println(s+10); +} +} + +Output: +1010 + + +" +Can you provide an example of Java String replace() Method?,"The String class replace() method replaces all occurrence of first sequence of character with second sequence of character. + +Stringoperation8.java +public class Stringoperation8 +{ +public static void main(String ar[]) +{ +String s1=""Java is a programming language. Java is a platform. Java is an Island.""; +String replaceString=s1.replace(""Java"",""Kava"");//replaces all occurrences of ""Java"" to ""Kava"" +System.out.println(replaceString); +} +} + +Output: +Kava is a programming language. Kava is a platform. Kava is an Island. + + " +What is Java StringBuffer Class?,"Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the same as String class except it is mutable i.e. it can be changed. + +Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order. + + + +" +What is Important Constructors of StringBuffer Class?,"Important Constructors of StringBuffer Class +Constructor: StringBuffer() +Description: It creates an empty String buffer with the initial capacity of 16. + + +Constructor: StringBuffer(String str) +Description: It creates a String buffer with the specified string. + + +Constructor: StringBuffer(int capacity) +Description: It creates an empty String buffer with the specified capacity as length. " +What are the Important methods of StringBuffer class?,"Important methods of StringBuffer class +Modifier and Type: public synchronized StringBuffer +Method: append(String s) +Description: It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. + +Modifier and Type: public synchronized StringBuffer +Method: insert(int offset, String s) +Description: It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. + +Modifier and Type: public synchronized StringBuffer +Method: replace(int startIndex, int endIndex, String str) +Description: It is used to replace the string from specified startIndex and endIndex. + +Modifier and Type: public synchronized StringBuffer +Method: delete(int startIndex, int endIndex) +Description: It is used to delete the string from specified startIndex and endIndex. + +Modifier and Type: public synchronized StringBuffer +Method: reverse() +Description: is used to reverse the string. + +Modifier and Type: public int +Method: capacity() +Description: It is used to return the current capacity. + +Modifier and Type: public void +Method: ensureCapacity(int minimumCapacity) +Description: It is used to ensure the capacity at least equal to the given minimum. + +Modifier and Type: public char +Method: charAt(int index) +Description: It is used to return the character at the specified position. + +Modifier and Type: public int +Method: length() +Description: It is used to return the length of the string i.e. total number of characters. + +Modifier and Type: public String +Method: substring(int beginIndex) +Description: It is used to return the substring from the specified beginIndex. + +Modifier and Type: public String +Method: substring(int beginIndex, int endIndex) +Description: It is used to return the substring from the specified beginIndex and endIndex. " +What is a mutable String?,"A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are used for creating mutable strings. + " +Can you provide an example of StringBuffer Class append() Method?,"The append() method concatenates the given argument with this String. + +StringBufferExample.java +class StringBufferExample{ +public static void main(String args[]){ +StringBuffer sb=new StringBuffer(""Hello ""); +sb.append(""Java"");//now original string is changed +System.out.println(sb);//prints Hello Java +} +} + +Output: +Hello Java + + " +Can you provide an example of StringBuffer insert() Method?,"The insert() method inserts the given String with this string at the given position. + +StringBufferExample2.java +class StringBufferExample2{ +public static void main(String args[]){ +StringBuffer sb=new StringBuffer(""Hello ""); +sb.insert(1,""Java"");//now original string is changed +System.out.println(sb);//prints HJavaello +} +} + + +Output: +HJavaello + + " +Can you provide an example of StringBuffer replace() Method?,"The replace() method replaces the given String from the specified beginIndex and endIndex. + +StringBufferExample3.java +class StringBufferExample3{ +public static void main(String args[]){ +StringBuffer sb=new StringBuffer(""Hello""); +sb.replace(1,3,""Java""); +System.out.println(sb);//prints HJavalo +} +} + +Output: +HJavalo + + " +Can you provide an example of StringBuffer delete() Method?,"The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex. + +StringBufferExample4.java +class StringBufferExample4{ +public static void main(String args[]){ +StringBuffer sb=new StringBuffer(""Hello""); +sb.delete(1,3); +System.out.println(sb);//prints Hlo +} +} + +Output: +Hlo + + " +Can you provide an example of StringBuffer reverse() Method?,"The reverse() method of the StringBuilder class reverses the current String. + +StringBufferExample5.java +class StringBufferExample5{ +public static void main(String args[]){ +StringBuffer sb=new StringBuffer(""Hello""); +sb.reverse(); +System.out.println(sb);//prints olleH +} +} + +Output: +olleH + + " +Can you provide an example of StringBuffer capacity() Method?,"The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. + +StringBufferExample6.java +class StringBufferExample6{ +public static void main(String args[]){ +StringBuffer sb=new StringBuffer(); +System.out.println(sb.capacity());//default 16 +sb.append(""Hello""); +System.out.println(sb.capacity());//now 16 +sb.append(""java is my favourite language""); +System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 +} +} + +Output: +16 +16 +34 + + " +Can you provide an example of StringBuffer ensureCapacity() method?,"The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. + +StringBufferExample7.java +class StringBufferExample7{ +public static void main(String args[]){ +StringBuffer sb=new StringBuffer(); +System.out.println(sb.capacity());//default 16 +sb.append(""Hello""); +System.out.println(sb.capacity());//now 16 +sb.append(""java is my favourite language""); +System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 +sb.ensureCapacity(10);//now no change +System.out.println(sb.capacity());//now 34 +sb.ensureCapacity(50);//now (34*2)+2 +System.out.println(sb.capacity());//now 70 +} +} + +Output: +16 +16 +34 +34 +70 + + +" +What is Java StringBuilder Class?,"Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5. + " +What are Important Constructors of StringBuilder class?,"Constructor: + +StringBuilder() +Description: It creates an empty String Builder with the initial capacity of 16. + +StringBuilder(String str) +Description: It creates a String Builder with the specified string. + +StringBuilder(int length) +Description: It creates an empty String Builder with the specified capacity as length. + +" +What are the Important methods of StringBuilder class?,"Method + +public StringBuilder append(String s) +Description: It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. + +public StringBuilder insert(int offset, String s) +Description: It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. + +public StringBuilder replace(int startIndex, int endIndex, String str) +Description: It is used to replace the string from specified startIndex and endIndex. + +public StringBuilder delete(int startIndex, int endIndex) +Description: It is used to delete the string from specified startIndex and endIndex. + +public StringBuilder reverse() +Description: It is used to reverse the string. + +public int capacity() +Description: It is used to return the current capacity. + +public void ensureCapacity(int minimumCapacity) +Description:It is used to ensure the capacity at least equal to the given minimum. + +public char charAt(int index) +Description:It is used to return the character at the specified position. + +public int length() +Description:It is used to return the length of the string i.e. total number of characters. + + +public String substring(int beginIndex) +Description:It is used to return the substring from the specified beginIndex. + +public String substring(int beginIndex, int endIndex) +Description:It is used to return the substring from the specified beginIndex and endIndex. +" +Can you provide an example of Java StringBuilder Examples?,"Let's see the examples of different methods of StringBuilder class. +1) StringBuilder append() method + +The StringBuilder append() method concatenates the given argument with this String. + +StringBuilderExample.java +class StringBuilderExample{ +public static void main(String args[]){ +StringBuilder sb=new StringBuilder(""Hello ""); +sb.append(""Java"");//now original string is changed +System.out.println(sb);//prints Hello Java +} +} + +Output: +Hello Java +2) StringBuilder insert() method + +The StringBuilder insert() method inserts the given string with this string at the given position. + +StringBuilderExample2.java +class StringBuilderExample2{ +public static void main(String args[]){ +StringBuilder sb=new StringBuilder(""Hello ""); +sb.insert(1,""Java"");//now original string is changed +System.out.println(sb);//prints HJavaello +} +} + +Output: +HJavaello +3) StringBuilder replace() method + +The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex. + +StringBuilderExample3.java +class StringBuilderExample3{ +public static void main(String args[]){ +StringBuilder sb=new StringBuilder(""Hello""); +sb.replace(1,3,""Java""); +System.out.println(sb);//prints HJavalo +} +} + +Output: +HJavalo +4) StringBuilder delete() method + +The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex. + +StringBuilderExample4.java +class StringBuilderExample4{ +public static void main(String args[]){ +StringBuilder sb=new StringBuilder(""Hello""); +sb.delete(1,3); +System.out.println(sb);//prints Hlo +} +} + +Output: +Hlo +5) StringBuilder reverse() method + +The reverse() method of StringBuilder class reverses the current string. + +StringBuilderExample5.java +class StringBuilderExample5{ +public static void main(String args[]){ +StringBuilder sb=new StringBuilder(""Hello""); +sb.reverse(); +System.out.println(sb);//prints olleH +} +} + +Output: +olleH +6) StringBuilder capacity() method + +The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. + +StringBuilderExample6.java +class StringBuilderExample6{ +public static void main(String args[]){ +StringBuilder sb=new StringBuilder(); +System.out.println(sb.capacity());//default 16 +sb.append(""Hello""); +System.out.println(sb.capacity());//now 16 +sb.append(""Java is my favourite language""); +System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 +} +} + +Output: +16 +16 +34 +7) StringBuilder ensureCapacity() method + +The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. + +StringBuilderExample7.java +class StringBuilderExample7{ +public static void main(String args[]){ +StringBuilder sb=new StringBuilder(); +System.out.println(sb.capacity());//default 16 +sb.append(""Hello""); +System.out.println(sb.capacity());//now 16 +sb.append(""Java is my favourite language""); +System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 +sb.ensureCapacity(10);//now no change +System.out.println(sb.capacity());//now 34 +sb.ensureCapacity(50);//now (34*2)+2 +System.out.println(sb.capacity());//now 70 +} +} + +Output: +16 +16 +34 +34 +70 + " +What are the Difference of String between StringBuffer?,"There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below: + +1) The String class is immutable while the StringBuffer class is mutable. +2) String is slow and consumes more memory when we concatenate too many strings because every time it creates new instance while StringBuffer is fast and consumes less memory when we concatenate t strings. +3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method while StringBuffer class doesn't override the equals() method of Object class +4) String class is slower while performing concatenation operation while StringBuffer class is faster while performing concatenation operation. +5) String class uses String constant pool while StringBuffer uses Heap memory. + + " +Can you provide an example of Performance Test of String and StringBuffer?,"ConcatTest.java + +public class ConcatTest{ + public static String concatWithString() { + String t = ""Java""; + for (int i=0; i<10000; i++){ + t = t + ""Tpoint""; + } + return t; + } + public static String concatWithStringBuffer(){ + StringBuffer sb = new StringBuffer(""Java""); + for (int i=0; i<10000; i++){ + sb.append(""Tpoint""); + } + return sb.toString(); + } + public static void main(String[] args){ + long startTime = System.currentTimeMillis(); + concatWithString(); + System.out.println(""Time taken by Concating with String: ""+(System.currentTimeMillis()-startTime)+""ms""); + startTime = System.currentTimeMillis(); + concatWithStringBuffer(); + System.out.println(""Time taken by Concating with StringBuffer: ""+(System.currentTimeMillis()-startTime)+""ms""); + } +} + +Output: +Time taken by Concating with String: 578ms +Time taken by Concating with StringBuffer: 0ms + + + " +Can you providean example of String and StringBuffer HashCode Test?,"As we can see in the program given below, String returns new hashcode while performing concatenation but the StringBuffer class returns same hashcode. + +InstanceTest.java +public class InstanceTest{ + public static void main(String args[]){ + System.out.println(""Hashcode test of String:""); + String str=""java""; + System.out.println(str.hashCode()); + str=str+""tpoint""; + System.out.println(str.hashCode()); + + System.out.println(""Hashcode test of StringBuffer:""); + StringBuffer sb=new StringBuffer(""java""); + System.out.println(sb.hashCode()); + sb.append(""tpoint""); + System.out.println(sb.hashCode()); + } +} + +Output: +Hashcode test of String: +3254818 +229541438 +Hashcode test of StringBuffer: +118352462 +118352462 + + " +What are the Difference between StringBuffer and StringBuilder?,"Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since JDK 1.5. + +A list of differences between StringBuffer and StringBuilder is given below: +1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously while StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. +2) StringBuffer is less efficient than StringBuilder while StringBuilder is more efficient than StringBuffer. +3) StringBuffer was introduced in Java 1.0 while StringBuilder was introduced in Java 1.5 + + +" +Can you provide StringBuffer Example?,"BufferTest.java +//Java Program to demonstrate the use of StringBuffer class. +public class BufferTest{ + public static void main(String[] args){ + StringBuffer buffer=new StringBuffer(""hello""); + buffer.append(""java""); + System.out.println(buffer); + } +} + +Output: +hellojava + + " +Can you provide StringBuilder Example?,"BuilderTest.java +//Java Program to demonstrate the use of StringBuilder class. +public class BuilderTest{ + public static void main(String[] args){ + StringBuilder builder=new StringBuilder(""hello""); + builder.append(""java""); + System.out.println(builder); + } +} + +Output: +hellojava + + " +Can you provide Performance Test of StringBuffer and StringBuilder?,"Let's see the code to check the performance of StringBuffer and StringBuilder classes. + +ConcatTest.java +//Java Program to demonstrate the performance of StringBuffer and StringBuilder classes. +public class ConcatTest{ + public static void main(String[] args){ + long startTime = System.currentTimeMillis(); + StringBuffer sb = new StringBuffer(""Java""); + for (int i=0; i<10000; i++){ + sb.append(""Tpoint""); + } + System.out.println(""Time taken by StringBuffer: "" + (System.currentTimeMillis() - startTime) + ""ms""); + startTime = System.currentTimeMillis(); + StringBuilder sb2 = new StringBuilder(""Java""); + for (int i=0; i<10000; i++){ + sb2.append(""Tpoint""); + } + System.out.println(""Time taken by StringBuilder: "" + (System.currentTimeMillis() - startTime) + ""ms""); + } +} + +Output: +Time taken by StringBuffer: 16ms +Time taken by StringBuilder: 0ms + + " +How to create Immutable class?,"There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members + " +Can you provide Example to create Immutable class?,"In this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method. + +ImmutableDemo.java +public final class Employee +{ +final String pancardNumber; +public Employee(String pancardNumber) +{ +this.pancardNumber=pancardNumber; +} +public String getPancardNumber(){ +return pancardNumber; +} +} +public class ImmutableDemo +{ +public static void main(String ar[]) +{ +Employee e = new Employee(""ABC123""); +String s1 = e.getPancardNumber(); +System.out.println(""Pancard Number: "" + s1); +} +} + +Output: +Pancard Number: ABC123 + + +The above class is immutable because: +-The instance variable of the class is final i.e. we cannot change the value of it after creating an object. +-The class is final so we cannot create the subclass. +-There is no setter methods i.e. we have no option to change the value of the instance variable. + +These points makes this class as immutable. + + +" +What is Java toString() Method?,"If you want to represent any object as a string, toString() method comes into existence. + +The toString() method returns the String representation of the object. + +If you print any object, Java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depending on your implementation. + + " +What is the Advantage of Java toString() method?,"By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code. + " +Can you provide an example of Understanding problem without toString() method?,"Let's see the simple code that prints reference. + +Student.java +class Student{ + int rollno; + String name; + String city; + + Student(int rollno, String name, String city){ + this.rollno=rollno; + this.name=name; + this.city=city; + } + + public static void main(String args[]){ + Student s1=new Student(101,""Raj"",""lucknow""); + Student s2=new Student(102,""Vijay"",""ghaziabad""); + + System.out.println(s1);//compiler writes here s1.toString() + System.out.println(s2);//compiler writes here s2.toString() + } +} + +Output: +Student@1fee6fc +Student@1eed786 + + +As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since Java compiler internally calls toString() method, overriding this method will return the specified values. + + " +Can you provide an Example of Java toString() method?,"Let's see an example of toString() method. + +Student.java +class Student{ + int rollno; + String name; + String city; + + Student(int rollno, String name, String city){ + this.rollno=rollno; + this.name=name; + this.city=city; + } + + public String toString(){//overriding the toString() method + return rollno+"" ""+name+"" ""+city; + } + public static void main(String args[]){ + Student s1=new Student(101,""Raj"",""lucknow""); + Student s2=new Student(102,""Vijay"",""ghaziabad""); + + System.out.println(s1);//compiler writes here s1.toString() + System.out.println(s2);//compiler writes here s2.toString() + } +} + +Output: +101 Raj lucknow +102 Vijay ghaziabad + + +In the above program, Java compiler internally calls toString() method, overriding this method will return the specified values of s1 and s2 objects of Student class. + + " +What is StringTokenizer in Java?,"The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a String. It is a legacy class of Java. + +It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter. + +In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens. + +Example of String Tokenizer class in Java + +Input: +Hello welcome to JavaTpoint -> String Tokenizer -> Tokens -> “hello”,”welcome”,”to”, “JavaTpoint” +" +What are the Constructors of the StringTokenizer Class?,"There are 3 constructors defined in the StringTokenizer class. + +Constructor + +StringTokenizer(String str) +Description: It creates StringTokenizer with specified string. + +StringTokenizer(String str, String delim) +Description: It creates StringTokenizer with specified string and delimiter. + +StringTokenizer(String str, String delim, boolean returnValue) +Description:It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens. " +What are the Methods of the StringTokenizer Class?,"The six useful methods of the StringTokenizer class are as follows: + +boolean hasMoreTokens() +Description: It checks if there is more tokens available. + +String nextToken() +Description: It returns the next token from the StringTokenizer object. + +String nextToken(String delim) +Description: It returns the next token based on the delimiter. + +boolean hasMoreElements() +Description: It is the same as hasMoreTokens() method. + +Object nextElement() +Description: It is the same as nextToken() but its return type is Object. + +int countTokens() +Description: It returns the total number of tokens. " +Can you provide an Example of StringTokenizer Class?,"Let's see an example of the StringTokenizer class that tokenizes a string ""my name is khan"" on the basis of whitespace. + +Simple.java +import java.util.StringTokenizer; +public class Simple{ + public static void main(String args[]){ + StringTokenizer st = new StringTokenizer(""my name is khan"","" ""); + while (st.hasMoreTokens()) { + System.out.println(st.nextToken()); + } + } +} + +Output: +my +name +is +khan + +The above Java code, demonstrates the use of StringTokenizer class and its methods hasMoreTokens() and nextToken(). + +" +Can you provide an Example of nextToken(String delim) method of the StringTokenizer class?,"Test.java +import java.util.*; + +public class Test { + public static void main(String[] args) { + StringTokenizer st = new StringTokenizer(""my,name,is,khan""); + + // printing next token + System.out.println(""Next token is : "" + st.nextToken("","")); + } +} + +Output: +Next token is : my + + " +Can you provide an Example of hasMoreTokens() method of the StringTokenizer class?,"This method returns true if more tokens are available in the tokenizer String otherwise returns false. + +StringTokenizer1.java +import java.util.StringTokenizer; +public class StringTokenizer1 +{ + /* Driver Code */ + public static void main(String args[]) + { + /* StringTokenizer object */ + StringTokenizer st = new StringTokenizer(""Demonstrating methods from StringTokenizer class"","" ""); + /* Checks if the String has any more tokens */ + while (st.hasMoreTokens()) + { + System.out.println(st.nextToken()); + } + } +} + +Output: +Demonstrating +methods +from +StringTokenizer +class + + +The above Java program shows the use of two methods hasMoreTokens() and nextToken() of StringTokenizer class. + + " +Can you provide an Example of hasMoreElements() method of the StringTokenizer class?,"This method returns the same value as hasMoreTokens() method of StringTokenizer class. The only difference is this class can implement the Enumeration interface. + +StringTokenizer2.java +import java.util.StringTokenizer; +public class StringTokenizer2 +{ + public static void main(String args[]) + { + StringTokenizer st = new StringTokenizer(""Hello everyone I am a Java developer"","" ""); + while (st.hasMoreElements()) + { + System.out.println(st.nextToken()); + } + } +} + +Output: +Hello +everyone +I +am +a +Java +developer + +The above code demonstrates the use of hasMoreElements() method. + + +" +Could you provide an Example of nextElement() method of the StringTokenizer class?,"nextElement() returns the next token object in the tokenizer String. It can implement Enumeration interface. + +StringTokenizer3.java +import java.util.StringTokenizer; +public class StringTokenizer3 +{ + /* Driver Code */ + public static void main(String args[]) + { + /* StringTokenizer object */ + StringTokenizer st = new StringTokenizer(""Hello Everyone Have a nice day"","" ""); + /* Checks if the String has any more tokens */ + while (st.hasMoreTokens()) + { + /* Prints the elements from the String */ + System.out.println(st.nextElement()); + } + } +} + +Output: +Hello +Everyone +Have +a +nice +day + +The above code demonstrates the use of nextElement() method. + + " +Could you provide an Example of countTokens() method of the StringTokenizer class?,"This method calculates the number of tokens present in the tokenizer String. + +StringTokenizer4.java +import java.util.StringTokenizer; +public class StringTokenizer3 +{ + /* Driver Code */ + public static void main(String args[]) + { + /* StringTokenizer object */ + StringTokenizer st = new StringTokenizer(""Hello Everyone Have a nice day"","" ""); + /* Prints the number of tokens present in the String */ + System.out.println(""Total number of Tokens: ""+st.countTokens()); + } +} + +Output: +Total number of Tokens: 6 + + +The above Java code demonstrates the countTokens() method of StringTokenizer() class. + + +" +How many objects will be created in the following code?,"String s1=""javatpoint""; +String s2=""javatpoint""; + +Answer: Only one. + + +" +What is the difference between equals() method and == operator?,"The equals() method matches content of the strings whereas == operator matches object or reference of the strings. + " +What is Java String charAt()?," +The Java String class charAt() method returns a char value at the given index number. + +The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number. + +Syntax + +public char charAt(int index) + +The method accepts index as a parameter. The starting index is 0. It returns a character at a specific index position in a string. It throws StringIndexOutOfBoundsException if the index is a negative value or greater than this string length. + +Specified by + +CharSequence interface, located inside java.lang package. +Internal implementation +public char charAt(int index) { + if ((index < 0) || (index >= value.length)) { + throw new StringIndexOutOfBoundsException(index); + } + return value[index]; + } + + +" +Can you provide an example of Java String charAt() Method?,"Let's see Java program related to string in which we will use charAt() method that perform some operation on the give string. +FileName: CharAtExample.java +public class CharAtExample{ +public static void main(String args[]){ +String name=""javatpoint""; +char ch=name.charAt(4);//returns the char value at the 4th index +System.out.println(ch); +}} + +Output: +t + + +Let's see the example of the charAt() method where we are passing a greater index value. In such a case, it throws StringIndexOutOfBoundsException at run time. + +FileName: CharAtExample.java +public class CharAtExample{ +public static void main(String args[]){ +String name=""javatpoint""; +char ch=name.charAt(10);//returns the char value at the 10th index +System.out.println(ch); +}} + +Output: +Exception in thread ""main"" java.lang.StringIndexOutOfBoundsException: +String index out of range: 10 +at java.lang.String.charAt(String.java:658) +at CharAtExample.main(CharAtExample.java:4) + + +" +Can you provide an example of Accessing First and Last Character by Using the charAt() Method?,"Let's see a simple example where we are accessing first and last character from the provided string. + +FileName: CharAtExample3.java +public class CharAtExample3 { + public static void main(String[] args) { + String str = ""Welcome to Javatpoint portal""; + int strLength = str.length(); + // Fetching first character + System.out.println(""Character at 0 index is: ""+ str.charAt(0)); + // The last Character is present at the string length-1 index + System.out.println(""Character at last index is: ""+ str.charAt(strLength-1)); + } +} + +Output: +Character at 0 index is: W +Character at last index is: l + + " +Can you provide an example of Print Characters Presented at Odd Positions by Using the charAt() Method?,"Let's see an example where we are accessing all the elements present at odd index. + +FileName: CharAtExample4.java +public class CharAtExample4 { + public static void main(String[] args) { + String str = ""Welcome to Javatpoint portal""; + for (int i=0; i<=str.length()-1; i++) { + if(i%2!=0) { + System.out.println(""Char at ""+i+"" place ""+str.charAt(i)); + } + } + } +} + +Output: +Char at 1 place e +Char at 3 place c +Char at 5 place m +Char at 7 place +Char at 9 place o +Char at 11 place J +Char at 13 place v +Char at 15 place t +Char at 17 place o +Char at 19 place n +Char at 21 place +Char at 23 place o +Char at 25 place t +Char at 27 place l + + +The position such as 7 and 21 denotes the space. + + " +Could you provide an example ofCounting Frequency of a character in a String by Using the charAt() Method?,"Let's see an example in which we are counting frequency of a character in the given string. + +FileName: CharAtExample5.java +public class CharAtExample5 { + public static void main(String[] args) { + String str = ""Welcome to Javatpoint portal""; + int count = 0; + for (int i=0; i<=str.length()-1; i++) { + if(str.charAt(i) == 't') { + count++; + } + } + System.out.println(""Frequency of t is: ""+count); + } +} + +Output: +Frequency of t is: 4 + + " +Could you provide an example of Counting the Number of Vowels in a String by Using the chatAt() Method?,"Let's see an example where we are counting the number of vowels present in a string with the help of the charAt() method. + +FileName: CharAtExample6.java +// import statement +import java.util.*; + +public class CharAtExample6 +{ +ArrayList al; + +// constructor for creating and +// assigning values to the ArrayList al +CharAtExample6() +{ +al = new ArrayList(); +al.add('A'); al.add('E'); +al.add('a'); al.add('e'); +al.add('I'); al.add('O'); +al.add('i'); al.add('o'); +al.add('U'); al.add('u'); +} + +// a method that checks whether the character c is a vowel or not +private boolean isVowel(char c) +{ +for(int i = 0; i < al.size(); i++) +{ +if(c == al.get(i)) +{ +return true; +} +} +return false; +} +// a method that calculates vowels in the String s +public int countVowels(String s) +{ +int countVowel = 0; // store total number of vowels +int size = s.length(); // size of string +for(int j = 0; j < size; j++) +{ +char c = s.charAt(j); +if(isVowel(c)) +{ +// vowel found! +// increase the count by 1 +countVowel = countVowel + 1; +} +} + +return countVowel; +} + +// main method +public static void main(String argvs[]) +{ +// creating an object of the class CharAtExample6 +CharAtExample6 obj = new CharAtExample6(); + +String str = ""Javatpoint is a great site for learning Java.""; + +int noOfVowel = obj.countVowels(str); + +System.out.println(""String: "" + str); + +System.out.println(""Total number of vowels in the string are: ""+ noOfVowel + ""\n""); + +str = ""One apple in a day keeps doctor away.""; + +System.out.println(""String: "" + str); + +noOfVowel = obj.countVowels(str); + +System.out.println(""Total number of vowels in the string are: ""+ noOfVowel); +} +} + +Output: +String: Javatpoint is a great site for learning Java. +Total number of vowels in the string are: 16 + +String: One apple in a day keeps doctor away. +Total number of vowels in the string are: 13 + + " +What is Java String compareTo()?,"The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0. + +It compares strings on the basis of the Unicode value of each character in the strings. + +If the first string is lexicographically greater than the second string, it returns a positive number (difference of character value). If the first string is less than the second string lexicographically, it returns a negative number, and if the first string is lexicographically equal to the second string, it returns 0. + +if s1 > s2, it returns positive number +if s1 < s2, it returns negative number +if s1 == s2, it returns 0 + +Syntax +public int compareTo(String anotherString) + +The method accepts a parameter of type String that is to be compared with the current string. + +It returns an integer value. It throws the following two exceptions: +ClassCastException: If this object cannot get compared with the specified object. +NullPointerException: If the specified object is null. + +Internal implementation +int compareTo(String anotherString) { + int length1 = value.length; + int length2 = anotherString.value.length; + int limit = Math.min(length1, length2); + char v1[] = value; + char v2[] = anotherString.value; + + int i = 0; + while (i < limit) { + char ch1 = v1[i]; + char ch2 = v2[i]; + if (ch1 != ch2) { + return ch1 - ch2; + } + i++; + } + return length1 - length2; +} + + " +Could you provide Java String compareTo() Method Example?,"FileName: CompareToExample.java + +public class CompareToExample{ +public static void main(String args[]){ +String s1=""hello""; +String s2=""hello""; +String s3=""meklo""; +String s4=""hemlo""; +String s5=""flag""; +System.out.println(s1.compareTo(s2));//0 because both are equal +System.out.println(s1.compareTo(s3));//-5 because ""h"" is 5 times lower than ""m"" +System.out.println(s1.compareTo(s4));//-1 because ""l"" is 1 times lower than ""m"" +System.out.println(s1.compareTo(s5));//2 because ""h"" is 2 times greater than ""f"" +}} + +Output: +0 +-5 +-1 +2 + + + " +Can you provide an example of Java String compareTo(): empty string?,"When we compare two strings in which either first or second string is empty, the method returns the length of the string. So, there may be two scenarios: + +-If first string is an empty string, the method returns a negative +-If second string is an empty string, the method returns a positive number that is the length of the first string. + +FileName: CompareToExample2.java +public class CompareToExample2{ +public static void main(String args[]){ +String s1=""hello""; +String s2=""""; +String s3=""me""; +System.out.println(s1.compareTo(s2)); +System.out.println(s2.compareTo(s3)); +}} + +Output: +5 +-2 + + + +" +Could you provide an example of Java String compareTo(): case sensitive?,"To check whether the compareTo() method considers the case sensitiveness of characters or not, we will make the comparison between two strings that contain the same letters in the same sequence. + +Suppose, a string having letters in uppercase, and the second string having the letters in lowercase. On comparing these two string, if the outcome is 0, then the compareTo() method does not consider the case sensitiveness of characters; otherwise, the method considers the case sensitiveness of characters. + +FileName: CompareToExample3.java +public class CompareToExample3 +{ +// main method +public static void main(String argvs[]) +{ + +// input string in uppercase +String st1 = new String(""INDIA IS MY COUNTRY""); + +// input string in lowercase +String st2 = new String(""india is my country""); + +System.out.println(st1.compareTo(st2)); +} +} + +Output: +-32 + + +Conclusion: It is obvious by looking at the output that the outcome is not equal to zero. Hence, the compareTo() method takes care of the case sensitiveness of characters. + + +" +Could you provide an example of Java String compareTo(): ClassCastException?,"The ClassCastException is thrown when objects of incompatible types get compared. In the following example, we are comparing an object of the ArrayList (al) with a string literal (""Sehwag""). + +FileName: CompareToExample4.java +// import statement +import java.util.*; + +class Players +{ + +private String name; + +// constructor of the class +public Players(String str) +{ +name = str; +} + +} + +public class CompareToExample4 +{ + +// main method +public static void main(String[] args) +{ + +Players ronaldo = new Players(""Ronaldo""); +Players sachin = new Players(""Sachin""); +Players messi = new Players(""Messi""); +ArrayList al = new ArrayList<>(); + +al.add(ronaldo); +al.add(sachin); +al.add(messi); + +// performing binary search on the list al +Collections.binarySearch(al, ""Sehwag"", null); +} + +} + +Output: +Exception in thread ""main"" java.lang.ClassCastException: class Players cannot be cast to class java.lang.Comparable + + " +Could you provide an example of Java String compareTo(): NullPointerException?,"The NullPointerException is thrown when a null object invokes the compareTo() method. Observe the following example. + +FileName: CompareToExample5.java +public class CompareToExample5 +{ +// main method +public static void main(String[] args) +{ + +String str = null; + +// null is invoking the compareTo method. Hence, the NullPointerException +// will be raised +int no = str.compareTo(""India is my country.""); + +System.out.println(no); +} +} + +Output: +Exception in thread ""main"" java.lang.NullPointerException + at CompareToExample5.main(CompareToExample5.java:9) + + " +What is Java String concat?,"The Java String class concat() method combines specified string at the end of this string. It returns a combined string. It is like appending another string. + +Signature +The signature of the string concat() method is given below: + +public String concat(String anotherString) +Parameter +anotherString : another string i.e., to be combined at the end of this string. + +Returns +combined string + +Internal implementation +public String concat(String str) { + int otherLen = str.length(); + if (otherLen == 0) { + return this; + } + int len = value.length; + char buf[] = Arrays.copyOf(value, len + otherLen); + str.getChars(buf, len); + return new String(buf, true); + } " +Could you provide an example of Java String concat() method example?,"FileName: ConcatExample.java + +public class ConcatExample{ +public static void main(String args[]){ +String s1=""java string""; +// The string s1 does not get changed, even though it is invoking the method +// concat(), as it is immutable. Therefore, the explicit assignment is required here. +s1.concat(""is immutable""); +System.out.println(s1); +s1=s1.concat("" is immutable so assign it explicitly""); +System.out.println(s1); +}} +Output: + +java string +java string is immutable so assign it explicitly" +What is Java String contains()?,"The Java String class contains() method searches the sequence of characters in this string. It returns true if the sequence of char values is found in this string otherwise returns false. +Signature +The signature of string contains() method is given below: +public boolean contains(CharSequence sequence) +Parameter + +sequence : specifies the sequence of characters to be searched. +Returns + +true if the sequence of char value exists, otherwise false. +Exception + +NullPointerException : if the sequence is null. + +Internal implementation + +public boolean contains(CharSequence s) { + return indexOf(s.toString()) > -1; + } + + +Here, the conversion of CharSequence takes place into String. After that, the indexOf() method is invoked. The method indexOf() either returns 0 or a number greater than 0 in case the searched string is found. +However, when the searched string is not found, the indexOf() method returns -1. Therefore, after execution, the contains() method returns true when the indexOf() method returns a non-negative value (when the searched string is found); otherwise, the method returns false. + + " +can you provide an example of Java String contains() Method Example?,"FileName: ContainsExample.java + +class ContainsExample{ +public static void main(String args[]){ +String name=""what do you know about me""; +System.out.println(name.contains(""do you know"")); +System.out.println(name.contains(""about"")); +System.out.println(name.contains(""hello"")); +}} + +Output: +true +true +false + + + +" +What are the Limitations of the Contains() method?,"Following are some limitations of the contains() method: + +-The contains() method should not be used to search for a character in a string. Doing so results in an error. +-The contains() method only checks for the presence or absence of a string in another string. It never reveals at which index the searched index is found. Because of these limitations, it is better to use the indexOf() method instead of the contains() method. + + + " +What is the Java String endsWith()?,"The Java String class endsWith() method checks if this string ends with a given suffix. It returns true if this string ends with the given suffix; else returns false. + +Signature +The syntax or signature of endsWith() method is given below. +public boolean endsWith(String suffix) + +Parameter +suffix : Sequence of character + +Returns +true or false + +Internal implementation +public boolean endsWith(String suffix) { + return startsWith(suffix, value.length - suffix.value.length); + } + +The internal implementation shows that the endWith() method is dependent on the startsWith() method of the String class. + + " +Could you provide an example of Java String endsWith() Method Example?,"FileName: EndsWithExample.java + +public class EndsWithExample{ +public static void main(String args[]){ +String s1=""java by javatpoint""; +System.out.println(s1.endsWith(""t"")); +System.out.println(s1.endsWith(""point"")); +}} + +Output: +true +true + + " +What is Java String equals()?,"The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. + +The String equals() method overrides the equals() method of the Object class. + +Signature +publicboolean equals(Object anotherObject) +Parameter +anotherObject : another object, i.e., compared with this string. +Returns +true if characters of both strings are equal otherwise false. +Internal implementation +public boolean equals(Object anObject) { + if (this == anObject) { + return true; + } + if (anObject instanceof String) { + String anotherString = (String) anObject; + int n = value.length; + if (n == anotherString.value.length) { + char v1[] = value; + char v2[] = anotherString.value; + int i = 0; + while (n-- != 0) { + if (v1[i] != v2[i]) + return false; + i++; + } + return true; + } + } + return false; + } + + " +Could you provide an example of Java String equals() Method?,"FileName: EqualsExample.java + +public class EqualsExample{ +public static void main(String args[]){ +String s1=""javatpoint""; +String s2=""javatpoint""; +String s3=""JAVATPOINT""; +String s4=""python""; +System.out.println(s1.equals(s2));//true because content and case is same +System.out.println(s1.equals(s3));//false because case is not same +System.out.println(s1.equals(s4));//false because content is not same +}} + +Output: +true +false +false + + + " +What is Java String equalsIgnoreCase()?,"The Java String class equalsIgnoreCase() method compares the two given strings on the basis of the content of the string irrespective of the case (lower and upper) of the string. It is just like the equals() method but doesn't check the case sensitivity. If any character is not matched, it returns false, else returns true. + +Signature +publicboolean equalsIgnoreCase(String str) +Parameter +str : another string i.e., compared with this string. +Returns +It returns true if characters of both strings are equal, ignoring case otherwise false. + +Internal implementation +public boolean equalsIgnoreCase(String anotherString) { + return (this == anotherString) ? true + : (anotherString != null) + && (anotherString.value.length == value.length) + && regionMatches(true, 0, anotherString, 0, value.length); + } + +It is obvious from looking at the implementation that the equalsIgnoreCase() method is invoking the regionMatches() method. It makes the equalsIgnoreCase() method case-insensitive. The signature of the regionMatches() method is mentioned below. +public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) + +The regionMatches() method parses five parameters. The first parameter ignoreCase is set to true in the above implementation. Thus, when the method is executed, it checks whether the ignoreCase flag is true or not. If yes, then one character each from both the strings is taken and then compared. If the comparison gives a false value, then both the character is converted to upper case and then checked if the comparison still gives a false value, then both the characters are converted to a lower case and then compared. If the comparison gives the true value, then both the strings have equal contents; otherwise, not. Code Snippet of the discussed comparison is mentioned below. + +while (toffset < last) +{ +char ch1 = getChar(value, toffset++); +char ch2 = getChar(other, ooffset++); +if (ch1 == ch2) +{ +continue; +} +// convert each character to uppercase and +// then make the comparison. +// If the comparison yeilds a true value, +// then next pair of characters should be scanned +char uCh1 = Character.toUpperCase(ch1); +char uCh2 = Character.toUpperCase(ch2); +if (uCh1 == u2) +{ +continue; +} + +// convert each character to lowercase and +// then make the comparison. +// If the comparison yeilds a true value, +// then next pair of characters should be scanned +// Otherwise, return false. +if (Character.toLowerCase(uCh1) == Character.toLowerCase(uCh2)) +{ +continue; +} +return false; +} + +// reaching here means the content of both the strings +// are the same after ignoring the case sensitiveness +return true; + +One may argue that if we made a comparison after converting to uppercase, then why do we need an extra comparison by converting characters to the lowercase. The reason behind this is to provide to the requirement of Georgian alphabets. Conversion in uppercase does not work properly for the Georgian alphabets, as they have some strange rules about the case conversion. Therefore, one extra comparison, by converting characters to the lowercase, is required. + + +" +Could you provide an example of Java String equalsIgnoreCase() Method?,"FileName: EqualsIgnoreCaseExample.java + +public class EqualsIgnoreCaseExample{ +public static void main(String args[]){ +String s1=""javatpoint""; +String s2=""javatpoint""; +String s3=""JAVATPOINT""; +String s4=""python""; +System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same +System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored +System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same +}} + +Output: +true +true +false + + +" +What is Java String format()?,"The java string format() method returns the formatted string by given locale, format and arguments. + +If you don't specify the locale in String.format() method, it uses default locale by calling Locale.getDefault() method. + +The format() method of java language is like sprintf() function in c language and printf() method of java language. +Internal implementation +public static String format(String format, Object... args) { + return new Formatter().format(format, args).toString(); + } + +Signature +There are two type of string format() method: +public static String format(String format, Object... args) +and, +public static String format(Locale locale, String format, Object... args) + +Parameters +locale : specifies the locale to be applied on the format() method. +format : format of the string. +args : arguments for the format string. It may be zero or more. + +Returns +formatted string + +Throws +NullPointerException : if format is null. +IllegalFormatException : if format is illegal or incompatible. + " +Could you provide an example of Java String format() method?,"public class FormatExample{ +public static void main(String args[]){ +String name=""sonoo""; +String sf1=String.format(""name is %s"",name); +String sf2=String.format(""value is %f"",32.33434); +String sf3=String.format(""value is %32.12f"",32.33434);//returns 12 char fractional part filling with 0 + +System.out.println(sf1); +System.out.println(sf2); +System.out.println(sf3); +}} + +name is sonoo +value is 32.334340 +value is 32.334340000000 + + " +What is Java String Format Specifiers?,"Here, we are providing a table of format specifiers supported by the Java String. + +Format Specifier: %a +Data Type: floating point (except BigDecimal) +Output: Returns Hex output of floating point number. + +Format Specifier: %b +Data Type: Any type +Output: ""true"" if non-null, ""false"" if null + +Format Specifier: %c +Data Type: character +Output: Unicode character + +Format Specifier: %d +Data Type: integer (incl. byte, short, int, long, bigint) +Output: Decimal Integer + +Format Specifier: %e +Data Type: floating point +Output:Output: decimal number in scientific notation + +Format Specifier: %f +Data Type: floating point +Output: decimal number + +Format Specifier:%g +Data Type: floating point +Output: decimal number, possibly in scientific notation depending on the precision and value. + +Format Specifier: %h +Data Type: any type +Output: Hex String of value from hashCode() method. + +Format Specifier: %n +Data Type: none +Output: Platform-specific line separator. +Format Specifier: %o +Data Type: integer (incl. byte, short, int, long, bigint) +Output: Octal number + +Format Specifier:%s +Data Type: any type +Output: String value + +Format Specifier:%t +Data Type: Date/Time (incl. long, Calendar, Date and TemporalAccessor) +Output:%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below. + +Format Specifier: %x +Data Type: integer (incl. byte, short, int, long, bigint) +Output: Hex string. + " +What is Java String getBytes()?,"The Java String class getBytes() method does the encoding of string into the sequence of bytes and keeps it in an array of bytes. +Signature +There are three variants of getBytes() method. The signature or syntax of string getBytes() method is given below: + +public byte[] getBytes() +public byte[] getBytes(Charset charset) +public byte[] getBytes(String charsetName)throws UnsupportedEncodingException +Parameters +charset / charsetName - The name of a charset the method supports. +Returns +Sequence of bytes. +Exception Throws +UnsupportedEncodingException: It is thrown when the mentioned charset is not supported by the method. + +Internal implementation +public byte[] getBytes() { + return StringCoding.encode(value, 0, value.length); + } + + " +Can you provide an example of String class getBytes() Method?,"The parameterless getBytes() method encodes the string using the default charset of the platform, which is UTF - 8. The following two examples show the same. + +FileName: StringGetBytesExample.java +public class StringGetBytesExample{ +public static void main(String args[]){ +String s1=""ABCDEFG""; +byte[] barr=s1.getBytes(); +for(int i=0;i= 0) +{ +// match found. Hence, increment the count +count = count + 1; + +// start looking after the searched index +startFrom = index + 1; +} + +else +{ +// the value of index is - 1 here. Therefore, terminate the loop +break; +} + +} + +System.out.println(""In the String: ""+ str); +System.out.println(""The 'o' character has come ""+ count + "" times""); +} +} + +Output: +In the String: Welcome to JavaTpoint +The 'o' character has come 3 times + + + + +" +Can you provide an example of Java String indexOf(String substring) Method?,"The method takes substring as an argument and returns the index of the first character of the substring. + +FileName: IndexOfExample2.java +public class IndexOfExample2 { + public static void main(String[] args) { + String s1 = ""This is indexOf method""; + // Passing Substring + int index = s1.indexOf(""method""); //Returns the index of this substring + System.out.println(""index of substring ""+index); + } + +} + +Output: +index of substring 16 + + + " +"Can you provide an example of Java String indexOf(String substring, int fromIndex) Method?","The method takes substring and index as arguments and returns the index of the first character that occurs after the given fromIndex. + +FileName: IndexOfExample3.java +public class IndexOfExample3 { + public static void main(String[] args) { + String s1 = ""This is indexOf method""; + // Passing substring and index + int index = s1.indexOf(""method"", 10); //Returns the index of this substring + System.out.println(""index of substring ""+index); + index = s1.indexOf(""method"", 20); // It returns -1 if substring does not found + System.out.println(""index of substring ""+index); + } +} + +Output: +index of substring 16 +index of substring -1 + + + + " +"Can you provide an example of Java String indexOf(int char, int fromIndex) Method?","The method takes char and index as arguments and returns the index of the first character that occurs after the given fromIndex. + +FileName: IndexOfExample4.java +public class IndexOfExample4 { + public static void main(String[] args) { + String s1 = ""This is indexOf method""; + // Passing char and index from + int index = s1.indexOf('e', 12); //Returns the index of this char + System.out.println(""index of char ""+index); + } +} + +Output: +index of char 17 + + " +What is Java String intern()?,"The Java String class intern() method returns the interned string. It returns the canonical representation of string. +It can be used to return string from memory if it is created by a new keyword. It creates an exact copy of the heap string object in the String Constant Pool. +Signature +The signature of the intern() method is given below: +public String intern() +Returns +interned string + + " +What is The need and working of the String.intern() Method?,"When a string is created in Java, it occupies memory in the heap. Also, we know that the String class is immutable. Therefore, whenever we create a string using the new keyword, new memory is allocated in the heap for corresponding string, which is irrespective of the content of the array. Consider the following code snippet. + +String str = new String(""Welcome to JavaTpoint.""); +String str1 = new String(""Welcome to JavaTpoint""); +System.out.println(str1 == str); // prints false + +The println statement prints false because separate memory is allocated for each string literal. Thus, two new string objects are created in the memory i.e. str and str1. that holds different references. + +We know that creating an object is a costly operation in Java. Therefore, to save time, Java developers came up with the concept of String Constant Pool (SCP). The SCP is an area inside the heap memory. It contains the unique strings. In order to put the strings in the string pool, one needs to call the intern() method. Before creating an object in the string pool, the JVM checks whether the string is already present in the pool or not. If the string is present, its reference is returned. + +String str = new String(""Welcome to JavaTpoint"").intern(); // statement - 1 +String str1 = new String(""Welcome to JavaTpoint"").intern(); // statement - 2 +System.out.println(str1 == str); // prints true + +In the above code snippet, the intern() method is invoked on the String objects. Therefore, the memory is allocated in the SCP. For the second statement, no new string object is created as the content of str and str1 are the same. Therefore, the reference of the object created in the first statement is returned for str1. Thus, str and str1 both point to the same memory. Hence, the print statement prints true. + + + +" +Could you provide an example of Java String intern() Method Example?,"FileName: InternExample.java + +public class InternExample{ +public static void main(String args[]){ +String s1=new String(""hello""); +String s2=""hello""; +String s3=s1.intern();//returns string from pool, now it will be same as s2 +System.out.println(s1==s2);//false because reference variables are pointing to different instance +System.out.println(s2==s3);//true because reference variables are pointing to same instance +}} + +Output: +false +true + + + " +What are the Points to Remember at intern() method?,"Following are some important points to remember regarding the intern() method: +1) A string literal always invokes the intern() method, whether one mention the intern() method along with the string literal or not. For example, + +String s = ""d"".intern(); +String p = ""d""; // compiler treats it as String p = ""d"".intern(); +System.out.println(s == p); // prints true + +2) Whenever we create a String object using the new keyword, two objects are created. For example, + +String str = new (""Hello World""); + +Here, one object is created in the heap memory outside of the SCP because of the usage of the new keyword. As we have got the string literal too (""Hello World""); therefore, one object is created inside the SCP, provided the literal ""Hello World"" is already not present in the SCP. + + " +What is Java String isEmpty()?,"The Java String class isEmpty() method checks if the input string is empty or not. Note that here empty means the number of characters contained in a string is zero. +Signature +The signature or syntax of string isEmpty() method is given below: +public boolean isEmpty() +Returns +true if length is 0 otherwise false. +Since +1.6 +Internal implementation +public boolean isEmpty() { + return value.length == 0; + } + + " +Could you provide an example of Java String isEmpty() method example?,"FileName: StringIsEmptyExample.java + +public class IsEmptyExample{ +public static void main(String args[]){ +String s1=""""; +String s2=""javatpoint""; + +System.out.println(s1.isEmpty()); +System.out.println(s2.isEmpty()); +}} + +Output: +true +false + + + +" +Could you provide an examples of Empty Vs. Null Strings?,"Earlier in this tutorial, we have discussed that the empty strings contain zero characters. However, the same is true for a null string too. A null string is a string that has no value. + +String str = """"; // empty string +String str1 = null; // null string. It is also not containing any characters. + +The isEmpty() method is not fit for checking the null strings. The following example shows the same. + +FileName: StringIsEmptyExample3.java +public class StringIsEmptyExample3 +{ +// main method +public static void main(String argvs[]) +{ +String str = null; +if(str.isEmpty()) +{ +System.out.println(""The string is null.""); +} +else +{ +System.out.println(""The string is not null.""); +} +} +} + +Output: +Exception in thread ""main"" java.lang.NullPointerException + at StringIsEmptyExample3.main(StringIsEmptyExample3.java:7) + +Here, we can use the == operator to check for the null strings. +FileName: StringIsEmptyExample4.java +class StringIsEmptyExample4 +{ +// main method +public static void main(String argvs[]) +{ +String str = null; +if(str == null) +{ +System.out.println(""The string is null.""); +} +else +{ +System.out.println(""The string is not null.""); +} +} +} + +Output: +The string is null. + + " +Could you provide an example of Blank Strings?,"Blank strings are those strings that contain only white spaces. The isEmpty() method comes in very handy to check for the blank strings. Consider the following example. + +FileName: StringIsEmptyExample5.java +public class StringIsEmptyExample5 +{ +// main method +public static void main(String argvs[]) +{ +// a blank string +String str = "" ""; +int size = str.length(); + +// trim the white spaces and after that +// if the string results in the empty string +// then the string is blank; otherwise, not. +if(size == 0) +{ +System.out.println(""The string is empty. \n""); +} +else if(size > 0 && str.trim().isEmpty()) +{ +System.out.println(""The string is blank. \n""); +} +else +{ +System.out.println(""The string is not blank. \n""); +} + +str = "" Welcome to JavaTpoint. ""; +size = str.length(); +if(size == 0) +{ +System.out.println(""The string is empty. \n""); +} +if(size > 0 && str.trim().isEmpty()) +{ +System.out.println(""The string is blank. \n""); +} +else +{ +System.out.println(""The string is not blank. \n""); +} +} +} + +Output: +The string is blank. +The string is not blank. + + +" +What is Java String join()?,"The Java String class join() method returns a string joined with a given delimiter. In the String join() method, the delimiter is copied for each element. The join() method is included in the Java string since JDK 1.8. +There are two types of join() methods in the Java String class. +Signature +The signature or syntax of the join() method is given below: +public static String join(CharSequence delimiter, CharSequence... elements) +and +public static String join(CharSequence delimiter, Iterable elements) +Parameters +delimiter : char value to be added with each element +elements : char value to be attached with delimiter +Returns +joined string with delimiter +Exception Throws +NullPointerException if element or delimiter is null. +Since +1.8 +Internal Implementation +// type - 1 +public static String join(CharSequence delimiter, CharSequence... elements) +{ + Objects.requireNonNull(elements); + Objects.requireNonNull(delimiter); + + StringJoiner jnr = new StringJoiner(delimiter); + for (CharSequence c: elements) + { + jnr.add(c); + } + return jnr.toString(); +} + + +// type - 2 +public static String join(CharSequence delimiter, CharSequence... elements) +{ + Objects.requireNonNull(elements); + Objects.requireNonNull(delimiter); + + StringJoiner jnr = new StringJoiner(delimiter); + for (CharSequence c: elements) + { + jnr.add(c); + } + return jnr.toString(); +} + +public static String join(CharSequence delimiter, Iterable elements) +{ + + + Objects.requireNonNull(elements); + Objects.requireNonNull(delimiter); + + StringJoiner jnr = new StringJoiner(delimiter); + for (CharSequence c: elements) + { + joiner.add(c); + } + return jnr.toString(); + } + + " +Could you provide Java String join() Method Example?,"FileName: StringJoinExample.java + +public class StringJoinExample{ +public static void main(String args[]){ +String joinString1=String.join(""-"",""welcome"",""to"",""javatpoint""); +System.out.println(joinString1); +}} + +Output: +welcome-to-javatpoint + + + +" +What is Java String lastIndexOf()?,"The Java String class lastIndexOf() method returns the last index of the given character value or substring. If it is not found, it returns -1. The index counter starts from zero. +Signature +There are four types of lastIndexOf() method in Java. The signature of the methods are given below: +1) int lastIndexOf(int ch) - It returns last index position for the given char value +2) int lastIndexOf(int ch, int fromIndex) - It returns last index position for the given char value and from index +3) int lastIndexOf(String substring) - It returns last index position for the given substring +4) int lastIndexOf(String substring, int fromIndex) - It returns last index position for the given substring and from index + +Parameters +ch: char value i.e. a single character e.g. 'a' +fromIndex: index position from where index of the char value or substring is retured +substring: substring to be searched in this string +Returns +last index of the string +Internal Implementation +The internal implementation of the four types of the lastIndexOf() method is mentioned below. +The internal implementation of the four types of the lastIndexOf() method is mentioned below. + +1. int lastIndexOf(int ch) +public int lastIndexOf(int ch) +{ + return lastIndexOf(ch, value.length - 1); +} + +2. int lastIndexOf(int ch, int fromIndex) +public int lastIndexOf(int ch, int fromIndex) +{ +if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) +{ +// handling most of the cases here +// negative value means invalid code point +final char[] val = this.value; +int j = Math.min(fromIndex, val.length - 1); +for (; jj >= 0; j--) +{ +if (val[i] == ch) +{ +return j; +} +} +return -1; +} + +else +{ +return lastIndexOfSupplementary(ch, fromIndex); +} +} + +// internal implementation of the method lastIndexOfSupplementary() +private int lastIndexOfSupplementary(int c, int fIndex) +{ +if (Character.isValidCodePoint(c)) +{ +final char[] val = this.value; +char h = Character.highSurrogate(c); +char l = Character.lowSurrogate(c); +int j = Math.min(fIndex, value.length - 2); +for (; j >= 0; j--) +{ +if (val[j] == h && val[j + 1] == l) +{ +return j; +} +} +} +return -1; +} + +3. int lastIndexOf(String subString) +public int lastIndexOf(String subString) +{ +return lastIndexOf(subString, value.length); +} + + +4. int lastIndexOf(String substring, int fromIndex) +public int lastIndexOf(String substring, int fromIndex) +{ +public int lastIndexOf(String str, int fromIndex) +{ +return lastIndexOf(value, 0, value.length, str.value, 0, str.value.length, fromIndex); +} +} + +// src the characters that are being searched. +// srcOffset provides the offset of the src string. +// srcCount number of the source string. +// tar the characters that are being searched for. +// fromIndex the index to start search from. +static int lastIndexOf(char[] src, int srcOffset, int srcCount, String tar, int fromIndex) +{ +return lastIndexOf(src, srcOffset, srcCount, tar.value, 0, tar.value.length, fromIndex); +} + + +static int lastIndexOf(char[] src, int srcOffset, int srcCount, char[] tar, int tarOffset, int tarCount, int fromIndex) +{ +int rightIndex = srcCount - tarCount; +if (fromIndex < 0) +{ + return -1; +} +if (fromIndex > rightIndex) +{ + fromIndex = rightIndex; +} +// an Empty string is always a match. +if (tarCount == 0) +{ + return fromIndex; +} + +int lastStrIndex = tarOffset + tarCount - 1; +char lastStrChar = tar[strLastIndex]; +int min = srcOffset + tarCount - 1; +int j = min + fromIndex; + +startLookForLastChar: +while (true) +{ +while (j >= min && src[j] != lastStrChar) +{ +j = j - 1; +} +if (j < min) +{ +return -1; +} +int i = j - 1; +int begin = i - (tarCount - 1); +int m = lastStrIndex - 1; + +while (i > begin) +{ +if (source[i--] != target[m--]) +{ +j = j + 1; +continue startLookForLastChar; +} +} +return begin - srcOffset + 1; +} +} + + " +Can you provide an example of Java String lastIndexOf() method?,"FileName: LastIndexOfExample.java + +public class LastIndexOfExample{ +public static void main(String args[]){ +String s1=""this is index of example"";//there are 2 's' characters in this sentence +int index1=s1.lastIndexOf('s');//returns last index of 's' char value +System.out.println(index1);//6 +}} + +Output: +6 + + + " +"Can provide an example of Java String lastIndexOf(int ch, int fromIndex) Method?","Here, we are finding the last index from the string by specifying fromIndex. + +FileName: LastIndexOfExample2.java +public class LastIndexOfExample2 { + public static void main(String[] args) { + String str = ""This is index of example""; + int index = str.lastIndexOf('s',5); + System.out.println(index); + } +} + +Output: +3 + + " +Could you provide an example of Java String lastIndexOf(String substring) Method?,"It returns the last index of the substring. + +FileName: LastIndexOfExample3.java +public class LastIndexOfExample3 { + public static void main(String[] args) { + String str = ""This is last index of example""; + int index = str.lastIndexOf(""of""); + System.out.println(index); + } +} + +Output: +19 + + + " +"Can you provide an example of Java String lastIndexOf(String substring, int fromIndex) Method?","It returns the last index of the substring from the fromIndex. + +FileName: LastIndexOfExample4.java +public class LastIndexOfExample4 { + public static void main(String[] args) { + String str = ""This is last index of example""; + int index = str.lastIndexOf(""of"", 25); + System.out.println(index); + index = str.lastIndexOf(""of"", 10); + System.out.println(index); // -1, if not found + } +} +Output: +19 +-1 + + + " +What is Java String length()?,"The Java String class length() method finds the length of a string. The length of the Java string is the same as the Unicode code units of the string. + +Signature +The signature of the string length() method is given below: +public int length() +Specified by +CharSequence interface +Returns +Length of characters. In other words, the total number of characters present in the string. +Internal implementation +public int length() { + return value.length; + } + +The String class internally uses a char[] array to store the characters. The length variable of the array is used to find the total number of elements present in the array. Since the Java String class uses this char[] array internally; therefore, the length variable can not be exposed to the outside world. Hence, the Java developers created the length() method, the exposes the value of the length variable. One can also think of the length() method as the getter() method, that provides a value of the class field to the user. The internal implementation clearly depicts that the length() method returns the value of then the length variable. + + +" +Could you provide Java String length() method example?,"FileName: LengthExample.java + +public class LengthExample{ +public static void main(String args[]){ +String s1=""javatpoint""; +String s2=""python""; +System.out.println(""string length is: ""+s1.length());//10 is the length of javatpoint string +System.out.println(""string length is: ""+s2.length());//6 is the length of python string +}} + +Output: +string length is: 10 +string length is: 6 + + + +" +What is Java String replace()?,"The Java String class replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence. + +Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char values. + +Signature +There are two types of replace() methods in Java String class. +public String replace(char oldChar, char newChar) +public String replace(CharSequence target, CharSequence replacement) +The second replace() method is added since JDK 1.5. +Parameters +oldChar : old character +newChar : new character +target : target sequence of characters +replacement : replacement sequence of characters +Returns +replaced string +Exception Throws +NullPointerException: if the replacement or target is equal to null. +Internal implementation +public String replace(char oldChar, char newChar) { + if (oldChar != newChar) { + int len = value.length; + int i = -1; + char[] val = value; /* avoid getfield opcode */ + + while (++i < len) { + if (val[i] == oldChar) { + break; + } + } + if (i < len) { + char buf[] = new char[len]; + for (int j = 0; j < i; j++) { + buf[j] = val[j]; + } + while (i < len) { + char c = val[i]; + buf[i] = (c == oldChar) ? newChar : c; + i++; + } + return new String(buf, true); + } + } + return this; + } + + +public String replace(CharSequence target, CharSequence replacement) +{ + return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( +this).replaceAll(Matcher.quoteReplacement(replacement.toString())); +} + + " +"Can you provide an example of Java String replace(char old, char new) method?","FileName: ReplaceExample1.java + +public class ReplaceExample1{ +public static void main(String args[]){ +String s1=""javatpoint is a very good website""; +String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e' +System.out.println(replaceString); +}} + +Output: +jevetpoint is e very good website + + + +" +"Could you provide Java String replace(CharSequence target, CharSequence replacement) method example?","FileName: ReplaceExample2.java + +public class ReplaceExample2{ +public static void main(String args[]){ +String s1=""my name is khan my name is java""; +String replaceString=s1.replace(""is"",""was"");//replaces all occurrences of ""is"" to ""was"" +System.out.println(replaceString); +}} + +Output: +my name was khan my name was java + + + " +What is Java String replaceAll()?,"The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string. + +Signature +public String replaceAll(String regex, String replacement) +Parameters +regex : regular expression +replacement : replacement sequence of characters +Returns +replaced string +Exception Throws +PatternSyntaxException: if the syntax of the regular expression is not valid. +Internal implementation + +public String replaceAll(String regex, String replacement) { + return Pattern.compile(regex).matcher(this).replaceAll(replacement); +} + + +" +Could you provide Java String replaceAll() example: replace character?,"Let's see an example to replace all the occurrences of a single character. + +FileName: ReplaceAllExample1.java + +public class ReplaceAllExample1{ +public static void main(String args[]){ +String s1=""javatpoint is a very good website""; +String replaceString=s1.replaceAll(""a"",""e"");//replaces all occurrences of ""a"" to ""e"" +System.out.println(replaceString); +}} + +Output: +jevetpoint is e very good website + + " +Could you provide Java String replaceAll() example: replace word?,"Let's see an example to replace all the occurrences of a single word or set of words. + +FileName: ReplaceAllExample2.java +public class ReplaceAllExample2{ +public static void main(String args[]){ +String s1=""My name is Khan. My name is Bob. My name is Sonoo.""; +String replaceString=s1.replaceAll(""is"",""was"");//replaces all occurrences of ""is"" to ""was"" +System.out.println(replaceString); +}} + +Output: +My name was Khan. My name was Bob. My name was Sonoo. + + + " +Java String replaceAll() example: remove white spaces?,"Let's see an example to remove all the occurrences of white spaces. + +FileName: ReplaceAllExample3.java +public class ReplaceAllExample3{ +public static void main(String args[]){ +String s1=""My name is Khan. My name is Bob. My name is Sonoo.""; +String replaceString=s1.replaceAll(""\\s"",""""); +System.out.println(replaceString); +}} + +Output: +MynameisKhan.MynameisBob.MynameisSonoo. + + " +What is Java String split()?,"The java string split() method splits this string against given regular expression and returns a char array. + " +Could you provide Java String split() method example?,"The given example returns total number of words in a string excluding space only. It also includes special characters. + +public class SplitExample{ +public static void main(String args[]){ +String s1=""java string split method by javatpoint""; +String[] words=s1.split(""\\s"");//splits the string based on whitespace +//using java foreach loop to print elements of string array +for(String w:words){ +System.out.println(w); +} +}} + +java +string +split +method +by +javatpoint + + " +Could you provide Java String split() method with regex and length example?,"public class SplitExample2{ +public static void main(String args[]){ +String s1=""welcome to split world""; +System.out.println(""returning words:""); +for(String w:s1.split(""\\s"",0)){ +System.out.println(w); +} +System.out.println(""returning words:""); +for(String w:s1.split(""\\s"",1)){ +System.out.println(w); +} +System.out.println(""returning words:""); +for(String w:s1.split(""\\s"",2)){ +System.out.println(w); +} + +}} + +returning words: +welcome +to +split +world +returning words: +welcome to split world +returning words: +welcome +to split world + + " +What is Java String startsWith()?,The Java String class startsWith() method checks if this string starts with the given prefix. It returns true if this string starts with the given prefix; else returns false. +Could you provide Java String startsWith() method example?,"The startsWith() method considers the case-sensitivity of characters. Consider the following example. + +FileName: StartsWithExample.java +public class StartsWithExample +{ +// main method +public static void main(String args[]) +{ +// input string +String s1=""java string split method by javatpoint""; +System.out.println(s1.startsWith(""ja"")); // true +System.out.println(s1.startsWith(""java string"")); // true +System.out.println(s1.startsWith(""Java string"")); // false as 'j' and 'J' are different +} +} + +Output: +true +true +false + + " +"Can you provide an example of Java String startsWith(String prefix, int offset) Method?","It is an overloaded method of the startWith() method that is used to pass an extra argument (offset) to the function. The method works from the passed offset. Let's see an example. + +FileName: StartsWithExample2.java +public class StartsWithExample2 { + public static void main(String[] args) { + String str = ""Javatpoint""; + // no offset mentioned; hence, offset is 0 in this case. + System.out.println(str.startsWith(""J"")); // True + + // no offset mentioned; hence, offset is 0 in this case. + System.out.println(str.startsWith(""a"")); // False + // offset is 1 + System.out.println(str.startsWith(""a"",1)); // True + } +} + +Output: +true +false +true + + " +What is Java String substring()?,"The Java String class substring() method returns a part of the string. + +We pass beginIndex and endIndex number position in the Java substring method where beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the endIndex starts from 1. + +There are two types of substring methods in Java string. + + " +Can you provide an example of Java String substring() method?,"FileName: SubstringExample.java + +public class SubstringExample{ +public static void main(String args[]){ +String s1=""javatpoint""; +System.out.println(s1.substring(2,4));//returns va +System.out.println(s1.substring(2));//returns vatpoint +}} + +Output: +va +vatpoint + " +Can you provide an example of Applications of substring() Method,"1) The substring() method can be used to do some prefix or suffix extraction. For example, we can have a list of names, and it is required to filter out names with surname as ""singh"". The following program shows the same. + +FileName: SubstringExample3.java +public class SubstringExample3 +{ +// main method +public static void main(String argvs[]) +{ +String str[] = +{ +""Praveen Kumar"", +""Yuvraj Singh"", +""Harbhajan Singh"", +""Gurjit Singh"", +""Virat Kohli"", +""Rohit Sharma"", +""Sandeep Singh"", +""Milkha Singh"" +}; + +String surName = ""Singh""; +int surNameSize = surName.length(); + +int size = str.length; + +for(int j = 0; j < size; j++) +{ + int length = str[j].length(); + // extracting the surname + String subStr = str[j].substring(length - surNameSize); + + // checks whether the surname is equal to ""Singh"" or not + if(subStr.equals(surName)) + { + System.out.println(str[j]); + } +} + +} +} +Output: +Yuvraj Singh +Harbhajan Singh +Gurjit Singh +Sandeep Singh +Milkha Singh + + +2) The substring() method can also be used to check whether a string is a palindrome or not. + +FileName: SubstringExample4.java +public class SubstringExample4 +{ +public boolean isPalindrome(String str) +{ +int size = str.length(); + +// handling the base case +if(size == 0 || size == 1) +{ +// an empty string +// or a string of only one character +// is always a palindrome +return true; +} +String f = str.substring(0, 1); +String l = str.substring(size - 1); +// comparing first and the last character of the string +if(l.equals(f)) +{ +// recursively finding the solution using the substring() method +// reducing the number of characters of the by 2 for the next recursion +return isPalindrome(str.substring(1, size - 1)); +} +return false; +} +// main method +public static void main(String argvs[]) +{ +// instantiating the class SubstringExample4 +SubstringExample4 obj = new SubstringExample4(); +String str[] = +{ +""madam"", +""rock"", +""eye"", +""noon"", +""kill"" +}; +int size = str.length; + +for(int j = 0; j < size; j++) +{ +if(obj.isPalindrome(str[j])) +{ +System.out.println(str[j] + "" is a palindrome.""); +} +else +{ +System.out.println(str[j] + "" is not a palindrome.""); +} +} +} +} + +Output: +madam is a palindrome. +rock is not a palindrome. +eye is a palindrome. +noon is a palindrome. +kill is not a palindrome. + + " +What is Java String toCharArray()?,"The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string. + " +Can you provide an example of Java String toCharArray() method?,"public class StringToCharArrayExample{ +public static void main(String args[]){ +String s1=""hello""; +char[] ch=s1.toCharArray(); +for(int i=0;i + +" +How to get Java Scanner?,"To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of Scanner class. For Example: + +Scanner in = new Scanner(System.in); + +To get the instance of Java Scanner which parses the strings, we need to pass the strings in the constructor of Scanner class. For Example: + +Scanner in = new Scanner(""Hello Javatpoint""); + +" +Can you give me the Java Scanner Class Constructors?,"Sn:1 +Constructor: Scanner(File source) +Description: It constructs a new Scanner that produces values scanned from the specified file. + +Sn:2 +Constructor: Scanner(File source, String charsetName) +Description: It constructs a new Scanner that produces values scanned from the specified file. + + +Sn:3 +Constructor: Scanner(InputStream source) +Description: It constructs a new Scanner that produces values scanned from the specified input stream. + + +Sn:4 +Constructor: Scanner(InputStream source, String charsetName) +Description: It constructs a new Scanner that produces values scanned from the specified input stream + + +Sn:5 +Constructor: Scanner(Readable source) +Description: It constructs a new Scanner that produces values scanned from the specified source. + + +Sn:6 +Constructor: Scanner(String source) +Description: It constructs a new Scanner that produces values scanned from the specified string. + + +Sn:7 +Constructor: Scanner(ReadableByteChannel source) +Description: It constructs a new Scanner that produces values scanned from the specified channel. + + +Sn:8 +Constructor: Scanner(ReadableByteChannel source, String charsetName) +Description: It constructs a new Scanner that produces values scanned from the specified channel. + + +Sn:9 +Constructor: Scanner(Path source) +Description: It constructs a new Scanner that produces values scanned from the specified file. + + +Sn:10 +Constructor: Scanner(Path source, String charsetName) +Description: It constructs a new Scanner that produces values scanned from the specified file." +Can you give me the ava Scanner Class Methods?,"Sn:1 +Modifier and Type: void +Method: close() +Description: It is used to close this scanner.. + +Sn:2 +Modifier and Type: pattern +Method: delimiter() +Description: It is used to get the Pattern which the Scanner class is currently using to match delimiters. + +Sn:3 +Modifier and Type: Stream +Method: findAll() +Description: It is used to find a stream of match results that match the provided pattern string. + +Sn:4 +Modifier and Type: String +Method: findInLine() +Description:It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. + +Sn:5 +Modifier and Type: string +Method: findWithinHorizon() +Description:It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. + +Sn:6 +Modifier and Type: boolean +Method: hasNext() +Description: It returns true if this scanner has another token in its input. + +Sn:7 +Modifier and Type: boolean +Method: hasNextBigDecimal() +Description: It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method or not. + +Sn:8 +Modifier and Type: boolean +Method: hasNextBigInteger() +Description: It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method or not. + +Sn:9 +Modifier and Type: boolean +Method: hasNextBoolean() +Description: It is used to check if the next token in this scanner's input can be interpreted as a Boolean using the nextBoolean() method or not. + +Sn:10 +Modifier and Type: boolean +Method: hasNextByte() +Description:It is used to check if the next token in this scanner's input can be interpreted as a Byte using the nextBigDecimal() method or not. + +Sn:11 +Modifier and Type: boolean +Method: hasNextDouble() +Description:It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextByte() method or not. + +Sn:12 +Modifier and Type: boolean +Method: hasNextFloat() +Description: It is used to check if the next token in this scanner's input can be interpreted as a Float using the nextFloat() method or not. + +Sn:13 +Modifier and Type: boolean +Method: hasNextInt() +Description:It is used to check if the next token in this scanner's input can be interpreted as an int using the nextInt() method or not. + +Sn:14 +Modifier and Type: boolean +Method: hasNextLine() +Description: It is used to check if there is another line in the input of this scanner or not. + +Sn:15 +Modifier and Type: boolean +Method: hasNextLong() +Description: It is used to check if the next token in this scanner's input can be interpreted as a Long using the nextLong() method or not. + +Sn:16 +Modifier and Type: boolean +Method: hasNextShort() +Description:It is used to check if the next token in this scanner's input can be interpreted as a Short using the nextShort() method or not. + +Sn:17 +Modifier and Type: IOException +Method: ioException() +Description:It is used to get the IOException last thrown by this Scanner's readable + +Sn:18 +Modifier and Type: Locale +Method: locale() +Description: It is used to get a Locale of the Scanner class. + +Sn:19 +Modifier and Type: MatchResult +Method: match() +Description: It is used to get the match result of the last scanning operation performed by this scanner. + +Sn:20 +Modifier and Type: String +Method: next() +Description: It is used to get the next complete token from the scanner which is in use. + +Sn:21 +Modifier and Type: BigDecimal +Method: nextBigDecimal() +Description: It scans the next token of the input as a BigDecimal. + +Sn:22 +Modifier and Type: BigInteger +Method: nextBigInteger() +Description: It scans the next token of the input as a BigInteger. + +Sn:23 +Modifier and Type: boolean +Method: nextBoolean() +Description:It scans the next token of the input into a boolean value and returns that value. + +Sn:24 +Modifier and Type: byte +Method: nextByte() +Description: It scans the next token of the input as a byte. + +Sn:25 +Modifier and Type: double +Method: nextDouble() +Description: It scans the next token of the input as a double. + +Sn:26 +Modifier and Type: float +Method: nextFloat() +Description: It scans the next token of the input as a float. + +Sn:27 +Modifier and Type: int +Method: nextInt() +Description: It scans the next token of the input as an Int. + +Sn:28 +Modifier and Type: String +Method: nextLine() +Description: It is used to get the input string that was skipped of the Scanner object. + +Sn:29 +Modifier and Type: long +Method: nextLong() +Description: It scans the next token of the input as a long. + +Sn:30 +Modifier and Type: short +Method: nextShort() +Description: It scans the next token of the input as a short. + +Sn:31 +Modifier and Type: int +Method: radix() +Description: It is used to get the default radix of the Scanner use. + +Sn:32 +Modifier and Type: void +Method: remove() +Description: It is used when remove operation is not supported by this implementation of Iterator. + +Sn:33 +Modifier and Type: Scanner +Method: reset() +Description: It is used to reset the Scanner which is in use. + +Sn:34 +Modifier and Type: Scanner +Method: skip() +Description:It skips input that matches the specified pattern, ignoring delimiters + +Sn:35 +Modifier and Type: Stream +Method: tokens() +Description:It is used to get a stream of delimiter-separated tokens from the Scanner object which is in use. + +Sn:36 +Modifier and Type: String +Method: toString() +Description:It is used to get the string representation of Scanner using. + +Sn:37 +Modifier and Type: Scanner +Method: useDelimiter() +Description: It is used to set the delimiting pattern of the Scanner which is in use to the specified pattern. + +Sn:38 +Modifier and Type: Scanner +Method: useLocale() +Description: It is used to sets this scanner's locale object to the specified locale. + +Sn:39 +Modifier and Type: Scanner +Method: useRadix() +Description: It is used to set the default radix of the Scanner which is in use to the specified radix. + +" +Can you provide Java Scanner Class example?,"Let's see a simple example of Java Scanner where we are getting a single input from the user. Here, we are asking for a string through in.nextLine() method. + +import java.util.*; +public class ScannerExample { +public static void main(String args[]){ + Scanner in = new Scanner(System.in); + System.out.print(""Enter your name: ""); + String name = in.nextLine(); + System.out.println(""Name is: "" + name); + in.close(); + } +} + +Output: +Enter your name: sonoo jaiswal +Name is: sonoo jaiswal + +" +What is Serialization and Deserialization in Java?,"Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies. + +The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform-independent, it means you can serialize an object on one platform and deserialize it on a different platform. + +For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class. + +We must have to implement the Serializable interface for serializing the object. + +" +What are the Advantages of Java Serialization?,"It is mainly used to travel object's state on the network (that is known as marshalling). +" +What is java.io.Serializable interface?,"Serializable is a marker interface (has no data member and method). It is used to ""mark"" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces. + +The Serializable interface must be implemented by the class whose object needs to be persisted. + +The String class and all the wrapper classes implement the java.io.Serializable interface by default. + +Let's see the example given below: + +Student.java + +import java.io.Serializable; +public class Student implements Serializable{ + int id; + String name; + public Student(int id, String name) { + this.id = id; + this.name = name; + } +} +In the above example, Student class implements Serializable interface. Now its objects can be converted into stream. The main class implementation of is showed in the next code." +What is the ObjectOutputStream class?,"The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream. Only objects that support the java.io.Serializable interface can be written to streams. + +Constructor: public ObjectOutputStream(OutputStream out) throws IOException {} +Description: It creates an ObjectOutputStream that writes to the specified OutputStream. + +Important Methods +1) public final void writeObject(Object obj) throws IOException {} - It writes the specified object to the ObjectOutputStream. +2) public void flush() throws IOException {} - It flushes the current output stream. +3) public void close() throws IOException {} - It closes the current output stream. + +" +What is the ObjectInputStream class?,"An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream. + +Constructor: public ObjectInputStream(InputStream in) throws IOException {} +Description: It creates an ObjectInputStream that reads from the specified InputStream. + +Important Methods + +1) public final Object readObject() throws IOException, ClassNotFoundException{} - It reads an object from the input stream. +2) public void close() throws IOException {} - It closes ObjectInputStream. + +" +Can you provide an Example of Java Serialization?,"In this example, we are going to serialize the object of Student class from above code. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt. + +Persist.java + +import java.io.*; +class Persist{ + public static void main(String args[]){ + try{ + //Creating the object + Student s1 =new Student(211,""ravi""); + //Creating stream and writing the object + FileOutputStream fout=new FileOutputStream(""f.txt""); + ObjectOutputStream out=new ObjectOutputStream(fout); + out.writeObject(s1); + out.flush(); + //closing the stream + out.close(); + System.out.println(""success""); + }catch(Exception e){System.out.println(e);} + } +} + + +Output: +success + +" +Can you provide an Example of Java Deserialization?,"Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. Let's see an example where we are reading the data from a deserialized object. + +Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. Let's see an example where we are reading the data from a deserialized object. + +Depersist.java + +import java.io.*; +class Depersist{ + public static void main(String args[]){ + try{ + //Creating stream to read the object + ObjectInputStream in=new ObjectInputStream(new FileInputStream(""f.txt"")); + Student s=(Student)in.readObject(); + //printing the data of the serialized object + System.out.println(s.id+"" ""+s.name); + //closing the stream + in.close(); + }catch(Exception e){System.out.println(e);} + } +} + +Output: +211 ravi + +" +Can you give me the Java Serialization with Inheritance (IS-A Relationship)?,"If a class implements Serializable interface then all its sub classes will also be serializable. Let's see the example given below: + +SerializeISA.java + +import java.io.Serializable; +class Person implements Serializable{ + int id; + String name; + Person(int id, String name) { + this.id = id; + this.name = name; + } +} +class Student extends Person{ + String course; + int fee; + public Student(int id, String name, String course, int fee) { + super(id,name); + this.course=course; + this.fee=fee; + } +} +public class SerializeISA +{ + public static void main(String args[]) + { + try{ + //Creating the object + Student s1 =new Student(211,""ravi"",""Engineering"",50000); + //Creating stream and writing the object + FileOutputStream fout=new FileOutputStream(""f.txt""); + ObjectOutputStream out=new ObjectOutputStream(fout); + out.writeObject(s1); + out.flush(); + //closing the stream + out.close(); + System.out.println(""success""); + }catch(Exception e){System.out.println(e);} + try{ + //Creating stream to read the object + ObjectInputStream in=new ObjectInputStream(new FileInputStream(""f.txt"")); + Student s=(Student)in.readObject(); + //printing the data of the serialized object + System.out.println(s.id+"" ""+s.name+"" ""+s.course+"" ""+s.fee); + //closing the stream + in.close(); + }catch(Exception e){System.out.println(e);} + } +} + +Output: +success +211 ravi Engineering 50000 + + +The SerializeISA class has serialized the Student class object that extends the Person class which is Serializable. Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be. + +" +Can you give me the Java Serialization with Aggregation (HAS-A Relationship)?,"If a class has a reference to another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime. + +Address.java +class Address{ + String addressLine,city,state; + public Address(String addressLine, String city, String state) { + this.addressLine=addressLine; + this.city=city; + this.state=state; + } +} + +Student.java +import java.io.Serializable; +public class Student implements Serializable{ + int id; + String name; + Address address;//HAS-A + public Student(int id, String name) { + this.id = id; + this.name = name; + } +} + +Since Address is not Serializable, you cannot serialize the instance of the Student class. + +" +Can you provide the Java Serialization with the static data member?,"If there is any static data member in a class, it will not be serialized because static is the part of class not object. + +Employee.java + +class Employee implements Serializable{ + int id; + String name; + static String company=""SSS IT Pvt Ltd"";//it won't be serialized + public Student(int id, String name) { + this.id = id; + this.name = name; + } +} + +" +What is Java Serialization with array or collection?,"Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is not serialiizable, serialization will be failed. +" +What is Externalizable in java?,"The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress format. It is not a marker interface. + +The Externalizable interface provides two methods: +-public void writeExternal(ObjectOutput out) throws IOException +-public void readExternal(ObjectInput in) throws IOException + +" +Can you provide the Java Transient Keyword?,"If you don't want to serialize any data member of a class, you can mark it as transient. + +Employee.java + +class Employee implements Serializable{ + transient int id; + String name; + public Student(int id, String name) { + this.id = id; + this.name = name; + } +} + +Now, id will not be serialized, so when you deserialize the object after serialization, you will not get the value of id. It will return default value always. In such case, it will return 0 because the data type of id is an integer. + + + +" +Can you give me the SerialVersionUID?,"The serialization process at runtime associates an id with each Serializable class which is known as SerialVersionUID. It is used to verify the sender and receiver of the serialized object. The sender and receiver must be the same. To verify it, SerialVersionUID is used. The sender and receiver must have the same SerialVersionUID, otherwise, InvalidClassException will be thrown when you deserialize the object. We can also declare our own SerialVersionUID in the Serializable class. To do so, you need to create a field SerialVersionUID and assign a value to it. It must be of the long type with static and final. It is suggested to explicitly declare the serialVersionUID field in the class and have it private also. For example: + +private static final long serialVersionUID=1L; + +Now, the Serializable class will look like this: + +Employee.java + +import java.io.Serializable; +class Employee implements Serializable{ + private static final long serialVersionUID=1L; + int id; + String name; + public Student(int id, String name) { + this.id = id; + this.name = name; + } +} + +" +What is Java transient Keyword?,"In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the type of data stored in that instance. Deserialization performs exactly opposite operation. It converts the byte sequence into original object data. During the serialization, when we do not want an object to be serialized we can use a transient keyword. +" +Why to use the transient keyword?,"The transient keyword can be used with the data members of a class in order to avoid their serialization. For example, if a program accepts a user's login details and password. But we don't want to store the original password in the file. Here, we can use transient keyword and when JVM reads the transient keyword it ignores the original value of the object and instead stores the default value of the object. + +Syntax: + +private transient ; + +Or + +transient private ; + +" +When to use the transient keyword?,"1)The transient modifier can be used where there are data members derived from the other data members within the same instance of the class. +2)This transient keyword can be used with the data members which do not depict the state of the object. +3)The data members of a non-serialized object or class can use a transient modifier. + +" +Can you provide an Example of Java Transient Keyword?,"Let's take an example, we have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but we don't want to serialize one value, e.g. age then we can declare the age data member as transient. + +In this example, we have created two classes Student and PersistExample. The age data member of the Student class is declared as transient, its value will not be serialized. + +If you deserialize the object, you will get the default value for transient variable. + +Let's create a class with transient variable. + +PersistExample.java + +import java.io.*; +public class Student implements Serializable{ + int id; + String name; + transient int age;//Now it will not be serialized + public Student(int id, String name,int age) { + this.id = id; + this.name = name; + this.age=age; + } +} +class PersistExample{ + public static void main(String args[])throws Exception{ + Student s1 =new Student(211,""ravi"",22);//creating object + //writing object into file + FileOutputStream f=new FileOutputStream(""f.txt""); + ObjectOutputStream out=new ObjectOutputStream(f); + out.writeObject(s1); + out.flush(); + out.close(); + f.close(); + System.out.println(""success""); + } +} +Output: +success + + +Now write the code for deserialization. + +DePersist.java + +import java.io.*; +class DePersist{ + public static void main(String args[])throws Exception{ + ObjectInputStream in=new ObjectInputStream(new FileInputStream(""f.txt"")); + Student s=(Student)in.readObject(); + System.out.println(s.id+"" ""+s.name+"" ""+s.age); + in.close(); + } +} + +Output: +211 ravi 0 + + +As you can see, printing age of the student returns 0 because value of age was not serialized. +In this article, we have discussed use of transient keyword in Java, where to use transient keyword and implementation of transient keyword in a Java program. + +" +What is Java Networking?,"Java Networking is a concept of connecting two or more computing devices together so that we can share resources. + +Java socket programming provides facility to share data between different computing devices. + +" +What is the Advantage of Java Networking?,"1.Sharing resources +2.Centralize software management + +The java.net package supports two protocols, + +1.TCP: Transmission Control Protocol provides reliable communication between the sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP. +2.UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of data to be transferred along two or more nodes + +" +What is Java Networking Terminology?,"The widely used Java networking terminologies are given below: +1.IP Address +2.Protocol +3.Port Number +4.MAC Address +5.Connection-oriented and connection-less protocol +6.Socket + +1) IP Address + +IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255. +It is a logical address that can be changed. + +2) Protocol + +A protocol is a set of rules basically that is followed for communication. For example: +-TCP +-FTP +-Telnet +-SMTP +-POP etc. +3) Port Number + +The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications. +The port number is associated with the IP address for communication between two applications. + +4) MAC Address + +MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller). A network node can have multiple NIC but each with unique MAC address. +For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e. + +5) Connection-oriented and connection-less protocol + +In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP. +But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of connection-less protocol is UDP. + +6) Socket + +A socket is an endpoint between two way communications. + +" +What is java.net package?,"The java.net package can be divided into two sections: + +1. A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network interfaces. +2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource pointed by URLs. + +The java.net package provides many classes to deal with networking applications in Java. A list of these classes is given below: + +-Authenticator +-CacheRequest +-CacheResponse +-ContentHandler +-CookieHandler +-CookieManager +-DatagramPacket +-DatagramSocket +-DatagramSocketImpl +-InterfaceAddress +-JarURLConnection +-MulticastSocket +-InetSocketAddress +-InetAddress +-Inet4Address +-Inet6Address +-IDN +-HttpURLConnection +-HttpCookie +-NetPermission +-NetworkInterface +-PasswordAuthentication +-Proxy +-ProxySelector +-ResponseCache +-SecureCacheResponse +-ServerSocket +-Socket +-SocketAddress +-SocketImpl +-SocketPermission +-StandardSocketOptions +-URI +-URL +-URLClassLoader +-URLConnection +-URLDecoder +-URLEncoder +-URLStreamHandler + +List of interfaces available in java.net package: + +-ContentHandlerFactory +-CookiePolicy +-CookieStore +-DatagramSocketImplFactory +-FileNameMap +-SocketOption +-SocketOptions +-SocketImplFactory +-URLStreamHandlerFactory +-ProtocolFamily + +" +What is Java Socket Programming?,"Java Socket programming is used for communication between the applications running on different JRE. + +Java Socket programming can be connection-oriented or connection-less. + +Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming. + +The client in socket programming must know two information: +1.IP Address of Server, and +2.Port number. + +Here, we are going to make one-way client and server communication. In this application, client sends a message to the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the client is connected. After the successful connection of client, it returns the instance of Socket at server-side. + +" +What is Socket class?,"A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket. + +Method: public InputStream getInputStream() +Description: returns the InputStream attached with this socket. + +Method: public OutputStream getOutputStream() +Description: returns the OutputStream attached with this socket. + +Method: public synchronized void close() +Description:closes this socket" +Can you provide the ServerSocket class?,"The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients. + +Method: public Socket accept() +Description: returns the socket and establish a connection between server and client. + +Method: public synchronized void close() +Description: closes the server socket." +Can you provide an Example of Java Socket Programming?,"Creating Server: + +To create the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port number for the communication between the client and server. You may also choose any other port number. The accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket. + +ServerSocket ss=new ServerSocket(6666); +Socket s=ss.accept();//establishes connection and waits for the client + +Creating Client: + +To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address or hostname of the Server and a port number. Here, we are using ""localhost"" because our server is running on same system. +Socket s=new Socket(""localhost"",6666); + +Let's see a simple of Java socket programming where client sends a text and server receives and prints it. + + +File: MyServer.java + +import java.io.*; +import java.net.*; +public class MyServer { +public static void main(String[] args){ +try{ +ServerSocket ss=new ServerSocket(6666); +Socket s=ss.accept();//establishes connection +DataInputStream dis=new DataInputStream(s.getInputStream()); +String str=(String)dis.readUTF(); +System.out.println(""message= ""+str); +ss.close(); +}catch(Exception e){System.out.println(e);} +} +} + +File: MyClient.java +import java.io.*; +import java.net.*; +public class MyClient { +public static void main(String[] args) { +try{ +Socket s=new Socket(""localhost"",6666); +DataOutputStream dout=new DataOutputStream(s.getOutputStream()); +dout.writeUTF(""Hello Server""); +dout.flush(); +dout.close(); +s.close(); +}catch(Exception e){System.out.println(e);} +} +} +To execute this program open two command prompts and execute each program at each command prompt +" +What is Java URL?,"The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. + +A URL contains many information: + +1.Protocol: In this case, http is the protocol. +2.Server name or IP Address: In this case, www.javatpoint.com is the server name. +3.Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1. +4.File Name or directory name: In this case, index.jsp is the file name. + +" +Can you give me the Constructors of Java URL class?,"URL(String spec) +Creates an instance of a URL from the String representation. + +URL(String protocol, String host, int port, String file) +Creates an instance of a URL from the given protocol, host, port number, and file. + +URL(String protocol, String host, int port, String file, URLStreamHandler handler) +Creates an instance of a URL from the given protocol, host, port number, file, and handler. + +URL(String protocol, String host, String file) +Creates an instance of a URL from the given protocol name, host name, and file name. + +URL(URL context, String spec) +Creates an instance of a URL by parsing the given spec within a specified context. + +URL(URL context, String spec, URLStreamHandler handler) +Creates an instance of a URL by parsing the given spec with the specified handler within a given context. + +" +Can you give me the Commonly used methods of Java URL class?,"The java.net.URL class provides many methods. The important methods of URL class are given below. + +Method: public String getProtocol() +Description: it returns the protocol of the URL. + +Method:public String getHost() +Description: it returns the host name of the URL. + +Method: public String getPort() +Description: it returns the Port Number of the URL. + +Method: public String getFile() +Description: it returns the file name of the URL. + +Method: public String getAuthority() +Description: it returns the authority of the URL. + +Method: public String toString() +Description: it returns the string representation of the URL. + +Method:public String getQuery() +Description: it returns the query string of the URL. + +Method: public String getDefaultPort() +Description: it returns the default port of the URL. + +Method: public URLConnection openConnection() +Description: it returns the instance of URLConnection i.e. associated with this URL. + +Method: public boolean equals(Object obj) +Description: it compares the URL with the given object. + +Method: public Object getContent() +Description: it returns the content of the URL. + +Method: public String getRef() +Description: it returns the anchor or reference of the URL. + +Method: public URI toURI() +Description: it returns a URI of the URL. +" +Can you provide an Example of Java URL class?,"//URLDemo.java + +import java.net.*; +public class URLDemo{ +public static void main(String[] args){ +try{ +URL url=new URL(""http://www.javatpoint.com/java-tutorial""); + +System.out.println(""Protocol: ""+url.getProtocol()); +System.out.println(""Host Name: ""+url.getHost()); +System.out.println(""Port Number: ""+url.getPort()); +System.out.println(""File Name: ""+url.getFile()); + +}catch(Exception e){System.out.println(e);} +} +} + +Output: +Protocol: http +Host Name: www.javatpoint.com +Port Number: -1 +File Name: /java-tutorial + + +" +What is Java URLConnection Class?,"The Java URLConnection class represents a communication link between the URL and the application. It can be used to read and write data to the specified resource referred by the URL. +" +What is the URL?,"-URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that helps to find a resource on the World Wide Web (WWW). + +-URL has two components: + +1.The protocol required to access the resource. +2.The location of the resource. + +" +What are the Features of URLConnection class?,"1.URLConnection is an abstract class. The two subclasses HttpURLConnection and JarURLConnection makes the connetion between the client Java program and URL resource on the internet. +2.With the help of URLConnection class, a user can read and write to and from any resource referenced by an URL object. +3.Once a connection is established and the Java program has an URLConnection object, we can use it to read or write or get further information like content length, etc. + +Constructor: protected URLConnection(URL url) +Description: It constructs a URL connection to the specified URL. + +" +Can you give me the URLConnection Class Methods?,"Method: void addRequestProperty(String key, String value) +Description: It adds a general request property specified by a key-value pair + +Method: void connect() +Description: It opens a communications link to the resource referenced by this URL, if such a connection has not already been established. + +Method: boolean getAllowUserInteraction() +Description: It returns the value of the allowUserInteraction field for the object. + +Method: int getConnectionTimeout() +Description: It returns setting for connect timeout + +Method: Object getContent() +Description: It retrieves the contents of the URL connection. + +Method: Object getContent(Class[] classes) +Description: It retrieves the contents of the URL connection. + +Method: String getContentEncoding() +Description:It returns the value of the content-encoding header field. + +Method: int getContentLength() +Description: It returns the value of the content-length header field. + +Method: long getContentLengthLong() +Description: It returns the value of the content-length header field as long. + +Method: String getContentType() +Description: It returns the value of the date header field + +Method: long getDate() +Description: It returns the value of the date header field. + +Method: static boolean getDefaultAllowUserInteraction() +Description: It returns the default value of the allowUserInteraction field. + +Method: boolean getDefaultUseCaches() +Description: It returns the default value of an URLConnetion's useCaches flag. + +Method: boolean getDoInput() +Description: It returns the value of the URLConnection's doInput flag. + +Method: boolean getDoInput() +Description: It returns the value of the URLConnection's doOutput flag. + +Method: long getExpiration() +Description:It returns the value of the expires header files. + +Method: static FileNameMap getFilenameMap() +Description: It loads the filename map from a data file. + +Method: String getHeaderField(int n) +Description: It returns the value of nth header field + +Method: String getHeaderField(String name) +Description: It returns the value of the named header field. + +Method: long getHeaderFieldDate(String name, long Default) +Description: It returns the value of the named field parsed as a number. + +Method: int getHeaderFieldInt(String name, int Default) +Description: It returns the value of the named field parsed as a number + +Method: String getHeaderFieldKey(int n) +Description: It returns the key for the nth header field. + +Method: long getHeaderFieldLong(String name, long Default) +Description: It returns the value of the named field parsed as a number + +Method: Map> getHeaderFields() +Description: It returns the unmodifiable Map of the header field. + +Method: long getIfModifiedSince() +Description: It returns the value of the object's ifModifiedSince field. + +Method: InputStream getInputStream() +Description: It returns an input stream that reads from the open condition. + +Method: long getLastModified() +Description: It returns the value of the last-modified header field. + +Method: OutputStream getOutputStream() +Description:It returns an output stream that writes to the connection. + +Method: Permission getPermission() +Description: It returns a permission object representing the permission necessary to make the connection represented by the object. + +Method: int getReadTimeout() +Description: It returns setting for read timeout + +Method: Map> getRequestProperties() +Description: It returns the value of the named general request property for the connection. + +Method: URL getURL() +Description: It returns the value of the URLConnection's URL field. + +Method: boolean getUseCaches() +Description: It returns the value of the URLConnection's useCaches field. + + +Method:Static String guessContentTypeFromName(String fname) +Description:It tries to determine the content type of an object, based on the specified file component of a URL. + +Method:static String guessContentTypeFromStream(InputStream is) +Description: It tries to determine the type of an input stream based on the characters at the beginning of the input stream. + +Method: void setAllowUserInteraction(boolean allowuserinteraction) +Description: It sets the value of the allowUserInteraction field of this URLConnection. + +Method: static void setContentHandlerFactory(ContentHandlerFactory fac) +Description: It sets the ContentHandlerFactory of an application. + +Method: static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction) +Description: It sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value. + +Method: void steDafaultUseCaches(boolean defaultusecaches) +Description: It sets the default value of the useCaches field to the specified value. + +Method: void setDoInput(boolean doinput) +Description: It sets the value of the doInput field for this URLConnection to the specified value. + +Method: void setDoOutput(boolean dooutput) +Description:It sets the value of the doOutput field for the URLConnection to the specified value. + +" +How to get the object of URLConnection Class?,"The openConnection() method of the URL class returns the object of URLConnection class. + +Syntax: +public URLConnection openConnection()throws IOException{} + +" +Can you give me the Displaying Source Code of a Webpage by URLConnecton Class?,"The URLConnection class provides many methods. We can display all the data of a webpage by using the getInputStream() method. It returns all the data of the specified URL in the stream that can be read and displayed. + +Example of Java URLConnection Class + +import java.io.*; +import java.net.*; +public class URLConnectionExample { +public static void main(String[] args){ +try{ +URL url=new URL(""http://www.javatpoint.com/java-tutorial""); +URLConnection urlcon=url.openConnection(); +InputStream stream=urlcon.getInputStream(); +int i; +while((i=stream.read())!=-1){ +System.out.print((char)i); +} +}catch(Exception e){System.out.println(e);} +} +} + +" +What is Java HttpURLConnection class?,"The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only. + +By the help of HttpURLConnection class, you can retrieve information of any HTTP URL such as header information, status code, response code etc. + +The java.net.HttpURLConnection is subclass of URLConnection class. + +" +Can you give me the HttpURLConnection Class Constructor?,"Constructor: protected HttpURLConnection(URL u) +Description: It constructs the instance of HttpURLConnection class. + +" +Can you give me the Java HttpURLConnection Methods?,"Method: void disconnect() +Description: It shows that other requests from the server are unlikely in the near future. + +Method: InputStream getErrorStream() +Description: It returns the error stream if the connection failed but the server sent useful data. + +Method: Static boolean getFollowRedirects() +Description: It returns a boolean value to check whether or not HTTP redirects should be automatically followed. + +Method: String getHeaderField(int n) +Description: It returns the value of nth header file. + +Method: long getHeaderFieldDate(String name, long Default) +Description: It returns the value of the named field parsed as a date. + +Method: String getHeaderFieldKey(int n) +Description: It returns the key for the nth header file. + +Method: boolean getInstanceFollowRedirects() +Description: It returns the value of HttpURLConnection's instance FollowRedirects field. + +Method: Permission getPermission() +Description: It returns the SocketPermission object representing the permission to connect to the destination host and port. + +Method: String getRequestMethod() +Description: It gets the request method. + +Method: int getResponseCode() +Description: It gets the response code from an HTTP response message. + +Method: String getResponseMessage() +Description:It gets the response message sent along with the response code from a server. + +Method: void setChunkedStreamingMode(int chunklen) +Description: The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. + +Method: void setFixedLengthStreamingMode(int contentlength) +Description: The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance. + +Method: void setFixedLengthStreamingMode(long contentlength) +Description: The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. + +Method: static void setFollowRedirects(boolean set) +Description:It sets whether HTTP redirects (requests with response code) should be automatically followed by HttpURLConnection class. + + +Method: void setInstanceFollowRedirects(boolean followRedirects) +Description: It sets whether HTTP redirects (requests with response code) should be automatically followed by instance of HttpURLConnection class. + +Method: void setRequestMethod(String method) +Description: Sets the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions. + +Method: abstract boolean usingProxy() +Description: It shows if the connection is going through a proxy. + + + +" +How to get the object of HttpURLConnection class?,"The openConnection() method of URL class returns the object of URLConnection class. + +Syntax: + +public URLConnection openConnection()throws IOException{} + +You can typecast it to HttpURLConnection type as given below. + +URL url=new URL(""http://www.javatpoint.com/java-tutorial""); +HttpURLConnection huc=(HttpURLConnection)url.openConnection(); +Java HttpURLConnection Example +import java.io.*; +import java.net.*; +public class HttpURLConnectionDemo{ +public static void main(String[] args){ +try{ +URL url=new URL(""http://www.javatpoint.com/java-tutorial""); +HttpURLConnection huc=(HttpURLConnection)url.openConnection(); +for(int i=1;i<=8;i++){ +System.out.println(huc.getHeaderFieldKey(i)+"" = ""+huc.getHeaderField(i)); +} +huc.disconnect(); +}catch(Exception e){System.out.println(e);} +} +} + + +Output: + +Date = Thu, 22 Jul 2021 18:08:17 GMT +Server = Apache +Location = https://www.javatpoint.com/java-tutorial +Cache-Control = max-age=2592000 +Expires = Sat, 21 Aug 2021 18:08:17 GMT +Content-Length = 248 +Keep-Alive =timeout=5, max=1500 +Connection = Keep-Alive +" +What is Java InetAddress class?,"Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com, etc. + +An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name. There are two types of addresses: Unicast and Multicast. The Unicast is an identifier for a single interface whereas Multicast is an identifier for a set of interfaces. + +Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name resolutions. + +IP Address + +-An IP address helps to identify a specific resource on the network using a numerical representation. +-Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual bridge among the destination and the source. +There are two versions of IP address: +1. IPv4 + +IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the ARAPNET in 1983. It is a widely used IP version to differentiate devices on network using an addressing scheme. A 32-bit addressing scheme is used to store 232 addresses that is more than 4 million addresses. +Features of IPv4: +-It is a connectionless protocol. +-It utilizes less memory and the addresses can be remembered easily with the class based addressing scheme. +-It also offers video conferencing and libraries. +2. IPv6 + +IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also identified with a name IPng (Internet Protocol next generation). + +Features of IPv6: + +-It has a stateful and stateless both configurations. +-It provides support for quality of service (QoS). +-It has a hierarchical addressing and routing infrastructure. +TCP/IP Protocol + +-TCP/IP is a communication protocol model used connect devices over a network via internet. +-TCP/IP helps in the process of addressing, transmitting, routing and receiving the data packets over the internet. + +-The two main protocols used in this communication model are: + +1.TCP i.e. Transmission Control Protocol. TCP provides the way to create a communication channel across the network. It also helps in transmission of packets at sender end as well as receiver end. +2.IP i.e. Internet Protocol. IP provides the address to the nodes connected on the internet. It uses a gateway computer to check whether the IP address is correct and the message is forwarded correctly or not. + +" +Can you give me the Java InetAddress Class Methods?,"Method: public static InetAddress getByName(String host) throws UnknownHostException +Description: It returns the instance of InetAddress containing LocalHost IP and name. + +Method: public static InetAddress getLocalHost() throws UnknownHostException +Description: It returns the instance of InetAdddress containing local host name and address. + +Method: public String getHostName() +Description: It returns the host name of the IP address. + +Method: public String getHostAddress() +Description: It returns the IP address in string format. + +" +Can you provide an Example of Java InetAddress Class?,"Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com website. + +InetDemo.java + +import java.io.*; +import java.net.*; +public class InetDemo{ +public static void main(String[] args){ +try{ +InetAddress ip=InetAddress.getByName(""www.javatpoint.com""); + +System.out.println(""Host Name: ""+ip.getHostName()); +System.out.println(""IP Address: ""+ip.getHostAddress()); +}catch(Exception e){System.out.println(e);} +} +} + +Output: +Host Name: www.javatpoint.com +IP Address: 172.67.196.82 + +" +Can you give me the Program to demonstrate methods of InetAddress class?,"InetDemo2.java + +import java.net.Inet4Address; +import java.util.Arrays; +import java.net.InetAddress; +public class InetDemo2 +{ +public static void main(String[] arg) throws Exception +{ +InetAddress ip = Inet4Address.getByName(""www.javatpoint.com""); +InetAddress ip1[] = InetAddress.getAllByName(""www.javatpoint.com""); +byte addr[]={72, 3, 2, 12}; +System.out.println(""ip : ""+ip); +System.out.print(""\nip1 : ""+ip1); +InetAddress ip2 = InetAddress.getByAddress(addr); +System.out.print(""\nip2 : ""+ip2); +System.out.print(""\nAddress : "" +Arrays.toString(ip.getAddress())); +System.out.print(""\nHost Address : "" +ip.getHostAddress()); +System.out.print(""\nisAnyLocalAddress : "" +ip.isAnyLocalAddress()); +System.out.print(""\nisLinkLocalAddress : "" +ip.isLinkLocalAddress()); +System.out.print(""\nisLoopbackAddress : "" +ip.isLoopbackAddress()); +System.out.print(""\nisMCGlobal : "" +ip.isMCGlobal()); +System.out.print(""\nisMCLinkLocal : "" +ip.isMCLinkLocal()); +System.out.print(""\nisMCNodeLocal : "" +ip.isMCNodeLocal()); +System.out.print(""\nisMCOrgLocal : "" +ip.isMCOrgLocal()); +System.out.print(""\nisMCSiteLocal : "" +ip.isMCSiteLocal()); +System.out.print(""\nisMulticastAddress : "" +ip.isMulticastAddress()); +System.out.print(""\nisSiteLocalAddress : "" +ip.isSiteLocalAddress()); +System.out.print(""\nhashCode : "" +ip.hashCode()); +System.out.print(""\n Is ip1 == ip2 : "" +ip.equals(ip2)); +} +} + +" +What is Java DatagramSocket and DatagramPacket?,"Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming using the UDP instead of TCP. + +Datagram + +Datagrams are collection of information sent from one device to another device via the established network. When the datagram is sent to the targeted device, there is no assurance that it will reach to the target device safely and completely. It may get damaged or lost in between. Likewise, the receiving device also never know if the datagram received is damaged or not. The UDP protocol is used to implement the datagrams in Java. + +" +What is Java DatagramSocket class?,"Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets. It is a mechanism used for transmitting datagram packets over network.` + +A datagram is basically an information but there is no guarantee of its content, arrival or arrival time. + +" +What is Commonly used Constructors of DatagramSocket class?,"-DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine. +-DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number. +-DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address. +" +Can you give me the Java DatagramSocket Class?,"Method: void bind(SocketAddress addr) +Description: It binds the DatagramSocket to a specific address and port. + +Method: void close() +Description: It closes the datagram socket. + + +Method: void connect(InetAddress address, int port) +Description:It connects the socket to a remote address for the socket. + + +Method: void disconnect() +Description: It disconnects the socket. + + +Method: boolean getBroadcast() +Description: It tests if SO_BROADCAST is enabled. + + +Method:DatagramChannel getChannel() +Description: It returns the unique DatagramChannel object associated with the datagram socket. + + +Method: InetAddress getInetAddress() +Description: It returns the address to where the socket is connected. + + +Method: InetAddress getLocalAddress() +Description: It gets the local address to which the socket is connected. + + +Method: int getLocalPort() +Description: It returns the port number on the local host to which the socket is bound. + + +Method: SocketAddress getLocalSocketAddress() +Description: It returns the address of the endpoint the socket is bound to. + + +Method: int getPort() +Description: It returns the port number to which the socket is connected. + + +Method: int getReceiverBufferSize() +Description: It gets the value of the SO_RCVBUF option for this DatagramSocket that is the buffer size used by the platform for input on the DatagramSocket. + + +Method: boolean isClosed() +Description: It returns the status of socket i.e. closed or not. + + +Method: boolean isConnected() +Description: It returns the connection state of the socket. + + +Method: void send(DatagramPacket p) +Description: It sends the datagram packet from the socket. + + +Method: void receive(DatagramPacket p) +Description:It receives the datagram packet from the socket. + +" +What is Java DatagramPacket Class?,"Java DatagramPacket is a message that can be sent or received. It is a data container. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed. +" +What is Commonly used Constructors of DatagramPacket class?,"-DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets. + +-DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets. + +" +Can you give me the Java DatagramPacket Class Methods?,"Method: InetAddress getAddress() +Description: It returns the IP address of the machine to which the datagram is being sent or from which the datagram was received. + +Method: byte[] getData() +Description: It returns the data buffer. + +Method: int getLength() +Description: It returns the length of the data to be sent or the length of the data received. + +Method: int getOffset() +Description: It returns the offset of the data to be sent or the offset of the data received. + +Method: int getPort() +Description: It returns the port number on the remote host to which the datagram is being sent or from which the datagram was received. + +Method: SocketAddress getSocketAddress() +Description: It gets the SocketAddress (IP address + port number) of the remote host that the packet is being sent to or is coming from. + +Method: void setAddress(InetAddress iaddr) +Description: It sets the IP address of the machine to which the datagram is being sent. + +Method: void setData(byte[] buff) +Description: It sets the data buffer for the packet. + +Method: void setLength(int length) +Description: It sets the length of the packet. + +Method: void setPort(int iport) +Description: It sets the port number on the remote host to which the datagram is being sent. + +Method: void setSocketAddress(SocketAddress addr) +Description: It sets the SocketAddress (IP address + port number) of the remote host to which the datagram is being sent. + +" +Can you provide an Example of Sending DatagramPacket by DatagramSocket?,"//DSender.java +import java.net.*; +public class DSender{ + public static void main(String[] args) throws Exception { + DatagramSocket ds = new DatagramSocket(); + String str = ""Welcome java""; + InetAddress ip = InetAddress.getByName(""127.0.0.1""); + + DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000); + ds.send(dp); + ds.close(); + } +} + +" +What is Java AWT Tutorial?,"Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based applications in Java. + +Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavy weight i.e. its components are using the resources of underlying operating system (OS). + +The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. + +The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps. + +" +Why AWT is platform independent?,"Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components like TextField, ChechBox, button, etc. + +For example, an AWT GUI with components like TextField, label and button will have different look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for their native components and AWT directly calls the native subroutine that creates those components. + +In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like a Mac application in the MAC OS. + +" +Can you give me the Useful Methods of Component Class?,"Method: public void add(Component c) +Description: Inserts a component on this component. + +Method: public void setSize(int width,int height) +Description: Sets the size (width and height) of the component. + +Method:public void setLayout(LayoutManager m) +Description: Defines the layout manager for the component. + +Method: public void setVisible(boolean status) +Description: Changes the visibility of the component, by default false. + +" +Can you provide the Java AWT Example?,"To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT. + +1.By extending Frame class (inheritance) +2.By creating the object of Frame class (association) + +" +Can you provide the AWT Example by Inheritance?,"Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame. + +AWTExample1.java + +// importing Java AWT class +import java.awt.*; + +// extending Frame class to our class AWTExample1 +public class AWTExample1 extends Frame { + + // initializing using constructor + AWTExample1() { + + // creating a button + Button b = new Button(""Click Me!!""); + + // setting button position on screen + b.setBounds(30,100,80,30); + + // adding button into frame + add(b); + + // frame size 300 width and 300 height + setSize(300,300); + + // setting the title of Frame + setTitle(""This is our basic AWT example""); + + // no layout manager + setLayout(null); + + // now frame will be visible, by default it is not visible + setVisible(true); +} + +// main method +public static void main(String args[]) { + +// creating instance of Frame class +AWTExample1 f = new AWTExample1(); + +} + +} + +The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that sets the position of the awt button. +" +What is Event and Listener (Java Event Handling)?,"Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling. +" +Can you give me the Java Event classes and Listener interfaces?,"Event class: ActionEvent +Listener Interface: ActionListener + +Event class: MouseEvent +Listener Interface: MouseListener and MouseMotionListener + +Event class: MouseWheelEvent +Listener Interface: MouseWheelListener + +Event class: KeyEvent +Listener Interface: KeyListener + +Event class: ItemEvent +Listener Interface: ItemListener + +Event class: TextEvent +Listener Interface: TextListener + +Event class: AdjustmentEvent +Listener Interface:AdjustmentListener + +Event class: WindowEvent +Listener Interface: WindowListener + +Event class: ComponentEvent +Listener Interface: ComponentListener + +Event class: ContainerEvent +Listener Interface: ContainerListener + +Event class: FocusEvent +Listener Interface: FocusListener + + + +" +Can you give me the Registration Methods?,"For registering the component with the Listener, many classes provide the registration methods. For example: + +-Button +-public void addActionListener(ActionListener a){} + +-MenuItem +-public void addActionListener(ActionListener a){} + +-TextField +-public void addActionListener(ActionListener a){} +-public void addTextListener(TextListener a){} + +-TextArea +-public void addTextListener(TextListener a){} + +-Checkbox +-public void addItemListener(ItemListener a){} + +-Choice +-public void addItemListener(ItemListener a){} + +-List +-public void addActionListener(ActionListener a){} +-public void addItemListener(ItemListener a){} + +" +How to use Java Event Handling Code?,"We can put the event handling code into one of the following places: + +1.Within class +2.Other class +3.Anonymous class + +" +Can you give me the Java event handling by implementing ActionListener?,"import java.awt.*; +import java.awt.event.*; +class AEvent extends Frame implements ActionListener{ +TextField tf; +AEvent(){ + +//create components +tf=new TextField(); +tf.setBounds(60,50,170,20); +Button b=new Button(""click me""); +b.setBounds(100,120,80,30); + +//register listener +b.addActionListener(this);//passing current instance + +//add components and set size, layout and visibility +add(b);add(tf); +setSize(300,300); +setLayout(null); +setVisible(true); +} +public void actionPerformed(ActionEvent e){ +tf.setText(""Welcome""); +} +public static void main(String args[]){ +new AEvent(); +} +} + +public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc. +" +Can you provide the Java event handling by outer class?,"import java.awt.*; +import java.awt.event.*; +class AEvent2 extends Frame{ +TextField tf; +AEvent2(){ +//create components +tf=new TextField(); +tf.setBounds(60,50,170,20); +Button b=new Button(""click me""); +b.setBounds(100,120,80,30); +//register listener +Outer o=new Outer(this); +b.addActionListener(o);//passing outer class instance +//add components and set size, layout and visibility +add(b);add(tf); +setSize(300,300); +setLayout(null); +setVisible(true); +} +public static void main(String args[]){ +new AEvent2(); +} +} + +import java.awt.event.*; +class Outer implements ActionListener{ +AEvent2 obj; +Outer(AEvent2 obj){ +this.obj=obj; +} +public void actionPerformed(ActionEvent e){ +obj.tf.setText(""welcome""); +} +} + +" +Can you give the Java event handling by anonymous class?,"import java.awt.*; +import java.awt.event.*; +class AEvent3 extends Frame{ +TextField tf; +AEvent3(){ +tf=new TextField(); +tf.setBounds(60,50,170,20); +Button b=new Button(""click me""); +b.setBounds(50,120,80,30); + +b.addActionListener(new ActionListener(){ +public void actionPerformed(){ +tf.setText(""hello""); +} +}); +add(b);add(tf); +setSize(300,300); +setLayout(null); +setVisible(true); +} +public static void main(String args[]){ +new AEvent3(); +} +} + +" +What is Java AWT Button?,"A button is basically a control component with a label that generates an event when pushed. The Button class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. + +When we press a button and release it, AWT sends an instance of ActionEvent to that button by calling processEvent on the button. The processEvent method of the button receives the all the events, then it passes an action event by calling its own method processActionEvent. This method passes the action event on to action listeners that are interested in the action events generated by the button. + +To perform an action on a button being pressed and released, the ActionListener interface needs to be implemented. The registered new listener can receive events from the button by calling addActionListener method of the button. The Java application can use the button's action command as a messaging protocol. + +" +What is AWT Button Class Declaration?,"public class Button extends Component implements Accessible +" +Can you give me the Button Class Constructors?,"Following table shows the types of Button class constructors + + +Sr. no : 1 +Constructor:Button( ) +Description: It constructs a new button with an empty string i.e. it has no label. + +Sr. no : 2 +Constructor: Button (String text) +Description: It constructs a new button with given string as its label. +" +Can you give me the Button Class Methods?,"Sr. no : 1 +Method: void setText (String text) +Description: It sets the string message on the button + +Sr. no : 2 +Method: String getText() +Description:It fetches the String message on the button. + +Sr. no : 3 +Method: void setLabel (String label) +Description: It sets the label of button with the specified string. + +Sr. no : 4 +Method: String getLabel() +Description:It fetches the label of the button. + +Sr. no : 5 +Method: void addNotify() +Description:It creates the peer of the button + +Sr. no : 6 +Method: AccessibleContext getAccessibleContext() +Description:It fetched the accessible context associated with the button. + +Sr. no : 7 +Method: void addActionListener(ActionListener l) +Description: It adds the specified action listener to get the action events from the button. + +Sr. no : 8 +Method: String getActionCommand() +Description: It returns the command name of the action event fired by the button. + +Sr. no : 9 +Method: ActionListener[ ] getActionListeners() +Description:It returns an array of all the action listeners registered on the button. + +Sr. no : 10 +Method: T[ ] getListeners(Class listenerType) +Description: It returns an array of all the objects currently registered as FooListeners upon this Button. +Sr. no : 11 +Method: protected String paramString() +Description:It returns the string which represents the state of button. + +Sr. no : 12 +Method: protected void processActionEvent (ActionEvent e) +Description: It process the action events on the button by dispatching them to a registered ActionListener object. + +Sr. no : 13 +Method: protected void processEvent (AWTEvent e) +Description:It process the events on the button + +Sr. no : 14 +Method: void removeActionListener (ActionListener l) +Description:It removes the specified action listener so that it no longer receives action events from the button. + +Sr. no : 15 +Method: void setActionCommand(String command) +Description:It sets the command name for the action event given by the button. + +" +Can you provide the Java AWT Button Example?,"ButtonExample.java + +import java.awt.*; +public class ButtonExample { +public static void main (String[] args) { + + // create instance of frame with the label + Frame f = new Frame(""Button Example""); + + // create instance of button with label + Button b = new Button(""Click Here""); + + // set the position for the button in frame + b.setBounds(50,100,80,30); + + // add button to the frame + f.add(b); + // set size, layout and visibility of frame + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +} + +To compile the program using command prompt type the following commands + +C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java + +If there's no error, we can execute the code using: + +C:\Users\Anurati\Desktop\abcDemo>java ButtonExample + +" +What is Java AWT Label?,"The object of the Label class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by a programmer but a user cannot edit it directly. + +It is called a passive control as it does not create any event when it is accessed. To create a label, we need to create the object of Label class. + +" +What is AWT Label Class Declaration?,"public class Label extends Component implements Accessible + +" +What is AWT Label Fields?,"The java.awt.Component class has following fields: +1.static int LEFT: It specifies that the label should be left justified. +2.static int RIGHT: It specifies that the label should be right justified. +3.static int CENTER: It specifies that the label should be placed in center + +" +Can you give me the Label class Constructors?,"Sr. no :1 +Constructor: Label() +Description: It constructs an empty label. + +Sr. no :2 +Constructor: Label(String text) +Description: It constructs a label with the given string (left justified by default). + +Sr. no :3 +Constructor: Label(String text, int alignement) +Description: It constructs a label with the specified string and the specified alignment. +" +Can you give me the Label Class Methods?,"Specified + +Sr. no :1 +Method name: void setText(String text) +Description:It sets the texts for label with the specified text.. + +Sr. no :2 +Method name: void setAlignment(int alignment) +Description:It sets the alignment for label with the specified alignment. + +Sr. no :3 +Method name: String getText() +Description:It gets the text of the label + +Sr. no :4 +Method name: int getAlignment() +Description: It gets the current alignment of the label. + +Sr. no :5 +Method name: void addNotify() +Description: It creates the peer for the label + +Sr. no :6 +Method name: AccessibleContext getAccessibleContext() +Description:It gets the Accessible Context associated with the label. + +Sr. no :7 +Method name: protected String paramString() +Description: It returns the string the state of the label. +" +Can you provide the Java AWT Label Example with ActionListener?,"In the following example, we are creating the objects of TextField, Label and Button classes and adding them to the Frame. Using the actionPerformed() method an event is generated over the button. When we add the website in the text field and click on the button, we get the IP address of website. + +LabelExample2.java + +import java.awt.*; +import java.awt.event.*; + +// creating class which implements ActionListener interface and inherits Frame class +public class LabelExample2 extends Frame implements ActionListener{ + + // creating objects of TextField, Label and Button class + TextField tf; + Label l; + Button b; + + // constructor to instantiate the above objects + LabelExample2() { + tf = new TextField(); + tf.setBounds(50, 50, 150, 20); + + l = new Label(); + l.setBounds(50, 100, 250, 20); + + b = new Button(""Find IP""); + b.setBounds(50,150,60,30); + b.addActionListener(this); + + add(b); + add(tf); + add(l); + + setSize(400,400); + setLayout(null); + setVisible(true); + } + + // defining actionPerformed method to generate an event + public void actionPerformed(ActionEvent e) { + try { + String host = tf.getText(); + String ip = java.net.InetAddress.getByName(host).getHostAddress(); + l.setText(""IP of ""+host+"" is: ""+ip); + } + catch (Exception ex) { + System.out.println(ex); + } + } + + // main method + public static void main(String[] args) { + new LabelExample2(); + } +} + +" +What is Java AWT TextField?,"The object of a TextField class is a text component that allows a user to enter a single line text and edit it. It inherits TextComponent class, which further inherits Component class. + +When we enter a key in the text field (like key pressed, key released or key typed), the event is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It can also be done using ActionEvent; if the ActionEvent is enabled on the text field, then the ActionEvent may be fired by pressing return key. The event is handled by the ActionListener interface. + +" +What is AWT TextField Class Declaration?,"public class TextField extends TextComponent + +" +Can you give me the TextField Class constructors?,"Sr. no: 1 +Constructor: TextField() +Description: It constructs a new text field component. + +Sr. no:2 +Constructor: TextField(String text) +Description: It constructs a new text field initialized with the given string text to be displayed. + +Sr. no:3 +Constructor: TextField(int columns) +Description: It constructs a new textfield (empty) with given number of columns. + +Sr. no:4 +Constructor: TextField(String text, int columns) +Description: It constructs a new text field with the given text and given number of columns (width)." +Can you give me the Method Inherited?,"The AWT TextField class inherits the methods from below classes: + +1.java.awt.TextComponent +2.java.awt.Component +3.java.lang.Object" +Can you provide the Java AWT TextField Example?,"TextFieldExample1.java + +// importing AWT class +import java.awt.*; +public class TextFieldExample1 { + // main method + public static void main(String args[]) { + // creating a frame + Frame f = new Frame(""TextField Example""); + + // creating objects of textfield + TextField t1, t2; + // instantiating the textfield objects + // setting the location of those objects in the frame + t1 = new TextField(""Welcome to Javatpoint.""); + t1.setBounds(50, 100, 200, 30); + t2 = new TextField(""AWT Tutorial""); + t2.setBounds(50, 150, 200, 30); + // adding the components to frame + f.add(t1); + f.add(t2); + // setting size, layout and visibility of frame + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +} " +What is Java AWT TextArea?,"The object of a TextArea class is a multiline region that displays text. It allows the editing of multiple line text. It inherits TextComponent class. + +The text area allows us to type as much text as we want. When the text in the text area becomes larger than the viewable area, the scroll bar appears automatically which helps us to scroll the text up and down, or right and left." +What is AWT TextArea Class Declaration?,public class TextArea extends TextComponent +Can you provide the Fields of TextArea Class?,"The fields of java.awt.TextArea class are as follows: + +-static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical scrollbars. +-static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the horizontal scrollbar. +–static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical scrollbar. +-static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text area." +Can you give me the Class constructors?,"Sr. no: 1 +Constructor: TextArea() +Description: It constructs a new and empty text area with no text in it. + +Sr. no: 2 +Constructor: TextArea (int row, int column) +Description: It constructs a new text area with specified number of rows and columns and empty string as text. + +Sr. no: 3 +Constructor: TextArea (String text) +Description: It constructs a new text area and displays the specified text in it. + +Sr. no: 4 +Constructor: TextArea (String text, int row, int column) +Description: It constructs a new text area with the specified text in the text area and specified number of rows and columns. + +Sr. no: 5 +Constructor: TextArea (String text, int row, int column, int scrollbars) +Description: It construcst a new text area with specified text in text area and specified number of rows and columns and visibility." +"Can you give me the TetArea Class Methods? +","Sr. no:1 +Method name: void addNotify() +Description:It creates a peer of text area. + +Sr. no:2 +Method name:void append(String str) +Description: It appends the specified text to the current text of text area. + + +Sr. no:3 +Method name: AccessibleContext getAccessibleContext() +Description: It returns the accessible context related to the text area + + +Sr. no:4 +Method name: int getColumns() +Description: It returns the number of columns of text area. + + +Sr. no:5 +Method name: Dimension getMinimumSize() +Description: It determines the minimum size of a text area. + + +Sr. no:6 +Method name: Dimension getMinimumSize(int rows, int columns) +Description: It determines the minimum size of a text area with the given number of rows and columns. + +Sr. no:7 +Method name: Dimension getPreferredSize() +Description: It determines the preferred size of a text area. + +Sr. no:8 +Method name: Dimension preferredSize(int rows, int columns) +Description: It determines the preferred size of a text area with given number of rows and columns. + +Sr. no:9 +Method name: int getRows() +Description: It returns the number of rows of text area. + +Sr. no:10 +Method name: int getScrollbarVisibility() +Description: It returns an enumerated value that indicates which scroll bars the text area uses. + +Sr. no:11 +Method name: void insert(String str, int pos) +Description: It inserts the specified text at the specified position in this text area. + +Sr. no:12 +Method name: protected String paramString() +Description: It returns a string representing the state of this TextArea. + +Sr. no:13 +Method name: void replaceRange(String str, int start, int end) +Description: It replaces text between the indicated start and end positions with the specified replacement text. + +Sr. no:14 +Method name: void setColumns(int columns) +Description: It sets the number of columns for this text area. + +Sr. no:15 +Method name: void setRows(int rows) +Description: It sets the number of rows for this text area." +Can you provide the Java AWT TextArea Example?,"The below example illustrates the simple implementation of TextArea where we are creating a text area using the constructor TextArea(String text) and adding it to the frame. + +TextAreaExample .java + +//importing AWT class +import java.awt.*; +public class TextAreaExample +{ +// constructor to initialize + TextAreaExample() { +// creating a frame + Frame f = new Frame(); +// creating a text area + TextArea area = new TextArea(""Welcome to javatpoint""); +// setting location of text area in frame + area.setBounds(10, 30, 300, 300); +// adding text area to frame + f.add(area); +// setting size, layout and visibility of frame + f.setSize(400, 400); + f.setLayout(null); + f.setVisible(true); + } +// main method +public static void main(String args[]) +{ + new TextAreaExample(); +} +} " +Can you give me the Java AWT TextArea Example with ActionListener?,"The following example displays a text area in the frame where it extends the Frame class and implements ActionListener interface. Using ActionListener the event is generated on the button press, where we are counting the number of character and words entered in the text area. + +TextAreaExample2.java + +// importing necessary libraries +import java.awt.*; +import java.awt.event.*; +// our class extends the Frame class to inherit its properties +// and implements ActionListener interface to override its methods +public class TextAreaExample2 extends Frame implements ActionListener { +// creating objects of Label, TextArea and Button class. +Label l1, l2; +TextArea area; +Button b; +// constructor to instantiate +TextAreaExample2() { +// instantiating and setting the location of components on the frame + l1 = new Label(); + l1.setBounds(50, 50, 100, 30); + l2 = new Label(); + l2.setBounds(160, 50, 100, 30); + area = new TextArea(); + area.setBounds(20, 100, 300, 300); + b = new Button(""Count Words""); + b.setBounds(100, 400, 100, 30); + +// adding ActionListener to button + b.addActionListener(this); + +// adding components to frame + add(l1); +add(l2); +add(area); +add(b); +// setting the size, layout and visibility of frame + setSize(400, 450); + setLayout(null); + setVisible(true); +} +// generating event text area to count number of words and characters +public void actionPerformed(ActionEvent e) { + String text = area.getText(); + String words[]=text.split(""\\s""); + l1.setText(""Words: ""+words.length); + l2.setText(""Characters: ""+text.length()); +} +// main method +public static void main(String[] args) { + new TextAreaExample2(); +} +}" +What is Java AWT Checkbox?,"The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a Checkbox changes its state from ""on"" to ""off"" or from ""off"" to ""on"". " +What is AWT Checkbox Class Declaration?,"public class Checkbox extends Component implements ItemSelectable, Accessible" +Can you give me the Method inherited by Checkbox?,"Sr. no:1 +Constructor: Checkbox() +Description: It constructs a checkbox with no string as the label. + +Sr. no:2 +Constructor: Checkbox(String label) +Description: It constructs a checkbox with the given label. + +Sr. no:3 +Constructor: Checkbox(String label, boolean state) +Description: It constructs a checkbox with the given label and sets the given state. + +Sr. no:4 +Constructor: Checkbox(String label, boolean state, CheckboxGroup group) +Description: It constructs a checkbox with the given label, set the given state in the specified checkbox group. + +Sr. no:5 +Constructor: Checkbox(String label, CheckboxGroup group, boolean state) +Description: It constructs a checkbox with the given label, in the given checkbox group and set to the specified state." +Can you give me the Checkbox Class Methods?,"Sr. no: 1 +Method name: void addItemListener(ItemListener IL) +Description: It adds the given item listener to get the item events from the checkbox. + +Sr. no:2 +Method name: AccessibleContext getAccessibleContext() +Description: It fetches the accessible context of checkbox. + + +Sr. no:3 +Method name: void addNotify() +Description: It creates the peer of checkbox. + + +Sr. no:4 +Method name: CheckboxGroup getCheckboxGroup() +Description: It determines the group of checkbox. + + +Sr. no:5 +Method name: ItemListener[] getItemListeners() +Description: It returns an array of the item listeners registered on checkbox. + + +Sr. no:6 +Method name: String getLabel() +Description: It fetched the label of checkbox. + +Sr. no:7 +Method name: T[] getListeners(Class listenerType) +Description: It returns an array of all the objects registered as FooListeners. + + +Sr. no:8 +Method name: Object[] getSelectedObjects() +Description: It returns an array (size 1) containing checkbox label and returns null if checkbox is not selected. + + +Sr. no:9 +Method name: boolean getState() +Description: It returns true if the checkbox is on, else returns off. + + +Sr. no:10 +Method name: protected String paramString() +Description: It returns a string representing the state of checkbox. + + +Sr. no:11 +Method name: protected void processEvent(AWTEvent e) +Description: It processes the event on checkbox. + + +Sr. no:12 +Method name: protected void processItemEvent(ItemEvent e) +Description: It process the item events occurring in the checkbox by dispatching them to registered ItemListener object. + + +Sr. no:13 +Method name: void removeItemListener(ItemListener l) +Description: It removes the specified item listener so that the item listener doesn't receive item events from the checkbox anymore. + +Sr. no:14 +Method name: void setCheckboxGroup(CheckboxGroup g) +Description: It sets the checkbox's group to the given checkbox. + +Sr. no:15 +Method name: void setLabel(String label) +Description: It sets the checkbox's label to the string argument. + +Sr. no:16 +Method name: void setState(boolean state) +Description: It sets the state of checkbox to the specified state." +Can you provide the Java AWT Checkbox Example?,"In the following example we are creating two checkboxes using the Checkbox(String label) constructo and adding them into the Frame using add() method. + +CheckboxExample1.java + +// importing AWT class +import java.awt.*; +public class CheckboxExample1 +{ +// constructor to initialize + CheckboxExample1() { +// creating the frame with the title + Frame f = new Frame(""Checkbox Example""); +// creating the checkboxes + Checkbox checkbox1 = new Checkbox(""C++""); + checkbox1.setBounds(100, 100, 50, 50); + Checkbox checkbox2 = new Checkbox(""Java"", true); +// setting location of checkbox in frame +checkbox2.setBounds(100, 150, 50, 50); +// adding checkboxes to frame + f.add(checkbox1); + f.add(checkbox2); + +// setting size, layout and visibility of frame + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } +// main method +public static void main (String args[]) +{ + new CheckboxExample1(); +} +} " +Can you give me the Java AWT Checkbox Example with ItemListener?,"In the following example, we have created two checkboxes and adding them into the Frame. Here, we are adding the ItemListener with the checkbox which displays the state of the checkbox (whether it is checked or unchecked) using the getStateChange() method. + +CheckboxExample2.java + +// importing necessary packages +import java.awt.*; +import java.awt.event.*; +public class CheckboxExample2 +{ +// constructor to initialize + CheckboxExample2() { +// creating the frame + Frame f = new Frame (""CheckBox Example""); +// creating the label + final Label label = new Label(); +// setting the alignment, size of label + label.setAlignment(Label.CENTER); + label.setSize(400,100); +// creating the checkboxes + Checkbox checkbox1 = new Checkbox(""C++""); + checkbox1.setBounds(100, 100, 50, 50); + Checkbox checkbox2 = new Checkbox(""Java""); + checkbox2.setBounds(100, 150, 50, 50); +// adding the checkbox to frame +f.add(checkbox1); +f.add(checkbox2); +f.add(label); + +// adding event to the checkboxes + checkbox1.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + label.setText(""C++ Checkbox: "" + + (e.getStateChange()==1?""checked"":""unchecked"")); + } + }); + checkbox2.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + label.setText(""Java Checkbox: "" + + (e.getStateChange()==1?""checked"":""unchecked"")); + } + }); +// setting size, layout and visibility of frame + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } +// main method +public static void main(String args[]) +{ + new CheckboxExample2(); +} +} " +What is Java AWT CheckboxGroup?,"The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box button is allowed to be in ""on"" state and remaining check box button in ""off"" state. It inherits the object class." +What is AWT CheckboxGroup Class Declaration?,public class CheckboxGroup extends Object implements Serializable +Can you provide the Java AWT CheckboxGroup Example?,"import java.awt.*; +public class CheckboxGroupExample +{ + CheckboxGroupExample(){ + Frame f= new Frame(""CheckboxGroup Example""); + CheckboxGroup cbg = new CheckboxGroup(); + Checkbox checkBox1 = new Checkbox(""C++"", cbg, false); + checkBox1.setBounds(100,100, 50,50); + Checkbox checkBox2 = new Checkbox(""Java"", cbg, true); + checkBox2.setBounds(100,150, 50,50); + f.add(checkBox1); + f.add(checkBox2); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } +public static void main(String args[]) +{ + new CheckboxGroupExample(); +} +} " +Can you give me the Java AWT CheckboxGroup Example with ItemListener?,"import java.awt.*; +import java.awt.event.*; +public class CheckboxGroupExample +{ + CheckboxGroupExample(){ + Frame f= new Frame(""CheckboxGroup Example""); + final Label label = new Label(); + label.setAlignment(Label.CENTER); + label.setSize(400,100); + CheckboxGroup cbg = new CheckboxGroup(); + Checkbox checkBox1 = new Checkbox(""C++"", cbg, false); + checkBox1.setBounds(100,100, 50,50); + Checkbox checkBox2 = new Checkbox(""Java"", cbg, false); + checkBox2.setBounds(100,150, 50,50); + f.add(checkBox1); f.add(checkBox2); f.add(label); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + checkBox1.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + label.setText(""C++ checkbox: Checked""); + } + }); + checkBox2.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + label.setText(""Java checkbox: Checked""); + } + }); + } +public static void main(String args[]) +{ + new CheckboxGroupExample(); +} +} +" +"What is Java AWT Choice? +",The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits Component class. +What is AWT Choice Class Declaration?,"public class Choice extends Component implements ItemSelectable, Accessible " +Can you give me the Choice Class constructor?,"Constructor: Choice() +Description: It constructs a new choice menu." +Can you give me the Choice Class Methods?,"Sr. no:1 +Method name: void add(String item) +Description: It adds an item to the choice menu. +. +Sr. no:2 +Method name: void addItemListener(ItemListener l) +Description: It adds the item listener that receives item events from the choice menu. + +Sr. no:3 +Method name: void addNotify() +Description: It creates the peer of choice. + +Sr. no:4 +Method name: AccessibleContext getAccessibleContext() +Description: It gets the accessbile context related to the choice. + +Sr. no:5 +Method name: String getItem(int index) +Description: It gets the item (string) at the given index position in the choice menu. + +Sr. no:6 +Method name: int getItemCount() +Description: It returns the number of items of the choice menu. + +Sr. no:7 +Method name: ItemListener[] getItemListeners() +Description: It returns an array of all item listeners registered on choice. + +Sr. no:8 +Method name: T[] getListeners(Class listenerType) +Description: Returns an array of all the objects currently registered as FooListeners upon this Choice. + +Sr. no:9 +Method name: int getSelectedIndex() +Description: Returns the index of the currently selected item. + +Sr. no:10 +Method name: String getSelectedItem() +Description: Gets a representation of the current choice as a string. + +Sr. no:11 +Method name:Object[] getSelectedObjects() +Description: Returns an array (length 1) containing the currently selected item. + +Sr. no:12 +Method name: void insert(String item, int index) +Description: Inserts the item into this choice at the specified position. + +Sr. no:13 +Method name: protected String paramString() +Description: Returns a string representing the state of this Choice menu. + +Sr. no:14 +Method name: protected void processEvent(AWTEvent e) +Description: It processes the event on the choice. + +Sr. no:15 +Method name: protected void processItemEvent (ItemEvent e) +Description: Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects. + +Sr. no:16 +Method name: void remove(int position) +Description: It removes an item from the choice menu at the given index position. + +Sr. no:17 +Method name: void remove(String item) +Description: It removes the first occurrence of the item from choice menu. + +Sr. no:18 +Method name: void removeAll() +Description: It removes all the items from the choice menu. + +Sr. no:19 +Method name: void removeItemListener (ItemListener l) +Description: It removes the mentioned item listener. Thus is doesn't receive item events from the choice menu anymore. + +Sr. no:20 +Method name: void select(int pos) +Description: It changes / sets the selected item in the choice menu to the item at given index position. + +Sr. no:21 +Method name: void select(String str) +Description: It changes / sets the selected item in the choice menu to the item whose string value is equal to string specified in the argument. + " +Can you provide the Java AWT Choice Example?,"In the following example, we are creating a choice menu using Choice() constructor. Then we add 5 items to the menu using add() method and Then add the choice menu into the Frame. + +ChoiceExample1.java + +// importing awt class +import java.awt.*; +public class ChoiceExample1 { + + // class constructor + ChoiceExample1() { + + // creating a frame + Frame f = new Frame(); + + // creating a choice component + Choice c = new Choice(); + + // setting the bounds of choice menu + c.setBounds(100, 100, 75, 75); + + // adding items to the choice menu + c.add(""Item 1""); + c.add(""Item 2""); + c.add(""Item 3""); + c.add(""Item 4""); + c.add(""Item 5""); + + // adding choice menu to frame + f.add(c); + + // setting size, layout and visibility of frame + f.setSize(400, 400); + f.setLayout(null); + f.setVisible(true); + } + +// main method +public static void main(String args[]) +{ + new ChoiceExample1(); +} +} " +Can you give me the Java AWT Choice Example with ActionListener?,"In the following example, we are creating a choice menu with 5 items. Along with that we are creating a button and a label. Here, we are adding an event to the button component using addActionListener(ActionListener a) method i.e. the selected item from the choice menu is displayed on the label when the button is clicked. + +ChoiceExample2.java + +// importing necessary packages +import java.awt.*; +import java.awt.event.*; + +public class ChoiceExample2 { + + // class constructor + ChoiceExample2() { + + // creating a frame + Frame f = new Frame(); + + // creating a final object of Label class + final Label label = new Label(); + + // setting alignment and size of label component + label.setAlignment(Label.CENTER); + label.setSize(400, 100); + + // creating a button + Button b = new Button(""Show""); + + // setting the bounds of button + b.setBounds(200, 100, 50, 20); + + // creating final object of Choice class + final Choice c = new Choice(); + + // setting bounds of choice menu + c.setBounds(100, 100, 75, 75); + + // adding 5 items to choice menu + c.add(""C""); + c.add(""C++""); + c.add(""Java""); + c.add(""PHP""); + c.add(""Android""); + + // adding above components into the frame + f.add(c); + f.add(label); + f.add(b); + + // setting size, layout and visibility of frame + f.setSize(400, 400); + f.setLayout(null); + f.setVisible(true); + + // adding event to the button + // which displays the selected item from the list when button is clicked + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String data = ""Programming language Selected: ""+ c.getItem(c.getSelectedIndex()); + label.setText(data); + } + }); + } + +// main method +public static void main(String args[]) +{ + new ChoiceExample2(); +} +} " +What is Java AWT List?,"The object of List class represents a list of text items. With the help of the List class, user can choose either one item or multiple items. It inherits the Component class." +What is AWT List class Declaration?,"public class List extends Component implements ItemSelectable, Accessible " +Can you give me the AWT List Class Constructors?,"Sr. no:1 +Constructor: List() +Description: It constructs a new scrolling list. + +Sr. no:2 +Constructor:List(int row_num) +Description:It constructs a new scrolling list initialized with the given number of rows visible. + +Sr. no:3 +Constructor: List(int row_num, Boolean multipleMode) +Description: It constructs a new scrolling list initialized which displays the given number of rows." +Can you give me the List Class Methods?,"Sr. no:1 +Method name: void add(String item) +Description: It adds the specified item into the end of scrolling list. + +Sr. no:2 +Method name: void add(String item, int index) +Description: It adds the specified item into list at the given index position. + +Sr. no:3 +Method name: void addActionListener(ActionListener l) +Description: It adds the specified action listener to receive action events from list. + +Sr. no:4 +Method name: void addItemListener(ItemListener l) +Description: It adds specified item listener to receive item events from list. + +Sr. no:5 +Method name: void addNotify() +Description: It creates peer of list. + +Sr. no:6 +Method name: void deselect(int index) +Description: It deselects the item at given index position. + +Sr. no:7 +Method name: AccessibleContext getAccessibleContext() +Description: It fetches the accessible context related to the list. + +Sr. no:8 +Method name: ActionListener[] getActionListeners() +Description: It returns an array of action listeners registered on the list. + +Sr. no:9 +Method name: String getItem(int index) +Description: It fetches the item related to given index position. + +Sr. no:10 +Method name: int getItemCount() +Description: It gets the count/number of items in the list. + +Sr. no:11 +Method name: ItemListener[] getItemListeners() +Description: It returns an array of item listeners registered on the list. + +Sr. no:12 +Method name: String[] getItems() +Description: It fetched the items from the list. + +Sr. no:13 +Method name:Dimension getMinimumSize() +Description: It gets the minimum size of a scrolling list. + +Sr. no:14 +Method name: Dimension getMinimumSize(int rows) +Description: It gets the minimum size of a list with given number of rows. + +Sr. no:15 +Method name: Dimension getPreferredSize() +Description: It gets the preferred size of list. + +Sr. no:16 +Method name: Dimension getPreferredSize(int rows) +Description: It gets the preferred size of list with given number of rows. + +Sr. no:17 +Method name: int getRows() +Description: It fetches the count of visible rows in the list. + +Sr. no:18 +Method name: int getSelectedIndex() +Description: It fetches the index of selected item of list. + +Sr. no:19 +Method name: int[] getSelectedIndexes() +Description: It gets the selected indices of the list. + +Sr. no:20 +Method name: String getSelectedItem() +Description: It gets the selected item on the list. + +Sr. no:21 +Method name:String[] getSelectedItems() +Description: It gets the selected items on the list. + +Sr. no:22 +Method name: Object[] getSelectedObjects() +Description: It gets the selected items on scrolling list in array of objects. + +Sr. no:23 +Method name: int getVisibleIndex() +Description: It gets the index of an item which was made visible by method makeVisible() + +Sr. no:24 +Method name:void makeVisible(int index) +Description: It makes the item at given index visible. + +Sr. no:25 +Method name: boolean isIndexSelected(int index) +Description: It returns true if given item in the list is selected. + +Sr. no:26 +Method name: boolean isMultipleMode() +Description: It returns the true if list allows multiple selections. + +Sr. no:27 +Method name: protected String paramString() +Description: It returns parameter string representing state of the scrolling list. + +Sr. no:28 +Method name: protected void processActionEvent(ActionEvent e) +Description: It process the action events occurring on list by dispatching them to a registered ActionListener object. + +Sr. no:29 +Method name: protected void processEvent(AWTEvent e) +Description: It process the events on scrolling list. + +Sr. no:30 +Method name:protected void processItemEvent(ItemEvent e) +Description: It process the item events occurring on list by dispatching them to a registered ItemListener object. + +Sr. no:31 +Method name: void removeActionListener(ActionListener l) +Description: It removes specified action listener. Thus it doesn't receive further action events from the list. + +Sr. no:32 +Method name: void removeItemListener(ItemListener l) +Description: It removes specified item listener. Thus it doesn't receive further action events from the list. + +Sr. no:33 +Method name: void remove(int position) +Description: It removes the item at given index position from the list. + +Sr. no:34 +Method name:void remove(String item) +Description: It removes the first occurrence of an item from list. + +Sr. no:35 +Method name: void removeAll() +Description: It removes all the items from the list. + +Sr. no:36 +Method name: void replaceItem(String newVal, int index) +Description: It replaces the item at the given index in list with the new string specified. + +Sr. no:37 +Method name: void select(int index) +Description: It selects the item at given index in the list. + +Sr. no:38 +Method name:void setMultipleMode(boolean b) +Description: It sets the flag which determines whether the list will allow multiple selection or not. + +Sr. no:39 +Method name:void removeNotify() +Description: It removes the peer of list." +Can you provide the Java AWT List Example?,"In the following example, we are creating a List component with 5 rows and adding it into the Frame. + +ListExample1.java + +// importing awt class +import java.awt.*; + +public class ListExample1 +{ + // class constructor + ListExample1() { + // creating the frame + Frame f = new Frame(); + // creating the list of 5 rows + List l1 = new List(5); + + // setting the position of list component + l1.setBounds(100, 100, 75, 75); + + // adding list items into the list + l1.add(""Item 1""); + l1.add(""Item 2""); + l1.add(""Item 3""); + l1.add(""Item 4""); + l1.add(""Item 5""); + + // adding the list to frame + f.add(l1); + + // setting size, layout and visibility of frame + f.setSize(400, 400); + f.setLayout(null); + f.setVisible(true); + } + +// main method +public static void main(String args[]) +{ + new ListExample1(); +} +} " +Can you give me the Java AWT List Example with ActionListene?,"In the following example, we are creating two List components, a Button and a Label and adding them into the frame. Here, we are generating an event on the button using the addActionListener(ActionListener l) method. On clicking the button, it displays the selected programming language and the framework. + +ListExample2.java + +// importing awt and event class +import java.awt.*; +import java.awt.event.*; + +public class ListExample2 +{ + // class constructor + ListExample2() { + // creating the frame + Frame f = new Frame(); + // creating the label which is final + final Label label = new Label(); + + // setting alignment and size of label + label.setAlignment(Label.CENTER); + label.setSize(500, 100); + + // creating a button + Button b = new Button(""Show""); + + // setting location of button + b.setBounds(200, 150, 80, 30); + + // creating the 2 list objects of 4 rows + // adding items to the list using add() + // setting location of list components + final List l1 = new List(4, false); + l1.setBounds(100, 100, 70, 70); + l1.add(""C""); + l1.add(""C++""); + l1.add(""Java""); + l1.add(""PHP""); + + + final List l2=new List(4, true); + l2.setBounds(100, 200, 70, 70); + l2.add(""Turbo C++""); + l2.add(""Spring""); + l2.add(""Hibernate""); + l2.add(""CodeIgniter""); + + // adding List, Label and Button to the frame + f.add(l1); + f.add(l2); + f.add(label); + f.add(b); + + // setting size, layout and visibility of frame + f.setSize(450,450); + f.setLayout(null); + f.setVisible(true); + + // generating event on the button + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String data = ""Programming language Selected: ""+l1.getItem(l1.getSelectedIndex()); + data += "", Framework Selected:""; + for(String frame:l2.getSelectedItems()) { + data += frame + "" ""; + } + label.setText(data); + } + }); +} + +// main method +public static void main(String args[]) +{ + new ListExample2(); +} +} " +What is Java AWT Canvas?,The Canvas class controls and represents a blank rectangular area where the application can draw or trap input events from the user. It inherits the Component class. +What is AWT Canvas class Declaration?,public class Canvas extends Component implements Accessible +What are the Constructors of the Canvas Class?,"Constructors of Canvas Class +Constructor: Canvas() +Description: It constructs a new Canvas. + +Constructor: Canvas(GraphicConfiguration config) +Description: It constructs a new Canvas with the given Graphic Configuration object." +What are the Method Inherited by Canvas Class?,"The Canvas has inherited above methods from the following classes: + +lang.Component +lang.Object +" +Can you provide the Java AWT Canvas Example?,"In the following example, we are creating a Canvas in the Frame and painting a red colored oval inside it. + +CanvasExample.java + + +// importing awt class +import java.awt.*; + +// class to construct a frame and containing main method +public class CanvasExample +{ + // class constructor + public CanvasExample() + { + + // creating a frame + Frame f = new Frame(""Canvas Example""); + // adding canvas to frame + f.add(new MyCanvas()); + + // setting layout, size and visibility of frame + f.setLayout(null); + f.setSize(400, 400); + f.setVisible(true); + } + + // main method + public static void main(String args[]) + { + new CanvasExample(); + } +} + +// class which inherits the Canvas class +// to create Canvas +class MyCanvas extends Canvas +{ + // class constructor + public MyCanvas() { + setBackground (Color.GRAY); + setSize(300, 200); + } + + // paint() method to draw inside the canvas + public void paint(Graphics g) + { + + // adding specifications + g.setColor(Color.red); + g.fillOval(75, 75, 150, 75); + } +} " +What is Java AWT Scrollbar?,"The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see invisible number of rows and columns. + +It can be added to top-level container like Frame or a component like Panel. The Scrollbar class extends the Component class." +What is AWT Scrollbar Class Declaration?,"public class Scrollbar extends Component implements Adjustable, Accessible " +What are the Scrollbar Class Fields?,"static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar. +static int VERTICAL - It is a constant to indicate a vertical scroll bar." +What are the Constructors of the Scrollbar Class?,"Sr. no.1 +Constructor: Scrollbar() +Description: Constructs a new vertical scroll bar. +Sr. no.2 +Constructor: Scrollbar(int orientation) +Description: Constructs a new scroll bar with the specified orientation. +Sr. no.3 +Constructor: Scrollbar(int orientation, int value, int visible, int minimum, int maximum) +Description: Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values." +What are the Method Inherited by Scrollbar?,"The methods of Scrollbar class are inherited from the following classes: +java.awt.Component +java.lang.Object" +What are the Methods of the Scrollbar Class?,"Sr. no. 1 Method name: void addAdjustmentListener (AdjustmentListener l) +Description: It adds the given adjustment listener to receive instances of AdjustmentEvent from the scroll bar. +Sr. no. 2 Method name: void addNotify() +Description: It creates the peer of scroll bar. +Sr. no. 3 Method name: int getBlockIncrement() +Description: It gets the block increment of the scroll bar. +Sr. no. 4 Method name: int getMaximum() +Description: It gets the maximum value of the scroll bar. +Sr. no. 5 Method name: int getMinimum() +Description: It gets the minimum value of the scroll bar. +Sr. no. 6 Method name: int getOrientation() +Description: It returns the orientation of scroll bar. +Sr. no. 7 Method name: int getUnitIncrement() +Description: int getUnitIncrement() +Sr. no. 8 Method name: int getValue() +Description: It fetches the current value of scroll bar. +Sr. no. 9 Method name: int getVisibleAmount() +Description: It fetches the visible amount of scroll bar. +Sr. no. 10 Method name: boolean getValueIsAdjusting() +Description: It returns true if the value is in process of changing where action results are being taken by the user. +Sr. no. 11 Method name: protected String paramString() +Description: It returns a string representing the state of Scroll bar. +Sr. no. 12 Method name: protected void processAdjustmentEvent (AdjustmentEvent e) +Description: It processes the adjustment event occurring on scroll bar by dispatching them to any registered AdjustmentListener objects. +Sr. no. 13 Method name: protected void processEvent(AWTEvent e) +Description: It processes the events on the scroll bar. +Sr. no. 14 Method name: void removeAdjustmentListener (AdjustmentListener l) +Description: It removes the given adjustment listener. Thus it no longer receives the instances of AdjustmentEvent from the scroll bar. +Sr. no. 15 Method name: void setBlockIncrement(int v) +Description: It sets the block increment from scroll bar. +Sr. no. 16 Method name: void setMaximum (int newMaximum) +Description: It sets the maximum value of the scroll bar. +Sr. no. 17 Method name: void setMinimum (int newMinimum) +Description: It sets the minimum value of the scroll bar. +Sr. no. 18 Method name: void setOrientation (int orientation) +Description: It sets the orientation for the scroll bar. +Sr. no. 19 Method name: void setUnitIncrement(int v) +Description: It sets the unit increment for the scroll bar. +Sr. no. 20 Method name: void setValue (int newValue) +Description: It sets the value of scroll bar with the given argument value. +Sr. no. 21 Method name: void setValueIsAdjusting (boolean b) +Description: It sets the valueIsAdjusting property to scroll bar. +Sr. no. 22 Method name: void setValues (int value, int visible, int minimum, int maximum) +Description: It sets the values of four properties for scroll bar: value, visible amount, minimum and maximum. +Sr. no. 23 Method name: void setVisibleAmount (int newAmount) +Description: It sets the visible amount of the scroll bar. +Sr. no. 24 Method name: AccessibleContext getAccessibleContext() +Description: It gets the accessible context related to the scroll bar. +Sr. no. 25 Method name: AdjustmentListener[] getAdjustmentListeners() +Description: It returns an array of al lthe adjustment listeners registered on the scroll bar. +Sr. no. 26 Method name: T[] getListeners(Class listenerType) +Description: It returns an array if all objects that are registered as FooListeners on the scroll bar currently. +" +Can you provide a Java AWT Scrollbar Example?,"The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see invisible number of rows and columns. + +It can be added to top-level container like Frame or a component like Panel. The Scrollbar class extends the Component class." +Can you provide a Java AWT Scrollbar Example with AdjustmentListener?,"In the following example, we are creating a Scrollbar and adding it into the Frame. Here, we are using addAdjustmentListener() method of Scrollbar class which receives the instances of AdjustmentEvent and eventually we display it in the form of Label. + +ScrollbarExample2.java + +// importing necessary packages +import java.awt.*; +import java.awt.event.*; + + +public class ScrollbarExample2 { + + // class constructor + ScrollbarExample2() { + // creating a Frame with a title + Frame f = new Frame(""Scrollbar Example""); + + // creating a final object of Label + final Label label = new Label(); + + // setting alignment and size of label object + label.setAlignment(Label.CENTER); + label.setSize(400, 100); + + // creating a final object of Scrollbar class + final Scrollbar s = new Scrollbar(); + + // setting the position of scroll bar + s.setBounds(100, 100, 50, 100); + + // adding Scrollbar and Label to the Frame + f.add(s); + f.add(label); + + // setting the size, layout, and visibility of frame + f.setSize(400, 400); + f.setLayout(null); + f.setVisible(true); + + // adding AdjustmentListener to the scrollbar object + s.addAdjustmentListener(new AdjustmentListener() { + public void adjustmentValueChanged(AdjustmentEvent e) { + label.setText(""Vertical Scrollbar value is:""+ s.getValue()); + } + }); + } + +// main method +public static void main(String args[]){ +new ScrollbarExample2(); +} +} " +What is Java AWT MenuItem and Menu?,"The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the MenuItem or any of its subclass. + +The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class." +What is AWT MenuItem class declaration?,public class MenuItem extends MenuComponent implements Accessible +What is AWT Menu class declaration?,"public class Menu extends MenuItem implements MenuContainer, Accessible " +Can you provide a Java AWT MenuItem and Menu Example?,"import java.awt.*; +class MenuExample +{ + MenuExample(){ + Frame f= new Frame(""Menu and MenuItem Example""); + MenuBar mb=new MenuBar(); + Menu menu=new Menu(""Menu""); + Menu submenu=new Menu(""Sub Menu""); + MenuItem i1=new MenuItem(""Item 1""); + MenuItem i2=new MenuItem(""Item 2""); + MenuItem i3=new MenuItem(""Item 3""); + MenuItem i4=new MenuItem(""Item 4""); + MenuItem i5=new MenuItem(""Item 5""); + menu.add(i1); + menu.add(i2); + menu.add(i3); + submenu.add(i4); + submenu.add(i5); + menu.add(submenu); + mb.add(menu); + f.setMenuBar(mb); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +public static void main(String args[]) +{ +new MenuExample(); +} +} " +What is Java AWT PopupMenu?,PopupMenu can be dynamically popped up at specific position within a component. It inherits the Menu class. +What is AWT PopupMenu class declaration?,"public class PopupMenu extends Menu implements MenuContainer, Accessible " +Can you provide a Java AWT PopupMenu Example?,"import java.awt.*; +import java.awt.event.*; +class PopupMenuExample +{ + PopupMenuExample(){ + final Frame f= new Frame(""PopupMenu Example""); + final PopupMenu popupmenu = new PopupMenu(""Edit""); + MenuItem cut = new MenuItem(""Cut""); + cut.setActionCommand(""Cut""); + MenuItem copy = new MenuItem(""Copy""); + copy.setActionCommand(""Copy""); + MenuItem paste = new MenuItem(""Paste""); + paste.setActionCommand(""Paste""); + popupmenu.add(cut); + popupmenu.add(copy); + popupmenu.add(paste); + f.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + popupmenu.show(f , e.getX(), e.getY()); + } + }); + f.add(popupmenu); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } +public static void main(String args[]) +{ + new PopupMenuExample(); +} +} " +"What is Java AWT Panel? +",The Panel is a simplest container class. It provides space in which an application can attach any other component. It inherits the Container class. +What is AWT Panel class declaration?,public class Panel extends Container implements Accessible +Can you provide a Java AWT Panel Example?,"import java.awt.*; +public class PanelExample { + PanelExample() + { + Frame f= new Frame(""Panel Example""); + Panel panel=new Panel(); + panel.setBounds(40,80,200,200); + panel.setBackground(Color.gray); + Button b1=new Button(""Button 1""); + b1.setBounds(50,100,80,30); + b1.setBackground(Color.yellow); + Button b2=new Button(""Button 2""); + b2.setBounds(100,100,80,30); + b2.setBackground(Color.green); + panel.add(b1); panel.add(b2); + f.add(panel); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } + public static void main(String args[]) + { + new PanelExample(); + } +} " +What is Java AWT Dialog?,"The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Window class. + +Unlike Frame, it doesn't have maximize and minimize buttons." +Frame vs Dialog,Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't have. +What is AWT Dialog class declaration?,public class Dialog extends Window +Can you provide a Java AWT Dialog Example?,"import java.awt.*; +import java.awt.event.*; +public class DialogExample { + private static Dialog d; + DialogExample() { + Frame f= new Frame(); + d = new Dialog(f , ""Dialog Example"", true); + d.setLayout( new FlowLayout() ); + Button b = new Button (""OK""); + b.addActionListener ( new ActionListener() + { + public void actionPerformed( ActionEvent e ) + { + DialogExample.d.setVisible(false); + } + }); + d.add( new Label (""Click button to continue."")); + d.add(b); + d.setSize(300,300); + d.setVisible(true); + } + public static void main(String args[]) + { + new DialogExample(); + } +} " +What is Java AWT Toolkit?,Toolkit class is the abstract superclass of every implementation in the Abstract Window Toolkit. Subclasses of Toolkit are used to bind various components. It inherits Object class. +What is AWT Toolkit class declaration?,public abstract class Toolkit extends Object +Can you provide a Java AWT Toolkit Example?,"import java.awt.*; +public class ToolkitExample { + public static void main(String[] args) { + Toolkit t = Toolkit.getDefaultToolkit(); + System.out.println(""Screen resolution = "" + t.getScreenResolution()); + Dimension d = t.getScreenSize(); + System.out.println(""Screen width = "" + d.width); + System.out.println(""Screen height = "" + d.height); + } +} +Output: + +Screen resolution = 96 +Screen width = 1366 +Screen height = 768" +Can you provide a Java AWT Toolkit Example: Change TitleBar Icon?,"import java.awt.*; +class ToolkitExample { +ToolkitExample(){ +Frame f=new Frame(); +Image icon = Toolkit.getDefaultToolkit().getImage(""D:\\icon.png""); +f.setIconImage(icon); +f.setLayout(null); +f.setSize(400,400); +f.setVisible(true); +} +public static void main(String args[]){ +new ToolkitExample(); +} +} " +Can you provide a Java ActionListener Example: On Button click?,"import java.awt.*; +import java.awt.event.*; +//1st step +public class ActionListenerExample implements ActionListener{ +public static void main(String[] args) { + Frame f=new Frame(""ActionListener Example""); + final TextField tf=new TextField(); + tf.setBounds(50,50, 150,20); + Button b=new Button(""Click Here""); + b.setBounds(50,100,60,30); + //2nd step + b.addActionListener(this); + f.add(b);f.add(tf); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +//3rd step +public void actionPerformed(ActionEvent e){ + tf.setText(""Welcome to Javatpoint.""); +} +} " +Can you provide a Java ActionListener Example: Using Anonymous class?,"We can also use the anonymous class to implement the ActionListener. It is the shorthand way, so you do not need to follow the 3 steps: + +b.addActionListener(new ActionListener(){ +public void actionPerformed(ActionEvent e){ + tf.setText(""Welcome to Javatpoint.""); +} +}); +Let us see the full code of ActionListener using anonymous class. + +import java.awt.*; +import java.awt.event.*; +public class ActionListenerExample { +public static void main(String[] args) { + Frame f=new Frame(""ActionListener Example""); + final TextField tf=new TextField(); + tf.setBounds(50,50, 150,20); + Button b=new Button(""Click Here""); + b.setBounds(50,100,60,30); + + b.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e){ + tf.setText(""Welcome to Javatpoint.""); + } + }); + f.add(b);f.add(tf); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +} " +What is Java MouseListener Interface?,The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods. +What are the Methods of MouseListener interface?,"The signature of 5 methods found in MouseListener interface are given below: + +public abstract void mouseClicked(MouseEvent e); +public abstract void mouseEntered(MouseEvent e); +public abstract void mouseExited(MouseEvent e); +public abstract void mousePressed(MouseEvent e); +public abstract void mouseReleased(MouseEvent e); +" +Can you provide a Java MouseListener Example?,"import java.awt.*; +import java.awt.event.*; +public class MouseListenerExample extends Frame implements MouseListener{ + Label l; + MouseListenerExample(){ + addMouseListener(this); + + l=new Label(); + l.setBounds(20,50,100,20); + add(l); + setSize(300,300); + setLayout(null); + setVisible(true); + } + public void mouseClicked(MouseEvent e) { + l.setText(""Mouse Clicked""); + } + public void mouseEntered(MouseEvent e) { + l.setText(""Mouse Entered""); + } + public void mouseExited(MouseEvent e) { + l.setText(""Mouse Exited""); + } + public void mousePressed(MouseEvent e) { + l.setText(""Mouse Pressed""); + } + public void mouseReleased(MouseEvent e) { + l.setText(""Mouse Released""); + } +public static void main(String[] args) { + new MouseListenerExample(); +} +} " +What is Java MouseMotionListener Interface?,The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It has two methods. +What are the Methods of MouseMotionListener interface?,"The signature of 2 methods found in MouseMotionListener interface are given below: + +public abstract void mouseDragged(MouseEvent e); +public abstract void mouseMoved(MouseEvent e); " +Can you provide a Java MouseMotionListener Example?,"import java.awt.*; +import java.awt.event.*; +public class MouseMotionListenerExample extends Frame implements MouseMotionListener{ + MouseMotionListenerExample(){ + addMouseMotionListener(this); + + setSize(300,300); + setLayout(null); + setVisible(true); + } +public void mouseDragged(MouseEvent e) { + Graphics g=getGraphics(); + g.setColor(Color.BLUE); + g.fillOval(e.getX(),e.getY(),20,20); +} +public void mouseMoved(MouseEvent e) {} + +public static void main(String[] args) { + new MouseMotionListenerExample(); +} +} " +What is Java ItemListener Interface?,The Java ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one method: itemStateChanged(). +What is itemStateChanged() method?,"The itemStateChanged() method is invoked automatically whenever you click or unclick on the registered checkbox component. + +public abstract void itemStateChanged(ItemEvent e); " +Can you provide a Java ItemListener Example?,"import java.awt.*; +import java.awt.event.*; +public class ItemListenerExample implements ItemListener{ + Checkbox checkBox1,checkBox2; + Label label; + ItemListenerExample(){ + Frame f= new Frame(""CheckBox Example""); + label = new Label(); + label.setAlignment(Label.CENTER); + label.setSize(400,100); + checkBox1 = new Checkbox(""C++""); + checkBox1.setBounds(100,100, 50,50); + checkBox2 = new Checkbox(""Java""); + checkBox2.setBounds(100,150, 50,50); + f.add(checkBox1); f.add(checkBox2); f.add(label); + checkBox1.addItemListener(this); + checkBox2.addItemListener(this); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } + public void itemStateChanged(ItemEvent e) { + if(e.getSource()==checkBox1) + label.setText(""C++ Checkbox: "" + + (e.getStateChange()==1?""checked"":""unchecked"")); + if(e.getSource()==checkBox2) + label.setText(""Java Checkbox: "" + + (e.getStateChange()==1?""checked"":""unchecked"")); + } +public static void main(String args[]) +{ + new ItemListenerExample(); +} +} " +What is Java KeyListener Interface?,"The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three methods." +What are the Methods of KeyListener interface?,"Methods of KeyListener interface +The signature of 3 methods found in KeyListener interface are given below: + +Method name: public abstract void keyPressed (KeyEvent e); +Description: It is invoked when a key has been pressed. + +Method name: public abstract void keyReleased (KeyEvent e); +Description: It is invoked when a key has been released. + +Method name: public abstract void keyTyped (KeyEvent e); +Description: It is invoked when a key has been typed. + + +" +Can you provide a Java KeyListener Example?,"In the following example, we are implementing the methods of the KeyListener interface. + +KeyListenerExample.java + +// importing awt libraries +import java.awt.*; +import java.awt.event.*; +// class which inherits Frame class and implements KeyListener interface +public class KeyListenerExample extends Frame implements KeyListener { +// creating object of Label class and TextArea class + Label l; + TextArea area; +// class constructor + KeyListenerExample() { + // creating the label + l = new Label(); +// setting the location of the label in frame + l.setBounds (20, 50, 100, 20); +// creating the text area + area = new TextArea(); +// setting the location of text area + area.setBounds (20, 80, 300, 300); +// adding the KeyListener to the text area + area.addKeyListener(this); +// adding the label and text area to the frame + add(l); +add(area); +// setting the size, layout and visibility of frame + setSize (400, 400); + setLayout (null); + setVisible (true); + } +// overriding the keyPressed() method of KeyListener interface where we set the text of the label when key is pressed + public void keyPressed (KeyEvent e) { + l.setText (""Key Pressed""); + } +// overriding the keyReleased() method of KeyListener interface where we set the text of the label when key is released + public void keyReleased (KeyEvent e) { + l.setText (""Key Released""); + } +// overriding the keyTyped() method of KeyListener interface where we set the text of the label when a key is typed + public void keyTyped (KeyEvent e) { + l.setText (""Key Typed""); + } + // main method + public static void main(String[] args) { + new KeyListenerExample(); + } +} " +What is Java WindowListener Interface?,The Java WindowListener is notified whenever you change the state of window. It is notified against WindowEvent. The WindowListener interface is found in java.awt.event package. It has three methods. +What is WindowListener interface declaration?,"The declaration for java.awt.event.WindowListener interface is shown below: + +public interface WindowListener extends EventListener " +What are the Methods of WindowListener interface?,"Methods of WindowListener interface +The signature of 7 methods found in WindowListener interface with their usage are given below: + +Method signature: public abstract void windowActivated (WindowEvent e); +Description: It is called when the Window is set to be an active Window. + +Method signature: public abstract void windowClosed (WindowEvent e); +Description: It is called when a window has been closed as the result of calling dispose on the window. + +Method signature: public abstract void windowClosing (WindowEvent e); +Description: It is called when the user attempts to close the window from the system menu of the window. + +Method signature: public abstract void windowDeactivated (WindowEvent e); +Description: It is called when a Window is not an active Window anymore. + +Method signature: public abstract void windowDeiconified (WindowEvent e); +Description: It is called when a window is changed from a minimized to a normal state. + +Method signature: public abstract void windowIconified (WindowEvent e); +Description: It is called when a window is changed from a normal to a minimized state. + +Method signature: public abstract void windowOpened (WindowEvent e); +Description: It is called when window is made visible for the first time. + +" +What is Working of WindowListener interface?,"-If a class needs to process some Window events, an object should exist which can implement the interface. +-As the object is already registered with Listener, an event will be generated on all the states of window. +-This helps in generation of invocation of relevant method in listener's object. And then WindowEvent is passed after invocation." +Can you provide a Java WindowListener Example?,"In the following example, we are going to implement all the method of WindowListener interface one by one. + +WindowExample.java + +// importing necessary libraries of awt +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +// class which inherits Frame class and implements WindowListener interface +public class WindowExample extends Frame implements WindowListener { + +// class constructor + WindowExample() { + + // adding WindowListener to the frame + addWindowListener(this); + // setting the size, layout and visibility of frame + setSize (400, 400); + setLayout (null); + setVisible (true); + } +// main method +public static void main(String[] args) { + new WindowExample(); +} + +// overriding windowActivated() method of WindowListener interface which prints the given string when window is set to be active +public void windowActivated (WindowEvent arg0) { + System.out.println(""activated""); +} + +// overriding windowClosed() method of WindowListener interface which prints the given string when window is closed +public void windowClosed (WindowEvent arg0) { + System.out.println(""closed""); +} + +// overriding windowClosing() method of WindowListener interface which prints the given string when we attempt to close window from system menu +public void windowClosing (WindowEvent arg0) { + System.out.println(""closing""); + dispose(); +} + +// overriding windowDeactivated() method of WindowListener interface which prints the given string when window is not active +public void windowDeactivated (WindowEvent arg0) { + System.out.println(""deactivated""); +} + +// overriding windowDeiconified() method of WindowListener interface which prints the given string when window is modified from minimized to normal state +public void windowDeiconified (WindowEvent arg0) { + System.out.println(""deiconified""); +} + +// overriding windowIconified() method of WindowListener interface which prints the given string when window is modified from normal to minimized state +public void windowIconified(WindowEvent arg0) { + System.out.println(""iconified""); +} + +// overriding windowOpened() method of WindowListener interface which prints the given string when window is first opened +public void windowOpened(WindowEvent arg0) { + System.out.println(""opened""); +} +} " +What is Java Adapter Classes?,"Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class, you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code." +What are the Pros of using Adapter classes?,"It assists the unrelated classes to work combinedly. +It provides ways to use classes in different ways. +It increases the transparency of classes. +It provides a way to include related patterns in the class. +It provides a pluggable kit for developing an application. +It increases the reusability of the class." +What is the list of java.awt.event Adapter classes?,"Adapter class : WindowAdapter +Listener interface : WindowListener +Adapter class : KeyAdapter +Listener interface : KeyListener +Adapter class : MouseAdapter +Listener interface : MouseListener +Adapter class : MouseMotionAdapter +Listener interface : MouseMotionListener +Adapter class : FocusAdapter +Listener interface : FocusListener +Adapter class : ComponentAdapter +Listener interface : ComponentListener +Adapter class : ContainerAdapter +Listener interface : ContainerListener +Adapter class : HierarchyBoundsAdapter +Listener interface : HierarchyBoundsListener +" +What is the list java.awt.dnd Adapter classes?,"Adapter class : DragSourceAdapter +Listener interface : DragSourceListener +Adapter class : DragTargetAdapter +Listener interface : DragTargetListener" +What is the list of javax.swing.event Adapter classes?,"Adapter class : MouseInputAdapter +Listener interface : MouseInputListener +Adapter class : InternalFrameAdapter +Listener interface : InternalFrameListener" +Can you provide a Java WindowAdapter Example?,"// importing the necessary libraries +import java.awt.*; +import java.awt.event.*; + +public class AdapterExample { +// object of Frame + Frame f; +// class constructor + AdapterExample() { +// creating a frame with the title + f = new Frame (""Window Adapter""); +// adding the WindowListener to the frame +// overriding the windowClosing() method + f.addWindowListener (new WindowAdapter() { + public void windowClosing (WindowEvent e) { + f.dispose(); + } + }); + // setting the size, layout and + f.setSize (400, 400); + f.setLayout (null); + f.setVisible (true); + } + +// main method +public static void main(String[] args) { + new AdapterExample(); +} +} " +Can you provide a Java MouseAdapter Example?,"// importing the necessary libraries +import java.awt.*; +import java.awt.event.*; + +// class which inherits the MouseAdapter class +public class MouseAdapterExample extends MouseAdapter { +// object of Frame class + Frame f; +// class constructor + MouseAdapterExample() { +// creating the frame with the title + f = new Frame (""Mouse Adapter""); +// adding MouseListener to the Frame + f.addMouseListener(this); + // setting the size, layout and visibility of the frame + f.setSize (300, 300); + f.setLayout (null); + f.setVisible (true); + } +// overriding the mouseClicked() method of the MouseAdapter class + public void mouseClicked (MouseEvent e) { +// creating the Graphics object and fetching them from the Frame object using getGraphics() method + Graphics g = f.getGraphics(); +// setting the color of graphics object + g.setColor (Color.BLUE); +// setting the shape of graphics object + g.fillOval (e.getX(), e.getY(), 30, 30); + } + // main method +public static void main(String[] args) { + new MouseAdapterExample(); +} +} " +Can you provide a Java MouseMotionAdapter Example?,"// importing the necessary libraries +import java.awt.*; +import java.awt.event.*; +// class which inherits the MouseMotionAdapter class +public class MouseMotionAdapterExample extends MouseMotionAdapter { +// object of Frame class + Frame f; +// class constructor + MouseMotionAdapterExample() { +// creating the frame with the title + f = new Frame (""Mouse Motion Adapter""); +// adding MouseMotionListener to the Frame + f.addMouseMotionListener (this); + // setting the size, layout and visibility of the frame + f.setSize (300, 300); + f.setLayout (null); + f.setVisible (true); + } +// overriding the mouseDragged() method +public void mouseDragged (MouseEvent e) { +// creating the Graphics object and fetching them from the Frame object using getGraphics() method + Graphics g = f.getGraphics(); +// setting the color of graphics object + g.setColor (Color.ORANGE); +// setting the shape of graphics object + g.fillOval (e.getX(), e.getY(), 20, 20); +} +public static void main(String[] args) { + new MouseMotionAdapterExample(); +} +} " +Can you provide a Java KeyAdapter Example?,"// importing the necessary libraries +import java.awt.*; +import java.awt.event.*; +// class which inherits the KeyAdapter class +public class KeyAdapterExample extends KeyAdapter { +// creating objects of Label, TextArea and Frame + Label l; + TextArea area; + Frame f; +// class constructor + KeyAdapterExample() { +// creating the Frame with title + f = new Frame (""Key Adapter""); +// creating the Label + l = new Label(); +// setting the location of label + l.setBounds (20, 50, 200, 20); +// creating the text area + area = new TextArea(); +// setting the location of text area + area.setBounds (20, 80, 300, 300); +// adding KeyListener to text area + area.addKeyListener(this); + // adding the label and text area to frame + f.add(l); +f.add(area); +// setting the size, layout and visibility of frame + f.setSize (400, 400); + f.setLayout (null); + f.setVisible (true); + } +// overriding the keyReleased() method + public void keyReleased (KeyEvent e) { +// creating the String object to get the text fromTextArea + String text = area.getText(); +// splitting the String into words + String words[] = text.split (""\\s""); +// setting the label text to print the number of words and characters of given string + l.setText (""Words: "" + words.length + "" Characters:"" + text.length()); + } + // main method + public static void main(String[] args) { + new KeyAdapterExample(); + } +} " +How to close AWT Window in Java?,We can close the AWT Window or Frame by calling dispose() or System.exit() inside windowClosing() method. The windowClosing() method is found in WindowListener interface and WindowAdapter class. +What are the Different ways to override windowClosing() method?,"By anonymous class +By inheriting WindowAdapter class +By implementing WindowListener interface" +Can you provide a Close AWT Window Example 1: Anonymous class?,"// importing necessary awt libraries +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +// class which inherits the Frame class +public class WindowExample extends Frame { +// class constructor + WindowExample() { +// adding WindowListener to the Frame +// and using the windowClosing() method of WindowAdapter class + addWindowListener (new WindowAdapter() { + public void windowClosing (WindowEvent e) { + dispose(); + } + }); +// setting the size, layout and visibility of frame + setSize (400, 400); + setLayout (null); + setVisible (true); + } +// main method +public static void main (String[] args) { + new WindowExample(); +} " +Can you provide a Close AWT Window Example 2: extending WindowAdapter?,"// importing the necessary libraries +import java.awt.*; +import java.awt.event.*; + +// class which inherits the WindowAdapter class +public class AdapterExample extends WindowAdapter { +// object of Frame + Frame f; +// class constructor + AdapterExample() { +// creating the frame + f = new Frame(); +// adding WindowListener to the frame + f.addWindowListener (this); + +// setting the size, layout and visibility of frame + f.setSize (400, 400); + f.setLayout (null); + f.setVisible (true); + } + +// overriding the windowClosing() method +public void windowClosing (WindowEvent e) { + f.dispose(); +} +// main method +public static void main(String[] args) { + new AdapterExample(); +} +} " +What is the Difference between AWT and Swing?," No.1 Java AWT : AWT components are platform-dependent. +Java Swing: Java swing components are platform-independent. +No.2 Java AWT : AWT components are heavyweight. +Java Swing: Swing components are lightweight. +No.3 Java AWT : AWT doesn't support pluggable look and feel. +Java Swing: Swing supports pluggable look and feel +No.4 Java AWT : AWT provides less components than Swing. +Java Swing: Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc. +No.5 Java AWT : AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. +Java Swing: Swing follows MVC." +What is JFC?,The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications. +What are the Commonly used Methods of Component class?,"Method: public void add(Component c) +Description: add a component on another component. +Method: public void setSize(int width,int height) +Description: sets size of the component. +Method: public void setLayout(LayoutManager m) +Description: sets the layout manager for the component. +Method: public void setVisible(boolean b) +Description: sets the visibility of the component. It is by default false. " +What is Java JButton?,The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class. +What is JButton class declaration?,public class JButton extends AbstractButton implements Accessible +What are the Commonly used Constructors:?,"Constructor: JButton() +Description: It creates a button with no text and icon. +Constructor: JButton(String s) +Description: It creates a button with the specified text. +Constructor: JButton(Icon i) +Description: It creates a button with the specified icon object. " +What are the Commonly used Methods of AbstractButton class?,"Methods: void setText(String s) +Description: It is used to set specified text on button +Methods: String getText() +Description: It is used to return the text of the button. +Methods: void setEnabled(boolean b) +Description: It is used to enable or disable the button. +Methods: void setIcon(Icon b) +Description: It is used to set the specified Icon on the button. +Methods: Icon getIcon() +Description: It is used to get the Icon of the button. +Methods: void setMnemonic(int a) +Description: It is used to set the mnemonic on the button. +Methods: It is used to set the mnemonic on the button. +Description: It is used to add the action listener to this object. " +Can you provide a Java JButton Example?,"import java.awt.event.*; +import javax.swing.*; +public class ButtonExample { +public static void main(String[] args) { + JFrame f=new JFrame(""Button Example""); + final JTextField tf=new JTextField(); + tf.setBounds(50,50, 150,20); + JButton b=new JButton(""Click Here""); + b.setBounds(50,100,95,30); + b.addActionListener(new ActionListener(){ +public void actionPerformed(ActionEvent e){ + tf.setText(""Welcome to Javatpoint.""); + } + }); + f.add(b);f.add(tf); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +} " +Can you provide a Java JButton Example with ActionListener?,"import java.awt.event.*; +import javax.swing.*; +public class ButtonExample { +public static void main(String[] args) { + JFrame f=new JFrame(""Button Example""); + final JTextField tf=new JTextField(); + tf.setBounds(50,50, 150,20); + JButton b=new JButton(""Click Here""); + b.setBounds(50,100,95,30); + b.addActionListener(new ActionListener(){ +public void actionPerformed(ActionEvent e){ + tf.setText(""Welcome to Javatpoint.""); + } + }); + f.add(b);f.add(tf); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +} " +Can you provide an Example of displaying image on the button?,"import javax.swing.*; +public class ButtonExample{ +ButtonExample(){ +JFrame f=new JFrame(""Button Example""); +JButton b=new JButton(new ImageIcon(""D:\\icon.png"")); +b.setBounds(100,100,100, 40); +f.add(b); +f.setSize(300,400); +f.setLayout(null); +f.setVisible(true); +f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } +public static void main(String[] args) { + new ButtonExample(); +} +} " +What is Java JLabel?,The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class. +What is JLabel class declaration?,"public class JLabel extends JComponent implements SwingConstants, Accessible " +Can you provide a Java JLabel Example?,"import javax.swing.*; +class LabelExample +{ +public static void main(String args[]) + { + JFrame f= new JFrame(""Label Example""); + JLabel l1,l2; + l1=new JLabel(""First Label.""); + l1.setBounds(50,50, 100,30); + l2=new JLabel(""Second Label.""); + l2.setBounds(50,100, 100,30); + f.add(l1); f.add(l2); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); + } + } " +Can you provide a Java JLabel Example with ActionListener?,"import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +public class LabelExample extends Frame implements ActionListener{ + JTextField tf; JLabel l; JButton b; + LabelExample(){ + tf=new JTextField(); + tf.setBounds(50,50, 150,20); + l=new JLabel(); + l.setBounds(50,100, 250,20); + b=new JButton(""Find IP""); + b.setBounds(50,150,95,30); + b.addActionListener(this); + add(b);add(tf);add(l); + setSize(400,400); + setLayout(null); + setVisible(true); + } + public void actionPerformed(ActionEvent e) { + try{ + String host=tf.getText(); + String ip=java.net.InetAddress.getByName(host).getHostAddress(); + l.setText(""IP of ""+host+"" is: ""+ip); + }catch(Exception ex){System.out.println(ex);} + } + public static void main(String[] args) { + new LabelExample(); + } } " +What is Java JTextField?,The object of a JTextField class is a text component that allows the editing of a single line text. It inherits JTextComponent class. +What is JTextField class declaration?,public class JTextField extends JTextComponent implements SwingConstants +Can you provide a Java JTextField Example?,"import javax.swing.*; +class TextFieldExample +{ +public static void main(String args[]) + { + JFrame f= new JFrame(""TextField Example""); + JTextField t1,t2; + t1=new JTextField(""Welcome to Javatpoint.""); + t1.setBounds(50,100, 200,30); + t2=new JTextField(""AWT Tutorial""); + t2.setBounds(50,150, 200,30); + f.add(t1); f.add(t2); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } + } " +Can you provide a Java JTextField Example with ActionListener?,"import javax.swing.*; +import java.awt.event.*; +public class TextFieldExample implements ActionListener{ + JTextField tf1,tf2,tf3; + JButton b1,b2; + TextFieldExample(){ + JFrame f= new JFrame(); + tf1=new JTextField(); + tf1.setBounds(50,50,150,20); + tf2=new JTextField(); + tf2.setBounds(50,100,150,20); + tf3=new JTextField(); + tf3.setBounds(50,150,150,20); + tf3.setEditable(false); + b1=new JButton(""+""); + b1.setBounds(50,200,50,50); + b2=new JButton(""-""); + b2.setBounds(120,200,50,50); + b1.addActionListener(this); + b2.addActionListener(this); + f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); + } + public void actionPerformed(ActionEvent e) { + String s1=tf1.getText(); + String s2=tf2.getText(); + int a=Integer.parseInt(s1); + int b=Integer.parseInt(s2); + int c=0; + if(e.getSource()==b1){ + c=a+b; + }else if(e.getSource()==b2){ + c=a-b; + } + String result=String.valueOf(c); + tf3.setText(result); + } +public static void main(String[] args) { + new TextFieldExample(); +} } " +What is Java JTextArea?,The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits JTextComponent class +What is JTextArea class declaration?,public class JTextArea extends JTextComponent +Can you provide a Java JTextArea Example?,"import javax.swing.*; +public class TextAreaExample +{ + TextAreaExample(){ + JFrame f= new JFrame(); + JTextArea area=new JTextArea(""Welcome to javatpoint""); + area.setBounds(10,30, 200,200); + f.add(area); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); + } +public static void main(String args[]) + { + new TextAreaExample(); + }} " +Can you provide a Java JTextArea Example with ActionListener?,"import javax.swing.*; +import java.awt.event.*; +public class TextAreaExample implements ActionListener{ +JLabel l1,l2; +JTextArea area; +JButton b; +TextAreaExample() { + JFrame f= new JFrame(); + l1=new JLabel(); + l1.setBounds(50,25,100,30); + l2=new JLabel(); + l2.setBounds(160,25,100,30); + area=new JTextArea(); + area.setBounds(20,75,250,200); + b=new JButton(""Count Words""); + b.setBounds(100,300,120,30); + b.addActionListener(this); + f.add(l1);f.add(l2);f.add(area);f.add(b); + f.setSize(450,450); + f.setLayout(null); + f.setVisible(true); +} +public void actionPerformed(ActionEvent e){ + String text=area.getText(); + String words[]=text.split(""\\s""); + l1.setText(""Words: ""+words.length); + l2.setText(""Characters: ""+text.length()); +} +public static void main(String[] args) { + new TextAreaExample(); +} +} " +What is JLabel class declaration?,"public class JLabel extends JComponent implements SwingConstants, Accessible " +What is JPasswordField class declaration?,public class JPasswordField extends JTextField +Can you provide a Java JPasswordField Example?,"import javax.swing.*; +public class PasswordFieldExample { + public static void main(String[] args) { + JFrame f=new JFrame(""Password Field Example""); + JPasswordField value = new JPasswordField(); + JLabel l1=new JLabel(""Password:""); + l1.setBounds(20,100, 80,30); + value.setBounds(100,100,100,30); + f.add(value); f.add(l1); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); +} +} " +Can you provide a Java JPasswordField Example with ActionListener?,"import javax.swing.*; +import java.awt.event.*; +public class PasswordFieldExample { + public static void main(String[] args) { + JFrame f=new JFrame(""Password Field Example""); + final JLabel label = new JLabel(); + label.setBounds(20,150, 200,50); + final JPasswordField value = new JPasswordField(); + value.setBounds(100,75,100,30); + JLabel l1=new JLabel(""Username:""); + l1.setBounds(20,20, 80,30); + JLabel l2=new JLabel(""Password:""); + l2.setBounds(20,75, 80,30); + JButton b = new JButton(""Login""); + b.setBounds(100,120, 80,30); + final JTextField text = new JTextField(); + text.setBounds(100,20, 100,30); + f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String data = ""Username "" + text.getText(); + data += "", Password: "" + + new String(value.getPassword()); + label.setText(data); + } + }); +} +} " +What is Java JCheckBox?,"The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from ""on"" to ""off"" or from ""off"" to ""on "".It inherits JToggleButton class." +What is JCheckBox class declaration?,public class JCheckBox extends JToggleButton implements Accessible +Can you provide a Java JCheckBox Example?,"import javax.swing.*; +public class CheckBoxExample +{ + CheckBoxExample(){ + JFrame f= new JFrame(""CheckBox Example""); + JCheckBox checkBox1 = new JCheckBox(""C++""); + checkBox1.setBounds(100,100, 50,50); + JCheckBox checkBox2 = new JCheckBox(""Java"", true); + checkBox2.setBounds(100,150, 50,50); + f.add(checkBox1); + f.add(checkBox2); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } +public static void main(String args[]) + { + new CheckBoxExample(); + }} " +Can you provide a Java JCheckBox Example with ItemListener?,"import javax.swing.*; +import java.awt.event.*; +public class CheckBoxExample +{ + CheckBoxExample(){ + JFrame f= new JFrame(""CheckBox Example""); + final JLabel label = new JLabel(); + label.setHorizontalAlignment(JLabel.CENTER); + label.setSize(400,100); + JCheckBox checkbox1 = new JCheckBox(""C++""); + checkbox1.setBounds(150,100, 50,50); + JCheckBox checkbox2 = new JCheckBox(""Java""); + checkbox2.setBounds(150,150, 50,50); + f.add(checkbox1); f.add(checkbox2); f.add(label); + checkbox1.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + label.setText(""C++ Checkbox: "" + + (e.getStateChange()==1?""checked"":""unchecked"")); + } + }); + checkbox2.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + label.setText(""Java Checkbox: "" + + (e.getStateChange()==1?""checked"":""unchecked"")); + } + }); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } +public static void main(String args[]) +{ + new CheckBoxExample(); +} +} " +What is Java JRadioButton?,"The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options. It is widely used in exam systems or quiz. + +It should be added in ButtonGroup to select one radio button only." +What is JRadioButton class declaration?,public class JRadioButton extends JToggleButton implements Accessible +Can you provide a Java JRadioButton Example?,"import javax.swing.*; +public class RadioButtonExample { +JFrame f; +RadioButtonExample(){ +f=new JFrame(); +JRadioButton r1=new JRadioButton(""A) Male""); +JRadioButton r2=new JRadioButton(""B) Female""); +r1.setBounds(75,50,100,30); +r2.setBounds(75,100,100,30); +ButtonGroup bg=new ButtonGroup(); +bg.add(r1);bg.add(r2); +f.add(r1);f.add(r2); +f.setSize(300,300); +f.setLayout(null); +f.setVisible(true); +} +public static void main(String[] args) { + new RadioButtonExample(); +} +} " +Can you provide a Java JRadioButton Example with ActionListener?,"import javax.swing.*; +import java.awt.event.*; +class RadioButtonExample extends JFrame implements ActionListener{ +JRadioButton rb1,rb2; +JButton b; +RadioButtonExample(){ +rb1=new JRadioButton(""Male""); +rb1.setBounds(100,50,100,30); +rb2=new JRadioButton(""Female""); +rb2.setBounds(100,100,100,30); +ButtonGroup bg=new ButtonGroup(); +bg.add(rb1);bg.add(rb2); +b=new JButton(""click""); +b.setBounds(100,150,80,30); +b.addActionListener(this); +add(rb1);add(rb2);add(b); +setSize(300,300); +setLayout(null); +setVisible(true); +} +public void actionPerformed(ActionEvent e){ +if(rb1.isSelected()){ +JOptionPane.showMessageDialog(this,""You are Male.""); +} +if(rb2.isSelected()){ +JOptionPane.showMessageDialog(this,""You are Female.""); +} +} +public static void main(String args[]){ +new RadioButtonExample(); +}} " +What is Java JComboBox?,The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits JComponent class. +What is JComboBox class declaration?,"public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener, Accessible " +Can you provide an Example of Java JComboBox?,"import javax.swing.*; +public class ComboBoxExample { +JFrame f; +ComboBoxExample(){ + f=new JFrame(""ComboBox Example""); + String country[]={""India"",""Aus"",""U.S.A"",""England"",""Newzealand""}; + JComboBox cb=new JComboBox(country); + cb.setBounds(50, 50,90,20); + f.add(cb); + f.setLayout(null); + f.setSize(400,500); + f.setVisible(true); +} +public static void main(String[] args) { + new ComboBoxExample(); +} +} " +Can you provide a Java JComboBox Example with ActionListener?,"import javax.swing.*; +import java.awt.event.*; +public class ComboBoxExample { +JFrame f; +ComboBoxExample(){ + f=new JFrame(""ComboBox Example""); + final JLabel label = new JLabel(); + label.setHorizontalAlignment(JLabel.CENTER); + label.setSize(400,100); + JButton b=new JButton(""Show""); + b.setBounds(200,100,75,20); + String languages[]={""C"",""C++"",""C#"",""Java"",""PHP""}; + final JComboBox cb=new JComboBox(languages); + cb.setBounds(50, 100,90,20); + f.add(cb); f.add(label); f.add(b); + f.setLayout(null); + f.setSize(350,350); + f.setVisible(true); + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { +String data = ""Programming language Selected: "" + + cb.getItemAt(cb.getSelectedIndex()); +label.setText(data); +} +}); +} +public static void main(String[] args) { + new ComboBoxExample(); +} +} " +What is Java JTable?,The JTable class is used to display data in tabular form. It is composed of rows and columns. +What is JTable class declaration?,"Constructor: JTable() +Description: Creates a table with empty cells. +Constructor: JTable(Object[][] rows, Object[] columns) +Description: Creates a table with the specified data. " +"Can you provide an example of Java JTable? +","import javax.swing.*; +public class TableExample { + JFrame f; + TableExample(){ + f=new JFrame(); + String data[][]={ {""101"",""Amit"",""670000""}, + {""102"",""Jai"",""780000""}, + {""101"",""Sachin"",""700000""}}; + String column[]={""ID"",""NAME"",""SALARY""}; + JTable jt=new JTable(data,column); + jt.setBounds(30,40,200,300); + JScrollPane sp=new JScrollPane(jt); + f.add(sp); + f.setSize(300,400); + f.setVisible(true); +} +public static void main(String[] args) { + new TableExample(); +} +} " +Java JTable Example with ListSelectionListener,"import javax.swing.*; +import javax.swing.event.*; +public class TableExample { + public static void main(String[] a) { + JFrame f = new JFrame(""Table Example""); + String data[][]={ {""101"",""Amit"",""670000""}, + {""102"",""Jai"",""780000""}, + {""101"",""Sachin"",""700000""}}; + String column[]={""ID"",""NAME"",""SALARY""}; + final JTable jt=new JTable(data,column); + jt.setCellSelectionEnabled(true); + ListSelectionModel select= jt.getSelectionModel(); + select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + select.addListSelectionListener(new ListSelectionListener() { + public void valueChanged(ListSelectionEvent e) { + String Data = null; + int[] row = jt.getSelectedRows(); + int[] columns = jt.getSelectedColumns(); + for (int i = 0; i < row.length; i++) { + for (int j = 0; j < columns.length; j++) { + Data = (String) jt.getValueAt(row[i], columns[j]); + } } + System.out.println(""Table element selected is: "" + Data); + } + }); + JScrollPane sp=new JScrollPane(jt); + f.add(sp); + f.setSize(300, 200); + f.setVisible(true); + } + } " +What is Java JList?,The object of JList class represents a list of text items. The list of text items can be set up so that the user can choose either one item or multiple items. It inherits JComponent class. +What is JList class declaration?,"public class JList extends JComponent implements Scrollable, Accessible " +Can you provide an example of Java JList?,"import javax.swing.*; +public class ListExample +{ + ListExample(){ + JFrame f= new JFrame(); + DefaultListModel l1 = new DefaultListModel<>(); + l1.addElement(""Item1""); + l1.addElement(""Item2""); + l1.addElement(""Item3""); + l1.addElement(""Item4""); + JList list = new JList<>(l1); + list.setBounds(100,100, 75,75); + f.add(list); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } +public static void main(String args[]) + { + new ListExample(); + }} " +Can you provid a Java JList Example with ActionListener?,"import javax.swing.*; +import java.awt.event.*; +public class ListExample +{ + ListExample(){ + JFrame f= new JFrame(); + final JLabel label = new JLabel(); + label.setSize(500,100); + JButton b=new JButton(""Show""); + b.setBounds(200,150,80,30); + final DefaultListModel l1 = new DefaultListModel<>(); + l1.addElement(""C""); + l1.addElement(""C++""); + l1.addElement(""Java""); + l1.addElement(""PHP""); + final JList list1 = new JList<>(l1); + list1.setBounds(100,100, 75,75); + DefaultListModel l2 = new DefaultListModel<>(); + l2.addElement(""Turbo C++""); + l2.addElement(""Struts""); + l2.addElement(""Spring""); + l2.addElement(""YII""); + final JList list2 = new JList<>(l2); + list2.setBounds(100,200, 75,75); + f.add(list1); f.add(list2); f.add(b); f.add(label); + f.setSize(450,450); + f.setLayout(null); + f.setVisible(true); + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String data = """"; + if (list1.getSelectedIndex() != -1) { + data = ""Programming language Selected: "" + list1.getSelectedValue(); + label.setText(data); + } + if(list2.getSelectedIndex() != -1){ + data += "", FrameWork Selected: ""; + for(Object frame :list2.getSelectedValues()){ + data += frame + "" ""; + } + } + label.setText(data); + } + }); + } +public static void main(String args[]) + { + new ListExample(); + }} " +What is Java JOptionPane?,"The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits JComponent class." +Can you provide an example of JOptionPane class declaration?,public class JOptionPane extends JComponent implements Accessible +Can you provide an example of Java JOptionPane: showMessageDialog()?,"import javax.swing.*; +public class OptionPaneExample { +JFrame f; +OptionPaneExample(){ + f=new JFrame(); + JOptionPane.showMessageDialog(f,""Hello, Welcome to Javatpoint.""); +} +public static void main(String[] args) { + new OptionPaneExample(); +} +} " +Can you provide an example of Java JOptionPane: showInputDialog()?,"import javax.swing.*; +public class OptionPaneExample { +JFrame f; +OptionPaneExample(){ + f=new JFrame(); + String name=JOptionPane.showInputDialog(f,""Enter Name""); +} +public static void main(String[] args) { + new OptionPaneExample(); +} +} " +Can you provide an example of Java JOptionPane showConfirmDialog()?,"import javax.swing.*; +import java.awt.event.*; +public class OptionPaneExample extends WindowAdapter{ +JFrame f; +OptionPaneExample(){ + f=new JFrame(); + f.addWindowListener(this); + f.setSize(300, 300); + f.setLayout(null); + f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); + f.setVisible(true); +} +public void windowClosing(WindowEvent e) { + int a=JOptionPane.showConfirmDialog(f,""Are you sure?""); +if(a==JOptionPane.YES_OPTION){ + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); +} +} +public static void main(String[] args) { + new OptionPaneExample(); +} +} " +What is Java JScrollBar?,The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a scrollbar. It inherits JComponent class. +What is JScrollBar class declaration?,"public class JScrollBar extends JComponent implements Adjustable, Accessible " +Can you provide an example of Java JScrollBar?,"import javax.swing.*; +class ScrollBarExample +{ +ScrollBarExample(){ + JFrame f= new JFrame(""Scrollbar Example""); + JScrollBar s=new JScrollBar(); +s.setBounds(100,100, 50,100); +f.add(s); +f.setSize(400,400); +f.setLayout(null); +f.setVisible(true); +} +public static void main(String args[]) +{ +new ScrollBarExample(); +}} " +Can you provide an example of Java JScrollBar with AdjustmentListener,"import javax.swing.*; +import java.awt.event.*; +class ScrollBarExample +{ +ScrollBarExample(){ + JFrame f= new JFrame(""Scrollbar Example""); + final JLabel label = new JLabel(); + label.setHorizontalAlignment(JLabel.CENTER); + label.setSize(400,100); + final JScrollBar s=new JScrollBar(); + s.setBounds(100,100, 50,100); + f.add(s); f.add(label); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + s.addAdjustmentListener(new AdjustmentListener() { + public void adjustmentValueChanged(AdjustmentEvent e) { + label.setText(""Vertical Scrollbar value is:""+ s.getValue()); + } + }); +} +public static void main(String args[]) +{ + new ScrollBarExample(); +}} " +"What are the Java JMenuBar, JMenu and JMenuItem?","The JMenuBar class is used to display menubar on the window or frame. It may have several menus. + +The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the JMenuItem class. + +The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the JMenuItem or any of its subclass." +What is JMenu class declaration?,"public class JMenu extends JMenuItem implements MenuElement, Accessible " +What is JMenuItem class declaration?,"public class JMenuItem extends AbstractButton implements Accessible, MenuElement " +Can you provide an example of Java JMenuItem and JMenu?,"import javax.swing.*; +class MenuExample +{ + JMenu menu, submenu; + JMenuItem i1, i2, i3, i4, i5; + MenuExample(){ + JFrame f= new JFrame(""Menu and MenuItem Example""); + JMenuBar mb=new JMenuBar(); + menu=new JMenu(""Menu""); + submenu=new JMenu(""Sub Menu""); + i1=new JMenuItem(""Item 1""); + i2=new JMenuItem(""Item 2""); + i3=new JMenuItem(""Item 3""); + i4=new JMenuItem(""Item 4""); + i5=new JMenuItem(""Item 5""); + menu.add(i1); menu.add(i2); menu.add(i3); + submenu.add(i4); submenu.add(i5); + menu.add(submenu); + mb.add(menu); + f.setJMenuBar(mb); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +public static void main(String args[]) +{ +new MenuExample(); +}} " +Can you provided an Example of creating Edit menu for Notepad?,"import javax.swing.*; +import java.awt.event.*; +public class MenuExample implements ActionListener{ +JFrame f; +JMenuBar mb; +JMenu file,edit,help; +JMenuItem cut,copy,paste,selectAll; +JTextArea ta; +MenuExample(){ +f=new JFrame(); +cut=new JMenuItem(""cut""); +copy=new JMenuItem(""copy""); +paste=new JMenuItem(""paste""); +selectAll=new JMenuItem(""selectAll""); +cut.addActionListener(this); +copy.addActionListener(this); +paste.addActionListener(this); +selectAll.addActionListener(this); +mb=new JMenuBar(); +file=new JMenu(""File""); +edit=new JMenu(""Edit""); +help=new JMenu(""Help""); +edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll); +mb.add(file);mb.add(edit);mb.add(help); +ta=new JTextArea(); +ta.setBounds(5,5,360,320); +f.add(mb);f.add(ta); +f.setJMenuBar(mb); +f.setLayout(null); +f.setSize(400,400); +f.setVisible(true); +} +public void actionPerformed(ActionEvent e) { +if(e.getSource()==cut) +ta.cut(); +if(e.getSource()==paste) +ta.paste(); +if(e.getSource()==copy) +ta.copy(); +if(e.getSource()==selectAll) +ta.selectAll(); +} +public static void main(String[] args) { + new MenuExample(); +} +} " +What is Java JPopupMenu?,PopupMenu can be dynamically popped up at specific position within a component. It inherits the JComponent class. +What is JPopupMenu class declaration?,"public class JPopupMenu extends JComponent implements Accessible, MenuElement " +Can you provide an example of Java JPopupMenu?,"import javax.swing.*; +import java.awt.event.*; +class PopupMenuExample +{ + PopupMenuExample(){ + final JFrame f= new JFrame(""PopupMenu Example""); + final JPopupMenu popupmenu = new JPopupMenu(""Edit""); + JMenuItem cut = new JMenuItem(""Cut""); + JMenuItem copy = new JMenuItem(""Copy""); + JMenuItem paste = new JMenuItem(""Paste""); + popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste); + f.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + popupmenu.show(f , e.getX(), e.getY()); + } + }); + f.add(popupmenu); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); + } +public static void main(String args[]) +{ + new PopupMenuExample(); +}} " +Can you provide an example Java JPopupMenu with MouseListener and ActionListener?,"import javax.swing.*; +import java.awt.event.*; +class PopupMenuExample +{ + PopupMenuExample(){ + final JFrame f= new JFrame(""PopupMenu Example""); + final JLabel label = new JLabel(); + label.setHorizontalAlignment(JLabel.CENTER); + label.setSize(400,100); + final JPopupMenu popupmenu = new JPopupMenu(""Edit""); + JMenuItem cut = new JMenuItem(""Cut""); + JMenuItem copy = new JMenuItem(""Copy""); + JMenuItem paste = new JMenuItem(""Paste""); + popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste); + f.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + popupmenu.show(f , e.getX(), e.getY()); + } + }); + cut.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + label.setText(""cut MenuItem clicked.""); + } + }); + copy.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + label.setText(""copy MenuItem clicked.""); + } + }); + paste.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + label.setText(""paste MenuItem clicked.""); + } + }); + f.add(label); f.add(popupmenu); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } +public static void main(String args[]) +{ + new PopupMenuExample(); +} +} " +What is Java JCheckBoxMenuItem?,"JCheckBoxMenuItem class represents checkbox which can be included on a menu . A CheckBoxMenuItem can have text or a graphic icon or both, associated with it. MenuItem can be selected or deselected. MenuItems can be configured and controlled by actions." +Can you provide a Java JCheckBoxMenuItem Example?,"import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import javax.swing.AbstractButton; +import javax.swing.Icon; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; + +public class JavaCheckBoxMenuItem { + public static void main(final String args[]) { + JFrame frame = new JFrame(""Jmenu Example""); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JMenuBar menuBar = new JMenuBar(); + // File Menu, F - Mnemonic + JMenu fileMenu = new JMenu(""File""); + fileMenu.setMnemonic(KeyEvent.VK_F); + menuBar.add(fileMenu); + // File->New, N - Mnemonic + JMenuItem menuItem1 = new JMenuItem(""Open"", KeyEvent.VK_N); + fileMenu.add(menuItem1); + + JCheckBoxMenuItem caseMenuItem = new JCheckBoxMenuItem(""Option_1""); + caseMenuItem.setMnemonic(KeyEvent.VK_C); + fileMenu.add(caseMenuItem); + + ActionListener aListener = new ActionListener() { + public void actionPerformed(ActionEvent event) { + AbstractButton aButton = (AbstractButton) event.getSource(); + boolean selected = aButton.getModel().isSelected(); + String newLabel; + Icon newIcon; + if (selected) { + newLabel = ""Value-1""; + } else { + newLabel = ""Value-2""; + } + aButton.setText(newLabel); + } + }; + + caseMenuItem.addActionListener(aListener); + frame.setJMenuBar(menuBar); + frame.setSize(350, 250); + frame.setVisible(true); + } +} " +What is Java JSeparator?,"The object of JSeparator class is used to provide a general purpose component for implementing divider lines. It is used to draw a line to separate widgets in a Layout. It inherits JComponent class. +" +What is JSeparator class declaration?,"public class JSeparator extends JComponent implements SwingConstants, Accessible " +Can you provide an example of Java JSeparator?,"import javax.swing.*; +class SeparatorExample +{ + JMenu menu, submenu; + JMenuItem i1, i2, i3, i4, i5; + SeparatorExample() { + JFrame f= new JFrame(""Separator Example""); + JMenuBar mb=new JMenuBar(); + menu=new JMenu(""Menu""); + i1=new JMenuItem(""Item 1""); + i2=new JMenuItem(""Item 2""); + menu.add(i1); + menu.addSeparator(); + menu.add(i2); + mb.add(menu); + f.setJMenuBar(mb); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +public static void main(String args[]) +{ +new SeparatorExample(); +}} " +What is Java JProgressBar?,The JProgressBar class is used to display the progress of the task. It inherits JComponent class. +What is JProgressBar class declaration?,"public class JProgressBar extends JComponent implements SwingConstants, Accessible " +Can you provide an example of Java JProgressBar?,"import javax.swing.*; +public class ProgressBarExample extends JFrame{ +JProgressBar jb; +int i=0,num=0; +ProgressBarExample(){ +jb=new JProgressBar(0,2000); +jb.setBounds(40,40,160,30); +jb.setValue(0); +jb.setStringPainted(true); +add(jb); +setSize(250,150); +setLayout(null); +} +public void iterate(){ +while(i<=2000){ + jb.setValue(i); + i=i+20; + try{Thread.sleep(150);}catch(Exception e){} +} +} +public static void main(String[] args) { + ProgressBarExample m=new ProgressBarExample(); + m.setVisible(true); + m.iterate(); +} +} " +What is Java JTree?,The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex component. It has a 'root node' at the top most which is a parent for all nodes in the tree. It inherits JComponent class. +What is JTree class declaration?,"public class JTree extends JComponent implements Scrollable, Accessible " +Can you provide an example of Java JTree?,"import javax.swing.*; +import javax.swing.tree.DefaultMutableTreeNode; +public class TreeExample { +JFrame f; +TreeExample(){ + f=new JFrame(); + DefaultMutableTreeNode style=new DefaultMutableTreeNode(""Style""); + DefaultMutableTreeNode color=new DefaultMutableTreeNode(""color""); + DefaultMutableTreeNode font=new DefaultMutableTreeNode(""font""); + style.add(color); + style.add(font); + DefaultMutableTreeNode red=new DefaultMutableTreeNode(""red""); + DefaultMutableTreeNode blue=new DefaultMutableTreeNode(""blue""); + DefaultMutableTreeNode black=new DefaultMutableTreeNode(""black""); + DefaultMutableTreeNode green=new DefaultMutableTreeNode(""green""); + color.add(red); color.add(blue); color.add(black); color.add(green); + JTree jt=new JTree(style); + f.add(jt); + f.setSize(200,200); + f.setVisible(true); +} +public static void main(String[] args) { + new TreeExample(); +}} " +What is Java JColorChooser?,The JColorChooser class is used to create a color chooser dialog box so that user can select any color. It inherits JComponent class. +What is JColorChooser class declaration?,public class JColorChooser extends JComponent implements Accessible +Can you provide an example of Java JColorChooser?,"import java.awt.event.*; +import java.awt.*; +import javax.swing.*; +public class ColorChooserExample extends JFrame implements ActionListener { +JButton b; +Container c; +ColorChooserExample(){ + c=getContentPane(); + c.setLayout(new FlowLayout()); + b=new JButton(""color""); + b.addActionListener(this); + c.add(b); +} +public void actionPerformed(ActionEvent e) { +Color initialcolor=Color.RED; +Color color=JColorChooser.showDialog(this,""Select a color"",initialcolor); +c.setBackground(color); +} + +public static void main(String[] args) { + ColorChooserExample ch=new ColorChooserExample(); + ch.setSize(400,400); + ch.setVisible(true); + ch.setDefaultCloseOperation(EXIT_ON_CLOSE); +} +} " +Can you provide an example in Java JColorChooser with ActionListener?,"import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +public class ColorChooserExample extends JFrame implements ActionListener{ +JFrame f; +JButton b; +JTextArea ta; +ColorChooserExample(){ + f=new JFrame(""Color Chooser Example.""); + b=new JButton(""Pad Color""); + b.setBounds(200,250,100,30); + ta=new JTextArea(); + ta.setBounds(10,10,300,200); + b.addActionListener(this); + f.add(b);f.add(ta); + f.setLayout(null); + f.setSize(400,400); + f.setVisible(true); +} +public void actionPerformed(ActionEvent e){ + Color c=JColorChooser.showDialog(this,""Choose"",Color.CYAN); + ta.setBackground(c); +} +public static void main(String[] args) { + new ColorChooserExample(); +} +} " +What is Java JTabbedPane?,The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It inherits JComponent class. +What is JTabbedPane class declaration?,"public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants " +Can you provide an example Java JTabbedPane?,"import javax.swing.*; +public class TabbedPaneExample { +JFrame f; +TabbedPaneExample(){ + f=new JFrame(); + JTextArea ta=new JTextArea(200,200); + JPanel p1=new JPanel(); + p1.add(ta); + JPanel p2=new JPanel(); + JPanel p3=new JPanel(); + JTabbedPane tp=new JTabbedPane(); + tp.setBounds(50,50,200,200); + tp.add(""main"",p1); + tp.add(""visit"",p2); + tp.add(""help"",p3); + f.add(tp); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); +} +public static void main(String[] args) { + new TabbedPaneExample(); +}} " +What is Java JSlider?,"The Java JSlider class is used to create the slider. By using JSlider, a user can select a value from a specific range." +Can you provide an example of Java JSlider?,"import javax.swing.*; +public class SliderExample1 extends JFrame{ +public SliderExample1() { +JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25); +JPanel panel=new JPanel(); +panel.add(slider); +add(panel); +} + +public static void main(String s[]) { +SliderExample1 frame=new SliderExample1(); +frame.pack(); +frame.setVisible(true); +} +} " +Can you provide an example of Java JSlider: painting ticks?,"import javax.swing.*; +public class SliderExample extends JFrame{ +public SliderExample() { +JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25); +slider.setMinorTickSpacing(2); +slider.setMajorTickSpacing(10); +slider.setPaintTicks(true); +slider.setPaintLabels(true); + +JPanel panel=new JPanel(); +panel.add(slider); +add(panel); +} +public static void main(String s[]) { +SliderExample frame=new SliderExample(); +frame.pack(); +frame.setVisible(true); +} +} " +What is Java JSpinner?,The object of JSpinner class is a single line input field that allows the user to select a number or an object value from an ordered sequence. +What is JSpinner class declaration?,public class JSpinner extends JComponent implements Accessible +Can you provide an example of Java JSpinner?,"import javax.swing.*; +public class SpinnerExample { + public static void main(String[] args) { + JFrame f=new JFrame(""Spinner Example""); + SpinnerModel value = + new SpinnerNumberModel(5, //initial value + 0, //minimum value + 10, //maximum value + 1); //step + JSpinner spinner = new JSpinner(value); + spinner.setBounds(100,100,50,30); + f.add(spinner); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); +} +} " +Can you provide an example of Java JSpinner with ChangeListener?,"import javax.swing.*; +import javax.swing.event.*; +public class SpinnerExample { + public static void main(String[] args) { + JFrame f=new JFrame(""Spinner Example""); + final JLabel label = new JLabel(); + label.setHorizontalAlignment(JLabel.CENTER); + label.setSize(250,100); + SpinnerModel value = + new SpinnerNumberModel(5, //initial value + 0, //minimum value + 10, //maximum value + 1); //step + JSpinner spinner = new JSpinner(value); + spinner.setBounds(100,100,50,30); + f.add(spinner); f.add(label); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); + spinner.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { + label.setText(""Value : "" + ((JSpinner)e.getSource()).getValue()); + } + }); +} +} " +What is Java JDialog?,"The JDialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Dialog class. + +Unlike JFrame, it doesn't have maximize and minimize buttons." +What is JDialog class declaration?,"public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer " +Can you provide an example of Java JDialog?,"import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +public class DialogExample { + private static JDialog d; + DialogExample() { + JFrame f= new JFrame(); + d = new JDialog(f , ""Dialog Example"", true); + d.setLayout( new FlowLayout() ); + JButton b = new JButton (""OK""); + b.addActionListener ( new ActionListener() + { + public void actionPerformed( ActionEvent e ) + { + DialogExample.d.setVisible(false); + } + }); + d.add( new JLabel (""Click button to continue."")); + d.add(b); + d.setSize(300,300); + d.setVisible(true); + } + public static void main(String args[]) + { + new DialogExample(); + } +} " +What is Java JPanel?,"The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class. + +It doesn't have title bar." +What is JPanel class declaration?,public class JPanel extends JComponent implements Accessible +Can you provide an example of Java JPanel?,"import java.awt.*; +import javax.swing.*; +public class PanelExample { + PanelExample() + { + JFrame f= new JFrame(""Panel Example""); + JPanel panel=new JPanel(); + panel.setBounds(40,80,200,200); + panel.setBackground(Color.gray); + JButton b1=new JButton(""Button 1""); + b1.setBounds(50,100,80,30); + b1.setBackground(Color.yellow); + JButton b2=new JButton(""Button 2""); + b2.setBounds(100,100,80,30); + b2.setBackground(Color.green); + panel.add(b1); panel.add(b2); + f.add(panel); + f.setSize(400,400); + f.setLayout(null); + f.setVisible(true); + } + public static void main(String args[]) + { + new PanelExample(); + } + } " +What is Java JFileChooser?,"JFileChooser is a class that is present in the java Swing package. The java Swing package is essential for JavaTM Foundation Classes(JFC). JFileChooser contains many elements that assist in building a graphical user Interface in java. Java Swing gives components like buttons, panels, dialogs, etc. JFileChooser is a simple and successful method for inciting the client to pick a file or a directory. JFileChooser inherited the properties of JComponent class and implemented them with an Accessible interface." +Can you provide an example of Constructors Present in Java JFileChooser Class?,"1. JFileChooser(): + +Constructs a JFileChooser highlighting the client's default directory. + +Example program on JFileChooser() + +// program to demonstrate the JFileChooser() constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ +public static void main(String[] args) { + // creating object to the JFileChooser class + JFileChooserjf = new JFileChooser(); // default constructor JFileChooser is called. + jf.showSaveDialog(null); + } +} " +What is JFileChooser():?,"Constructs a JFileChooser highlighting the client's default directory. + +Example program on JFileChooser() + +// program to demonstrate the JFileChooser() constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ +public static void main(String[] args) { + // creating object to the JFileChooser class + JFileChooserjf = new JFileChooser(); // default constructor JFileChooser is called. + jf.showSaveDialog(null); + } +} " +Can you provide an example ofJFileChooser(File currentDirectory):?,"Constructs a JFileChooser involving the given File as the way. + +Example program on JFileChooser(File currentDirectory) + +// program to demonstrate the JFileChooser(File currentDirectory) constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ +public static void main(String[] args) { + // creating object to the JFileChooser class + JFileChooserjf = new JFileChooser(""c:""); // parameterised constructor JFileChooser( File currentDirectory) is called. + jf.showSaveDialog(null); // opening the saved dialogue + } +} ." +"Can you provide an example of JFileChooser(File currentDirectory, FileSystemViewfsv):?","Constructs a JFileChooser utilizing the given current catalog and FileSystemView. + +Example program on JFileChooser(File currentDirectory, FileSystemViewfsv) + +// program to demonstrate the JFileChooser(File currentDirectory, FileSystemViewfsv) constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ +public static void main(String[] args) { + // creating object to the JFileChooser class + JFileChooserjf = new JFileChooser(""c:"", FileSystemView.getFileSystemView()); // parameterised constructor JFileChooser(File currentDirectory, FileSystemViewfsv) is called. + jf.showSaveDialog(null); // opening the saved dialogue + } +} " +Can you provide an example of JFileChooser(FileSystemViewfsv):?,"Constructs a JFileChooser utilizing the given FileSystemView. + +Example program on JFileChooser(FileSystemViewfsv) + +// program to demonstrate the JFileChooser(FileSystemViewfsv) constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ +public static void main(String[] args) { + // creating object to the JFileChooser class + JFileChooserjf = new JFileChooser(FileSystemView.getFileSystemView()); // parameterised constructor JFileChooser(FileSystemViewfsv) is called. + jf.showSaveDialog(null); // opening the saved dialogue + } +} " +Can you provide an example of JFileChooser(String currentDirectoryPath):?,"Constructs a JFileChooser utilizing the given way. + +Example program on JFileChooser(String currentDirectoryPath): + +// program to demonstrate the JFileChooser(String currentDirectoryPath) constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ +public static void main(String[] args) { + // creating object to the JFileChooser class + JFileChooserjf = new JFileChooser(""C:\Altaf zameer""); // parameterised constructor JFileChooser(string current DirectoryPath) is called. + jf.showSaveDialog(null); // opening the saved dialogue + } +} " +"Can you provide an example of JFileChooser(String currentDirectoryPath, FileSystemViewfsv):?","Constructs a JFileChooser utilizing the given current catalog way and FileSystemView. + +Example program on JFileChooser( String currentDirectoryPath, FileSystemViewfsv ): + +// program to demonstrate the JFileChooser( String currentDirectoryPath, FileSystemViewfsv ) constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ + public static void main(String[] args) { + // creating object to the JFileChooser class +JFileChooserjf = new JFileChooser(""C:"", FileSystemView.getFileSystemView());// parameterised constructor JFileChooser( String currentDirectoryPath, FileSystemViewfsv ) is called. +jf.showSaveDialog(null); // opening the saved dialogue + } +} " +Can you provide an example of JFileChooser( File ):?,"Example program on JFileChooser( File ) constructor: + +// program to demonstrate the JFileChooser( file ) constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ +public static void main(String[] args) { + // creating object to the JFileChooser class + JFileChooserjf = new JFileChooser(new File("" C:\\Users ""));// parameterised constructor JFileChooser( file ) is called. + jf.showSaveDialog(null); // opening the saved dialogue + } +} " +"Can you provide an example of JFileChooser(File, FileSystemView):?","Example on JFileChooser( File, FileSystemView ) + +// program to demonstrate the JFileChooser( file, FileSystemView ) constructor +// importing the required packages +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld +{ +public static void main(String[] args) { + // creating object to the JFileChooser class + // File class + File f = new File(""C:\\Altafzameer\\""); + JFileChooserjf = new JFileChooser(f, FileSystemView.getFileSystemView());// parameterised constructor JFileChooser( file ) is called. + jf.showSaveDialog(null); // opening the saved dialogue + } +} " +"What are the Advantages of JFileChooser()? +","1.Statement of the JFileChooser() beyond the occasion audience additionally can be used within the occasion audience. +2.JFileChooser return esteem, which portrays regardless of whether the record has been picked. +3.Boundary given to the accompanying strategy for JFileChooser can confine clients effectively to choose either record or envelope or both. +4.The JFileChooser() declaration made external to the event listener can moreover be utilized inside the event listener. +5.The JFileChooser return result shows whether the file has been chosen. +6.The accompanying JFileChooser technique's boundary permits clients to handily be limited from choosing either a file, a folder, or both." +Can you give me Methods in JFileChooser Class?,"The JFileChooser class fundamentally gives three strategies that show the record chooser discoursed, as in the accompanying:" +what is showOpenDialog(component owner ):?,"1. showOpenDialog(component owner ): This technique opens an exchange box that contains an endorsement button, as such, ""Open"", that opens a document from the discourse. + +Syntax: + +intshowOpenDialog(component proprietor); " +What is showSaveDialog( component owner ):?,"2. showSaveDialog( component owner ): This strategy is utilized when the client needs to save the particular document that he/she is utilizing. This exchange box contains an endorsement button, as such, ""Save"", to save the document. + +Syntax: + +intshowSaveDialog(component proprietor); " +"What is showDialog(component owner, string):?","3. showDialog(component owner, string): This technique shows an exchange box with an endorsement button which is client characterized. + +Syntax: + +intshowDialog(component owner,string); " +What is getSelectedFile(): ?,"4. getSelectedFile(): This technique returns the document that is chosen by the client. + +Syntax: + +filegetSelectedFile(); " +What is setCurrentDirectory(File f):?,"5. setCurrentDirectory(File f): This technique sets the ongoing catalog as determined. + +Syntax: + +voidsetCurrentDirectory(File f); " +What is getCurrentDirectory()?,"6. getCurrentDirectory(): This technique for JFileChooser returns the ongoing index as chosen by the client. + +Syntax: + +filegetCurrentDirectory(); " +What is (File f)?,"7. (File f):This strategy returns the name of the document as given by the record contention. + +Syntax: + +String getName(File f); " +Can you provide an example of the program to create a JFrame window:?,"A example program to create a JFrame window: + +// java program to create the frame and perform the action in that +// importing the required packages and classes +import java.io.*; +importjavax.swing.*; +importjava.awt.event.*; +importjavax.swing.filechooser.*; +classHelloWorld extends JFrame implements ActionListener { + + // declaring a Jlable to show the files whichare selected by the user + staticJLabel l; + + // a default constructor + HelloWorld() + { + } + + public static void main(String args[]) + { + // // creating an object to the Jframe class and giving the name of the frame + JFrame f = new JFrame("" JavaTpoint""); + + // fixing the size of the frame + f.setSize(400, 400); + + // giving the frame visibility + f.setVisible(true); + + // closing the frame + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + // creating a JButton to save the dialog + JButton b1 = new JButton(""save dialog""); + + // creating a JButton to open the dialog + JButton b2 = new JButton(""open dialog""); + + // creating an object to the HelloWorld class + HelloWorld f1 = new HelloWorld(); + + // Using action listener class to capture the response of the user using buttons + b1.addActionListener(f1); // adding b1 button in actionListener + b2.addActionListener(f1); // adding b2 button in actionListener + + // Creating a panel to add buttons and labels + JPanel p = new JPanel(); + + // adding buttons to the frame + p.add(b1); + p.add(b2); + + // set the label to its initial value + l = new JLabel(""no file selected""); + + // adding the panel to the frame + p.add(l); + f.add(p); + + f.show(); + } + public void actionPerformed(ActionEvent e) + { + // if the client presses the save button, show the save dialog + String com = e.getActionCommand(); + + if (com.equals(""save"")) { + // creating an object to the JFileChooser class + JFileChooserjf = new JFileChooser(FileSystemView.getFileSystemView()); + + // calling the showsSaveDialog method to display the save dialog on the frame + int r = jf.showSaveDialog(null); + + // if the user selects a file + if (r == JFileChooser.APPROVE_OPTION) + + { + // setting the label as the path of the selected file + l.setText(jf.getSelectedFile().getAbsolutePath()); + } + // if the user canceled the operation + else + l.setText(""The user cancelled the operation""); + } + + // if the user presses the open dialog, show the open dialog + else { + // create an object of JFileChooser class + JFileChooserjf = new JFileChooser(FileSystemView.getFileSystemView()); + + // calling the showOpenDialog method to display the save dialog on the frame + int r = jf.showOpenDialog(null); + + // if the user selects a file + if (r == JFileChooser.APPROVE_OPTION) + + { + // setting the label as the path of the selected file + l.setText(jf.getSelectedFile().getAbsolutePath()); + } + // if the user canceled the operation + else + l.setText(""The user cancelled the operation""); + } + } +} " +What is Java JToggleButton?,"JToggleButton is used to create toggle button, it is two-states button to switch on or off." +Can you provide an example of JToggleButton ?,"import java.awt.FlowLayout; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import javax.swing.JFrame; +import javax.swing.JToggleButton; + +public class JToggleButtonExample extends JFrame implements ItemListener { + public static void main(String[] args) { + new JToggleButtonExample(); + } + private JToggleButton button; + JToggleButtonExample() { + setTitle(""JToggleButton with ItemListener Example""); + setLayout(new FlowLayout()); + setJToggleButton(); + setAction(); + setSize(200, 200); + setVisible(true); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + private void setJToggleButton() { + button = new JToggleButton(""ON""); + add(button); + } + private void setAction() { + button.addItemListener(this); + } + public void itemStateChanged(ItemEvent eve) { + if (button.isSelected()) + button.setText(""OFF""); + else + button.setText(""ON""); + } +} " +What is Java JToolBar?,"JToolBar container allows us to group other components, usually buttons with icons in a row or column. JToolBar provides a component which is useful for displaying commonly used actions or controls." +Can you provide an example of Java JToolBar?,"import java.awt.BorderLayout; +import java.awt.Container; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JToolBar; + +public class JToolBarExample { + public static void main(final String args[]) { + JFrame myframe = new JFrame(""JToolBar Example""); + myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JToolBar toolbar = new JToolBar(); + toolbar.setRollover(true); + JButton button = new JButton(""File""); + toolbar.add(button); + toolbar.addSeparator(); + toolbar.add(new JButton(""Edit"")); + toolbar.add(new JComboBox(new String[] { ""Opt-1"", ""Opt-2"", ""Opt-3"", ""Opt-4"" })); + Container contentPane = myframe.getContentPane(); + contentPane.add(toolbar, BorderLayout.NORTH); + JTextArea textArea = new JTextArea(); + JScrollPane mypane = new JScrollPane(textArea); + contentPane.add(mypane, BorderLayout.EAST); + myframe.setSize(450, 250); + myframe.setVisible(true); + } +} " +What is Java JViewport?,"The JViewport class is used to implement scrolling. JViewport is designed to support both logical scrolling and pixel-based scrolling. The viewport's child, called the view, is scrolled by calling the JViewport.setViewPosition() method." +Can you provide an example of JViewport?,"import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.border.LineBorder; +public class ViewPortClass2 { + public static void main(String[] args) { + JFrame frame = new JFrame(""Tabbed Pane Sample""); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JLabel label = new JLabel(""Label""); + label.setPreferredSize(new Dimension(1000, 1000)); + JScrollPane jScrollPane = new JScrollPane(label); + + JButton jButton1 = new JButton(); + jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + jScrollPane.setViewportBorder(new LineBorder(Color.RED)); + jScrollPane.getViewport().add(jButton1, null); + + frame.add(jScrollPane, BorderLayout.CENTER); + frame.setSize(400, 150); + frame.setVisible(true); + } +} " +What is Java JFrame?,"The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI. + +Unlike Frame, JFrame has the option to hide or close the window with the help of setDefaultCloseOperation(int) method." +Can you provide an example of JFrame?,"import java.awt.FlowLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +public class JFrameExample { + public static void main(String s[]) { + JFrame frame = new JFrame(""JFrame Example""); + JPanel panel = new JPanel(); + panel.setLayout(new FlowLayout()); + JLabel label = new JLabel(""JFrame By Example""); + JButton button = new JButton(); + button.setText(""Button""); + panel.add(label); + panel.add(button); + frame.add(panel); + frame.setSize(200, 300); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} " +What is Java JComponent?,"The JComponent class is the base class of all Swing components except top-level containers. Swing components whose names begin with ""J"" are descendants of the JComponent class. For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame and JDialog don't inherit JComponent class because they are the child of top-level containers. + +The JComponent class extends the Container class which itself extends Component. The Container class has support for adding components to the container." +Can you provide an example of Java JComponent?,"import java.awt.Color; +import java.awt.Graphics; +import javax.swing.JComponent; +import javax.swing.JFrame; +class MyJComponent extends JComponent { + public void paint(Graphics g) { + g.setColor(Color.green); + g.fillRect(30, 30, 100, 100); + } +} +public class JComponentExample { + public static void main(String[] arguments) { + MyJComponent com = new MyJComponent(); + // create a basic JFrame + JFrame.setDefaultLookAndFeelDecorated(true); + JFrame frame = new JFrame(""JComponent Example""); + frame.setSize(300,200); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + // add the JComponent to main frame + frame.add(com); + frame.setVisible(true); + } +} " +What is Java JLayeredPane?,The JLayeredPane class is used to add depth to swing container. It is used to provide a third dimension for positioning component and divide the depth-range into several different layers. +What is JLayeredPane class declaration?,public class JLayeredPane extends JComponent implements Accessible +Can you provide an example of Java JLayeredPane?,"import javax.swing.*; +import java.awt.*; +public class LayeredPaneExample extends JFrame { + public LayeredPaneExample() { + super(""LayeredPane Example""); + setSize(200, 200); + JLayeredPane pane = getLayeredPane(); + //creating buttons + JButton top = new JButton(); + top.setBackground(Color.white); + top.setBounds(20, 20, 50, 50); + JButton middle = new JButton(); + middle.setBackground(Color.red); + middle.setBounds(40, 40, 50, 50); + JButton bottom = new JButton(); + bottom.setBackground(Color.cyan); + bottom.setBounds(60, 60, 50, 50); + //adding buttons on pane + pane.add(bottom, new Integer(1)); + pane.add(middle, new Integer(2)); + pane.add(top, new Integer(3)); + } + public static void main(String[] args) { + LayeredPaneExample panel = new LayeredPaneExample(); + panel.setVisible(true); + } +} " +What is Java JDesktopPane?,"The JDesktopPane class, can be used to create ""multi-document"" applications. A multi-document application can have many windows included in it. We do it by making the contentPane in the main window as an instance of the JDesktopPane class or a subclass. Internal windows add instances of JInternalFrame to the JdesktopPane instance. The internal windows are the instances of JInternalFrame or its subclasses." +Can you provide an example of Java JDesktopPane?,"import java.awt.BorderLayout; +import java.awt.Container; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JLabel; +public class JDPaneDemo extends JFrame +{ + public JDPaneDemo() + { + CustomDesktopPane desktopPane = new CustomDesktopPane(); + Container contentPane = getContentPane(); + contentPane.add(desktopPane, BorderLayout.CENTER); + desktopPane.display(desktopPane); + + setTitle(""JDesktopPane Example""); + setSize(300,350); + setVisible(true); + } + public static void main(String args[]) + { + new JDPaneDemo(); + } +} +class CustomDesktopPane extends JDesktopPane +{ + int numFrames = 3, x = 30, y = 30; + public void display(CustomDesktopPane dp) + { + for(int i = 0; i < numFrames ; ++i ) + { + JInternalFrame jframe = new JInternalFrame(""Internal Frame "" + i , true, true, true, true); + + jframe.setBounds(x, y, 250, 85); + Container c1 = jframe.getContentPane( ) ; + c1.add(new JLabel(""I love my country"")); + dp.add( jframe ); + jframe.setVisible(true); + y += 85; + } + } +} " +What is Java JEditorPane?,JEditorPane class is used to create a simple text editor window. This class has setContentType() and setText() methods. +"What is setContentType(""text/plain"")?","setContentType(""text/plain""): This method is used to set the content type to be plain text." +What is setText(text)?,setText(text): This method is used to set the initial text content. +Can you provide an example of JEditorPane?,"import javax.swing.JEditorPane; +import javax.swing.JFrame; + +public class JEditorPaneExample { + JFrame myFrame = null; + + public static void main(String[] a) { + (new JEditorPaneExample()).test(); + } + + private void test() { + myFrame = new JFrame(""JEditorPane Test""); + myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + myFrame.setSize(400, 200); + JEditorPane myPane = new JEditorPane(); + myPane.setContentType(""text/plain""); + myPane.setText(""Sleeping is necessary for a healthy body."" + + "" But sleeping in unnecessary times may spoil our health, wealth and studies."" + + "" Doctors advise that the sleeping at improper timings may lead for obesity during the students days.""); + myFrame.setContentPane(myPane); + myFrame.setVisible(true); + } +} " +What is Java JScrollPane?,"A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll pane to display a large component or a component whose size can change dynamically." +Can you provide an example of JScrollPane?,"import java.awt.FlowLayout; +import javax.swing.JFrame; +import javax.swing.JScrollPane; +import javax.swing.JtextArea; + +public class JScrollPaneExample { + private static final long serialVersionUID = 1L; + + private static void createAndShowGUI() { + + // Create and set up the window. + final JFrame frame = new JFrame(""Scroll Pane Example""); + + // Display the window. + frame.setSize(500, 500); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + // set flow layout for the frame + frame.getContentPane().setLayout(new FlowLayout()); + + JTextArea textArea = new JTextArea(20, 20); + JScrollPane scrollableTextArea = new JScrollPane(textArea); + + scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + + frame.getContentPane().add(scrollableTextArea); + } + public static void main(String[] args) { + + + javax.swing.SwingUtilities.invokeLater(new Runnable() { + + public void run() { + createAndShowGUI(); + } + }); + } +} " +What is Java JSplitPane?,"JSplitPane is used to divide two components. The two components are divided based on the look and feel implementation, and they can be resized by the user. If the minimum size of the two components is greater than the size of the split pane, the divider will not allow you to resize it. + +The two components in a split pane can be aligned left to right using JSplitPane.HORIZONTAL_SPLIT, or top to bottom using JSplitPane.VERTICAL_SPLIT. When the user is resizing the components the minimum size of the components is used to determine the maximum/minimum position the components can be set to." +Can you provide an example of JSplitPane?,"import java.awt.FlowLayout; +import java.awt.Panel; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JSplitPane; +public class JSplitPaneExample { + private static void createAndShow() { + // Create and set up the window. + final JFrame frame = new JFrame(""JSplitPane Example""); + // Display the window. + frame.setSize(300, 300); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + // set flow layout for the frame + frame.getContentPane().setLayout(new FlowLayout()); + String[] option1 = { ""A"",""B"",""C"",""D"",""E"" }; + JComboBox box1 = new JComboBox(option1); + String[] option2 = {""1"",""2"",""3"",""4"",""5""}; + JComboBox box2 = new JComboBox(option2); + Panel panel1 = new Panel(); + panel1.add(box1); + Panel panel2 = new Panel(); + panel2.add(box2); + JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2); + // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, + // panel1, panel2); + frame.getContentPane().add(splitPane); + } + public static void main(String[] args) { + // Schedule a job for the event-dispatching thread: + // creating and showing this application's GUI. + javax.swing.SwingUtilities.invokeLater(new Runnable() { + public void run() { + createAndShow(); + } + }); + } +} " +What is Java JTextPane?,JTextPane is a subclass of JEditorPane class. JTextPane is used for styled document with embedded images and components. It is text component that can be marked up with attributes that are represented graphically. JTextPane uses a DefaultStyledDocument as its default model. +Can you provide an example of JTextPane?,"import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Container; +import javax.swing.JFrame; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; +public class JTextPaneExample { + public static void main(String args[]) throws BadLocationException { + JFrame frame = new JFrame(""JTextPane Example""); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + Container cp = frame.getContentPane(); + JTextPane pane = new JTextPane(); + SimpleAttributeSet attributeSet = new SimpleAttributeSet(); + StyleConstants.setBold(attributeSet, true); + + // Set the attributes before adding text + pane.setCharacterAttributes(attributeSet, true); + pane.setText(""Welcome""); + + attributeSet = new SimpleAttributeSet(); + StyleConstants.setItalic(attributeSet, true); + StyleConstants.setForeground(attributeSet, Color.red); + StyleConstants.setBackground(attributeSet, Color.blue); + + Document doc = pane.getStyledDocument(); + doc.insertString(doc.getLength(), ""To Java "", attributeSet); + + attributeSet = new SimpleAttributeSet(); + doc.insertString(doc.getLength(), ""World"", attributeSet); + + JScrollPane scrollPane = new JScrollPane(pane); + cp.add(scrollPane, BorderLayout.CENTER); + + frame.setSize(400, 300); + frame.setVisible(true); + } +} " +What is Java JRootPane?,"RootPane is a lightweight container used behind the scenes by JFrame, JDialog, JWindow, JApplet, and JInternalFrame." +Can you provide an example of JRootPane?,"import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JRootPane; + +public class JRootPaneExample { + public static void main(String[] args) { + JFrame f = new JFrame(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JRootPane root = f.getRootPane(); + + // Create a menu bar + JMenuBar bar = new JMenuBar(); + JMenu menu = new JMenu(""File""); + bar.add(menu); + menu.add(""Open""); + menu.add(""Close""); + root.setJMenuBar(bar); + + // Add a button to the content pane + root.getContentPane().add(new JButton(""Press Me"")); + + // Display the UI + f.pack(); + f.setVisible(true); + } +} " +How to use ToolTip in Java Swing?,"You can create a tool tip for any JComponent with setToolTipText() method. This method is used to set up a tool tip for the component. + +For example, to add tool tip to PasswordField, you need to add only one line of code: + +field.setToolTipText(""Enter your Password""); " +Can you provide an example of Simple ToolTip?,"import javax.swing.*; +public class ToolTipExample { + public static void main(String[] args) { + JFrame f=new JFrame(""Password Field Example""); + //Creating PasswordField and label + JPasswordField value = new JPasswordField(); + value.setBounds(100,100,100,30); + value.setToolTipText(""Enter your Password""); + JLabel l1=new JLabel(""Password:""); + l1.setBounds(20,100, 80,30); + //Adding components to frame + f.add(value); f.add(l1); + f.setSize(300,300); + f.setLayout(null); + f.setVisible(true); +} +} " +How to change TitleBar icon in Java AWT and Swing?,"The setIconImage() method of Frame class is used to change the icon of Frame or Window. It changes the icon which is displayed at the left side of Frame or Window. + +The Toolkit class is used to get instance of Image class in AWT and Swing. + +Toolkit class is the abstract super class of every implementation in the Abstract Window Toolkit(AWT). Subclasses of Toolkit are used to bind various components. It inherits Object class." +Can you provide an Example to change TitleBar icon in Java AWT?,"import java.awt.*; +class IconExample { +IconExample(){ +Frame f=new Frame(); +Image icon = Toolkit.getDefaultToolkit().getImage(""D:\\icon.png""); +f.setIconImage(icon); +f.setLayout(null); +f.setSize(400,400); +f.setVisible(true); +} +public static void main(String args[]){ +new IconExample(); +} +} " +Can you provide an Example to change TitleBar icon in Java Swing?,"import javax.swing.*; +import java.awt.*; +class IconExample { +IconExample(){ +JFrame f=new JFrame(); +Image icon = Toolkit.getDefaultToolkit().getImage(""D:\\icon.png""); +f.setIconImage(icon); +f.setLayout(null); +f.setSize(200,200); +f.setVisible(true); +} +public static void main(String args[]){ +new ToolkitExample(); +} +} " +How to make an executable jar file in Java?,"The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An executable jar file calls the main method of the class if you double click it. + +To create the executable jar file, you need to create .mf file, also known as manifest file." +What is jar (Java Archive)?,"The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An executable jar file calls the main method of the class if you double click it. + +To create the executable jar file, you need to create .mf file, also known as manifest file." +What is Creating manifest file?,"To create manifest file, you need to write Main-Class, then colon, then space, then classname then enter. For example: + +myfile.mf +Main-Class: First +As you can see, the mf file starts with Main-Class colon space class name. Here, class name is First. + +In mf file, new line is must after the class name." +What is Creating executable jar file using jar tool?,"The jar tool provides many switches, some of them are as follows: + +1-c creates new archive file +2-v generates verbose output. It displays the included or extracted resource on the standard output. +3-m includes manifest information from the given mf file. +4-f specifies the archive file name +5.-x extracts files from the archive file +Now, let's write the code to generated the executable jar using mf file. + +You need to write jar then swiches then mf_file then jar_file then .classfile as given below: + +jar -cvmf myfile.mf myjar.jar First.class " +Can you provide an Example of digital clock in swing:?,"import javax.swing.*; +import java.awt.*; +import java.text.*; +import java.util.*; +public class DigitalWatch implements Runnable{ +JFrame f; +Thread t=null; +int hours=0, minutes=0, seconds=0; +String timeString = """"; +JButton b; + +DigitalWatch(){ + f=new JFrame(); + + t = new Thread(this); + t.start(); + + b=new JButton(); + b.setBounds(100,100,100,50); + + f.add(b); + f.setSize(300,400); + f.setLayout(null); + f.setVisible(true); +} + + public void run() { + try { + while (true) { + + Calendar cal = Calendar.getInstance(); + hours = cal.get( Calendar.HOUR_OF_DAY ); + if ( hours > 12 ) hours -= 12; + minutes = cal.get( Calendar.MINUTE ); + seconds = cal.get( Calendar.SECOND ); + + SimpleDateFormat formatter = new SimpleDateFormat(""hh:mm:ss""); + Date date = cal.getTime(); + timeString = formatter.format( date ); + + printTime(); + + t.sleep( 1000 ); // interval given in milliseconds + } + } + catch (Exception e) { } + } + +public void printTime(){ +b.setText(timeString); +} + +public static void main(String[] args) { + new DigitalWatch(); + + +} +} " +What is Displaying graphics in swing:?,java.awt.Graphics class provides many methods for graphics programming. +"What is public abstract void drawString(String str, int x, int y)?","public abstract void drawString(String str, int x, int y): is used to draw the specified string." +"What is public void drawRect(int x, int y, int width, int height)?","public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height." +"What is public abstract void fillRect(int x, int y, int width, int height)?","public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height." +"What is public abstract void drawOval(int x, int y, int width, int height)?","public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height." +"What is public abstract void fillOval(int x, int y, int width, int height)?","public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height." +"What is public abstract void drawLine(int x1, int y1, int x2, int y2)?","public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2)." +"What is public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)?","public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image." +"What is public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)?","public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc." +"What is public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)?","public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc." +What is public abstract void setColor(Color c)?,public abstract void setColor(Color c): is used to set the graphics current color to the specified color. +What is public abstract void setFont(Font font)?,public abstract void setFont(Font font): is used to set the graphics current font to the specified font. +Can you provide an Example of displaying graphics in swing?,"import java.awt.*; +import javax.swing.JFrame; + +public class DisplayGraphics extends Canvas{ + + public void paint(Graphics g) { + g.drawString(""Hello"",40,40); + setBackground(Color.WHITE); + g.fillRect(130, 30,100, 80); + g.drawOval(30,130,50, 60); + setForeground(Color.RED); + g.fillOval(130,130,50, 60); + g.drawArc(30, 200, 40,50,90,60); + g.fillArc(30, 130, 40,50,180,40); + + } + public static void main(String[] args) { + DisplayGraphics m=new DisplayGraphics(); + JFrame f=new JFrame(); + f.add(m); + f.setSize(400,400); + //f.setLayout(null); + f.setVisible(true); + } + +} " +What is Displaying image in swing?,"For displaying image, we can use the method drawImage() of Graphics class." +What is Syntax of drawImage() method?,"public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image." +"What is public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)?","public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image." +Can you provide an Example of displaying image in swing?,"import java.awt.*; +import javax.swing.JFrame; + +public class MyCanvas extends Canvas{ + + public void paint(Graphics g) { + + Toolkit t=Toolkit.getDefaultToolkit(); + Image i=t.getImage(""p3.gif""); + g.drawImage(i, 120,100,this); + + } + public static void main(String[] args) { + MyCanvas m=new MyCanvas(); + JFrame f=new JFrame(); + f.add(m); + f.setSize(400,400); + f.setVisible(true); + } + +} " +What are the Java LayoutManagers?,"The LayoutManagers are used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms. LayoutManager is an interface that is implemented by all the classes of layout managers. There are the following classes that represent the layout managers: + +1.java.awt.BorderLayout +2.java.awt.FlowLayout +3.java.awt.GridLayout +4.java.awt.CardLayout +5.java.awt.GridBagLayout +6.javax.swing.BoxLayout +7.javax.swing.GroupLayout +8.javax.swing.ScrollPaneLayout +9.javax.swing.SpringLayout etc." +What are the Java BorderLayout?,"The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center. Each region (area) may contain one component only. It is the default layout of a frame or window. The BorderLayout provides five constants for each region: + +1.public static final int NORTH +2.public static final int SOUTH +3.public static final int EAST +4.public static final int WEST +5.public static final int CENTER" +What are the Constructors of BorderLayout class:?,"-BorderLayout(): creates a border layout but with no gaps between the components. +-BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components." +Can you provide an Example of BorderLayout class: Using BorderLayout() constructor?,"FileName: Border.java + +import java.awt.*; +import javax.swing.*; + +public class Border +{ +JFrame f; +Border() +{ + f = new JFrame(); + + // creating buttons + JButton b1 = new JButton(""NORTH"");; // the button will be labeled as NORTH + JButton b2 = new JButton(""SOUTH"");; // the button will be labeled as SOUTH + JButton b3 = new JButton(""EAST"");; // the button will be labeled as EAST + JButton b4 = new JButton(""WEST"");; // the button will be labeled as WEST + JButton b5 = new JButton(""CENTER"");; // the button will be labeled as CENTER + + f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction + f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction + f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction + f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction + f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center + + f.setSize(300, 300); + f.setVisible(true); +} +public static void main(String[] args) { + new Border(); +} +} " +What is Java GridLayout?,The Java GridLayout class is used to arrange the components in a rectangular grid. One component is displayed in each rectangle. +What are the Constructors of GridLayout class?,"1.GridLayout(): creates a grid layout with one column per component in a row. +2.GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components. +3.GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns along with given horizontal and vertical gaps." +Can you provide an Example of GridLayout class: Using GridLayout() Constructor?,"The GridLayout() constructor creates only one row. The following example shows the usage of the parameterless constructor. + +FileName: GridLayoutExample.java + +// import statements +import java.awt.*; +import javax.swing.*; + +public class GridLayoutExample +{ +JFrame frameObj; + +// constructor +GridLayoutExample() +{ +frameObj = new JFrame(); + +// creating 9 buttons +JButton btn1 = new JButton(""1""); +JButton btn2 = new JButton(""2""); +JButton btn3 = new JButton(""3""); +JButton btn4 = new JButton(""4""); +JButton btn5 = new JButton(""5""); +JButton btn6 = new JButton(""6""); +JButton btn7 = new JButton(""7""); +JButton btn8 = new JButton(""8""); +JButton btn9 = new JButton(""9""); + +// adding buttons to the frame +// since, we are using the parameterless constructor, therfore; +// the number of columns is equal to the number of buttons we +// are adding to the frame. The row count remains one. +frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3); +frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6); +frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9); + +// setting the grid layout using the parameterless constructor +frameObj.setLayout(new GridLayout()); + + +frameObj.setSize(300, 300); +frameObj.setVisible(true); +} + +// main method +public static void main(String argvs[]) +{ +new GridLayoutExample(); +} +} ." +What is Java FlowLayout?,"The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow). It is the default layout of the applet or panel." +What are the Fields of FlowLayout class?,"1.public static final int LEFT +2.public static final int RIGHT +3.public static final int CENTER +4.public static final int LEADING +5.public static final int TRAILING" +What are the Constructors of FlowLayout class?,"1.FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap. +2.FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap. +3.FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap." +Can you provide an Example of FlowLayout class: Using FlowLayout() constructor?,"FileName: FlowLayoutExample.java + +// import statements +import java.awt.*; +import javax.swing.*; + +public class FlowLayoutExample +{ + +JFrame frameObj; + +// constructor +FlowLayoutExample() +{ + // creating a frame object + frameObj = new JFrame(); + + // creating the buttons + JButton b1 = new JButton(""1""); + JButton b2 = new JButton(""2""); + JButton b3 = new JButton(""3""); + JButton b4 = new JButton(""4""); + JButton b5 = new JButton(""5""); + JButton b6 = new JButton(""6""); + JButton b7 = new JButton(""7""); + JButton b8 = new JButton(""8""); + JButton b9 = new JButton(""9""); + JButton b10 = new JButton(""10""); + + + // adding the buttons to frame + frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4); + frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8); + frameObj.add(b9); frameObj.add(b10); + + // parameter less constructor is used + // therefore, alignment is center + // horizontal as well as the vertical gap is 5 units. + frameObj.setLayout(new FlowLayout()); + + frameObj.setSize(300, 300); + frameObj.setVisible(true); +} + +// main method +public static void main(String argvs[]) +{ + new FlowLayoutExample(); +} +} " +What is Java BoxLayout?,"The Java BoxLayout class is used to arrange the components either vertically or horizontally. For this purpose, the BoxLayout class provides four constants. They are as follows: + +Note: The BoxLayout class is found in javax.swing package." +What are the Fields of BoxLayout Class?,"1.public static final int X_AXIS: Alignment of the components are horizontal from left to right. +2.public static final int Y_AXIS: Alignment of the components are vertical from top to bottom. +3.public static final int LINE_AXIS: Alignment of the components is similar to the way words are aligned in a line, which is based on the ComponentOrientation property of the container. If the ComponentOrientation property of the container is horizontal, then the components are aligned horizontally; otherwise, the components are aligned vertically. For horizontal orientations, we have two cases: left to right, and right to left. If the value ComponentOrientation property of the container is from left to right, then the components are rendered from left to right, and for right to left, the rendering of components is also from right to left. In the case of vertical orientations, the components are always rendered from top to bottom. +4.public static final int PAGE_AXIS: Alignment of the components is similar to the way text lines are put on a page, which is based on the ComponentOrientation property of the container. If the ComponentOrientation property of the container is horizontal, then components are aligned vertically; otherwise, the components are aligned horizontally. For horizontal orientations, we have two cases: left to right, and right to left. If the value ComponentOrientation property of the container is also from left to right, then the components are rendered from left to right, and for right to left, the rendering of components is from right to left. In the case of vertical orientations, the components are always rendered from top to bottom." +What is Constructor of BoxLayout class?,"BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis." +Can you provide an Example of BoxLayout class with Y-AXIS:?,"FileName: BoxLayoutExample1.java + +import java.awt.*; +import javax.swing.*; + +public class BoxLayoutExample1 extends Frame { + Button buttons[]; + + public BoxLayoutExample1 () { + buttons = new Button [5]; + + for (int i = 0;i<5;i++) { + buttons[i] = new Button (""Button "" + (i + 1)); + // adding the buttons so that it can be displayed + add (buttons[i]); + } + // the buttons will be placed horizontally +setLayout (new BoxLayout (this, BoxLayout.Y_AXIS)); +setSize(400,400); +setVisible(true); +} + // main method +public static void main(String args[]){ +BoxLayoutExample1 b=new BoxLayoutExample1(); +} +} " +Can you provide an Example of BoxLayout class with X-AXIS?,"FileName: BoxLayoutExample2.java + +import java.awt.*; +import javax.swing.*; + +public class BoxLayoutExample2 extends Frame { + Button buttons[]; + + public BoxLayoutExample2() { + buttons = new Button [5]; + + for (int i = 0;i<5;i++) { + buttons[i] = new Button (""Button "" + (i + 1)); + // adding the buttons so that it can be displayed + add (buttons[i]); + } + // the buttons in the output will be aligned vertically +setLayout (new BoxLayout(this, BoxLayout.X_AXIS)); +setSize(400,400); +setVisible(true); +} + // main method +public static void main(String args[]){ +BoxLayoutExample2 b=new BoxLayoutExample2(); +} +} " +Can you provide an Example of BoxLayout Class with LINE_AXIS?,"The following example shows the effect of setting the value of ComponentOrientation property of the container to RIGHT_TO_LEFT. If we do not set the value of ComponentOrientation property, then the components would be laid out from left to right. Comment line 11, and see it yourself. + +FileName: BoxLayoutExample3.java + +// import statements +import java.awt.*; +import javax.swing.*; + +public class BoxLayoutExample3 extends Frame +{ +Button buttons[]; + +// constructor of the class +public BoxLayoutExample3() +{ +buttons = new Button[5]; +setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); // line 11 + +for (int i = 0; i < 5; i++) +{ + buttons[i] = new Button (""Button "" + (i + 1)); + + // adding the buttons so that it can be displayed + add (buttons[i]); +} + +// the ComponentOrientation is set to RIGHT_TO_LEFT. Therefore, +// the added buttons will be rendered from right to left +setLayout (new BoxLayout(this, BoxLayout.LINE_AXIS)); +setSize(400, 400); +setVisible(true); +} + +// main method +public static void main(String argvs[]) +{ +// creating an object of the class BoxLayoutExample3 +BoxLayoutExample3 obj = new BoxLayoutExample3(); +} +} " +Can you provide an Example of BoxLayout Class with PAGE_AXIS?,"The following example shows how to use PAGE_AXIS. + +FileName: BoxLayoutExample4.java + +// import statements +import java.awt.*; +import javax.swing.*; + +public class BoxLayoutExample4 extends Frame +{ +Button buttons[]; +// constructor of the class +public BoxLayoutExample4() +{ +JFrame f = new JFrame(); +JPanel pnl = new JPanel(); +buttons = new Button[5]; +GridBagConstraints constrntObj = new GridBagConstraints(); + +constrntObj.fill = GridBagConstraints.VERTICAL; +for (int i = 0; i < 5; i++) +{ + buttons[i] = new Button (""Button "" + (i + 1)); + + // adding the buttons so that it can be displayed + add(buttons[i]); +} + +// the components will be displayed just like the line is present on a page +setLayout (new BoxLayout(this, BoxLayout.PAGE_AXIS)); +setSize(400, 400); +setVisible(true); +} + +// main method +public static void main(String argvs[]) +{ +// creating an object of the class BoxLayoutExample4 +BoxLayoutExample4 obj = new BoxLayoutExample4(); +} +} " +What is Java CardLayout?,The Java CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout. +What are the Constructors of CardLayout Class?,"1.CardLayout(): creates a card layout with zero horizontal and vertical gap. +2.CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap." +What are the Commonly Used Methods of CardLayout Class?,"-public void next(Container parent): is used to flip to the next card of the given container. +-public void previous(Container parent): is used to flip to the previous card of the given container. +-public void first(Container parent): is used to flip to the first card of the given container. +-public void last(Container parent): is used to flip to the last card of the given container. +-public void show(Container parent, String name): is used to flip to the specified card with the given name." +Can you provide an Example of CardLayout Class: Using Default Constructor,"The following program uses the next() method to move to the next card of the container. + +FileName: CardLayoutExample1.java + +// import statements +import java.awt.*; +import javax.swing.*; +import java.awt.event.*; + +public class CardLayoutExample1 extends JFrame implements ActionListener +{ + +CardLayout crd; + +// button variables to hold the references of buttons +JButton btn1, btn2, btn3; +Container cPane; + +// constructor of the class +CardLayoutExample1() +{ + +cPane = getContentPane(); + +//default constructor used +// therefore, components will +// cover the whole area +crd = new CardLayout(); + +cPane.setLayout(crd); + +// creating the buttons +btn1 = new JButton(""Apple""); +btn2 = new JButton(""Boy""); +btn3 = new JButton(""Cat""); + +// adding listeners to it +btn1.addActionListener(this); +btn2.addActionListener(this); +btn3.addActionListener(this); + +cPane.add(""a"", btn1); // first card is the button btn1 +cPane.add(""b"", btn2); // first card is the button btn2 +cPane.add(""c"", btn3); // first card is the button btn3 + +} +public void actionPerformed(ActionEvent e) +{ +// Upon clicking the button, the next card of the container is shown +// after the last card, again, the first card of the container is shown upon clicking +crd.next(cPane); +} + +// main method +public static void main(String argvs[]) +{ +// creating an object of the class CardLayoutExample1 +CardLayoutExample1 crdl = new CardLayoutExample1(); + +// size is 300 * 300 +crdl.setSize(300, 300); +crdl.setVisible(true); +crdl.setDefaultCloseOperation(EXIT_ON_CLOSE); +} +} " +What is Java GridBagLayout?,"The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline. + +The components may not be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display area. Each component associates an instance of GridBagConstraints. With the help of the constraints object, we arrange the component's display area on the grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine the component's size. GridBagLayout components are also arranged in the rectangular grid but can have many different sizes and can occupy multiple rows or columns." +What is GridBagLayout Fields?,"Modifier and Type: double[] +Field: columnWeights +Description: It is used to hold the overrides to the column weights. + +Modifier and Type: int[] +Field: columnWidths +Description: It is used to hold the overrides to the column minimum width. + +Modifier and Type: protected Hashtable +Field: comptable +Description: It is used to maintains the association between a component and its gridbag constraints. + +Modifier and Type: protected GridBagConstraints +Field: defaultConstraints +Description: It is used to hold a gridbag constraints instance containing the default values. + +Modifier and Type: protected GridBagLayoutInfo +Field: layoutInfo +Description: It is used to hold the layout information for the gridbag. + +Modifier and Type: protected static int +Field: MAXGRIDSIZE +Description: No longer in use just for backward compatibility + + + +Modifier and Type: protected static int +Field: MINSIZE +Description: It is smallest grid that can be laid out by the grid bag layout. + +Modifier and Type: protected static int +Field: PREFERREDSIZE +Description: It is preferred grid size that can be laid out by the grid bag layout. + +Modifier and Type: int[] +Field: rowHeights +Description: It is used to hold the overrides to the row minimum heights. + +Modifier and Type: double[] +Field: rowWeights +Description: It is used to hold the overrides to the row weights. + " +Can you give me GridBagLayout Methods?,"Modifier and Type: void +Method: addLayoutComponent(Component comp, Object constraints) +Description: It adds specified component to the layout, using the specified constraints object. + +Modifier and Type: void +Method: addLayoutComponent(String name, Component comp) +Description: It has no effect, since this layout manager does not use a per-component string. + + +Modifier and Type: protected void +Method: adjustForGravity(GridBagConstraints constraints, Rectangle r) +Description: It adjusts the x, y, width, and height fields to the correct values depending on the constraint geometry and pads. + + +Modifier and Type: protected void +Method: AdjustForGravity(GridBagConstraints constraints, Rectangle r) +Description: This method is for backwards compatibility only + + +Modifier and Type: protected void +Method: arrangeGrid(Container parent) +Description: Lays out the grid. + + + + +Modifier and Type: protected void +Method: ArrangeGrid(Container parent) +Description: This method is obsolete and supplied for backwards compatibility + +Modifier and Type: GridBagConstraints +Method: getConstraints(Component comp) +Description: It is for getting the constraints for the specified component. + +Modifier and Type: float +Method: getLayoutAlignmentX(Container parent) +Description: It returns the alignment along the x axis. + +Modifier and Type: float +Method: getLayoutAlignmentY(Container parent) +Description: It returns the alignment along the y axis. + +Modifier and Type: int[][] +Method: getLayoutDimensions() +Description: It determines column widths and row heights for the layout grid. + +Modifier and Type: protected GridBagLayoutInfo +Method: getLayoutInfo(Container parent, int sizeflag) +Description: This method is obsolete and supplied for backwards compatibility. + + + +Modifier and Type: protected GridBagLayoutInfo +Method: GetLayoutInfo(Container parent, int sizeflag) +Description: This method is obsolete and supplied for backwards compatibility. + + +Modifier and Type: Point +Method: getLayoutOrigin() +Description: It determines the origin of the layout area, in the graphics coordinate space of the target container. + +Modifier and Type: double[][] +Method: getLayoutWeights() +Description: It determines the weights of the layout grid's columns and rows. + +Modifier and Type: protected Dimension +Method: getMinSize(Container parent, GridBagLayoutInfo info) +Description: It figures out the minimum size of the master based on the information from getLayoutInfo. + +Modifier and Type: protected Dimension +Method: GetMinSize(Container parent, GridBagLayoutInfo info) +Description: This method is obsolete and supplied for backwards compatibility only + + +" +What is GroupLayout?,"GroupLayout groups its components and places them in a Container hierarchically. The grouping is done by instances of the Group class. + +Group is an abstract class, and two concrete classes which implement this Group class are SequentialGroup and ParallelGroup. + +SequentialGroup positions its child sequentially one after another whereas ParallelGroup aligns its child on top of each other. + +The GroupLayout class provides methods such as createParallelGroup() and createSequentialGroup() to create groups. + +GroupLayout treats each axis independently. That is, there is a group representing the horizontal axis, and a group representing the vertical axis. Each component must exist in both a horizontal and vertical group, otherwise an IllegalStateException is thrown during layout or when the minimum, preferred, or maximum size is requested." +What is Java SpringLayout?,"A SpringLayout arranges the children of its associated container according to a set of constraints. Constraints are nothing but horizontal and vertical distance between two-component edges. Every constraint is represented by a SpringLayout.Constraint object. + +Each child of a SpringLayout container, as well as the container itself, has exactly one set of constraints associated with them. + +Each edge position is dependent on the position of the other edge. If a constraint is added to create a new edge, than the previous binding is discarded. SpringLayout doesn't automatically set the location of the components it manages." +What is pringLayout Fields?,"Modifier and Type: static String +Field: BASELINE +Description: It specifies the baseline of a component. + +Modifier and Type: static String +Field: EAST +Description: It specifies the right edge of a component's bounding rectangle. + +Modifier and Type: static String +Field: HEIGHT +Description: It specifies the height of a component's bounding rectangle. + +Modifier and Type: static String +Field: HORIZONTAL_CENTER +Description: It specifies the horizontal center of a component's bounding rectangle. + +Modifier and Type: static String +Field: NORTH +Description: It specifies the top edge of a component's bounding rectangle. + +Modifier and Type: static String +Field: SOUTH +Description: It specifies the bottom edge of a component's bounding rectangle. + + + +Modifier and Type: static String +Field: VERTICAL_CENTER +Description: It specifies the vertical center of a component's bounding rectangle. + +Modifier and Type: static String +Field: WEST +Description: It specifies the left edge of a component's bounding rectangle. + +Modifier and Type: static String +Field: WIDTH +Description: It specifies the width of a component's bounding rectangle. + + + " +Can you give SpringLayout Methods?,"SpringLayout Methods +Modifier and Type: void +Method: addLayoutComponent(Component component, Object constraints) +Description: If constraints is an instance of SpringLayout. Constraints, associates the constraints with the specified component. + +Modifier and Type: void +Method: addLayoutComponent(String name, Component c) +Description: Has no effect, since this layout manager does not use a per-component string. + +Modifier and Type: Spring +Method: getConstraint(String edgeName, Component c) +Description: It returns the spring controlling the distance between the specified edge of the component and the top or left edge of its parent. + +Modifier and Type: SpringLayout.Constraints +Method: getConstraints(Component c) +Description: +It returns the constraints for the specified component. + + +Modifier and Type: float +Method: getLayoutAlignmentX(Container p) +Description: It returns 0.5f (centered). + +Modifier and Type: float +Method: getLayoutAlignmentY(Container p) +Description: It returns 0.5f (centered). + + + +Modifier and Type: void +Method: invalidateLayout(Container p) +Description: It Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. + +Modifier and Type: void +Method: layoutContainer(Container parent) +Description: It lays out the specified container. + +Modifier and Type: Dimension +Method: maximumLayoutSize(Container parent) +Description: It is used to calculates the maximum size dimensions for the specified container, given the components it contains. + +Modifier and Type: Dimension +Method: minimumLayoutSize(Container parent) +Description: It is used to calculates the minimum size dimensions for the specified container, given the components it contains. + +Modifier and Type: Dimension +Method: preferredLayoutSize(Container parent) +Description: It is used to calculates the preferred size dimensions for the specified container, given the components it contains. + + +" +What is ScrollPaneLayout?,"The layout manager is used by JScrollPane. JScrollPaneLayout is responsible for nine components: a viewport, two scrollbars, a row header, a column header, and four ""corner"" components." +FieldScrollPanelLayout Field,"Modifier and Type: protected JViewport +Field: colHead +Description: It is column header child. + +Modifier and Type: protected JScrollBar +Field: hsb +Description: It is scrollpane's horizontal scrollbar child. + +Modifier and Type: protected int +Field: hsbPolicy +Description: It displays policy for the horizontal scrollbar. + + +Modifier and Type: protected Component +Field: lowerLeft +Description: This displays the lower left corner. + + +Modifier and Type: protected Component +Field: lowerRight +Description: This displays in the lower right corner. + + +Modifier and Type: protected JViewport +Field: rowHead +Description: It is row header child. + + +Modifier and Type: protected Component +Field: upperLeft +Description: This component displays in the upper left corner. + + +Modifier and Type: protected Component +Field: upperRight +Description: This component displays in the upper right corner. + + +Modifier and Type: protected JViewport +Field: viewport +Description: It is scrollpane's viewport child. + + +Modifier and Type: protected JScrollBar +Field: vsb +Description: It is scrollpane's vertical scrollbar child. + + +Modifier and Type: protected int +Field: vsbPolicy +Description: It is the display policy for the vertical scrollbar. + + + + " +Can you give me ScrollPanelLayout Methods?,"ScrollPanelLayout Methods + + +Modifier and Type: void +Method: addLayoutComponent(String s, Component c) +Description: It adds the specified component to the layout. + +Modifier and Type: protected Component +Method: addSingletonComponent(Component oldC, Component newC) +Description: It removes an existing component. + +Modifier and Type: JViewport +Method: getColumnHeader() +Description: It returns the JViewport object that is the column header. + +Modifier and Type: Component +Method: getCorner(String key) +Description: It returns the Component at the specified corner. + +Modifier and Type: JScrollBar +Method: getHorizontalScrollBar() +Description: It returns the JScrollBar object that handles horizontal scrolling. + +Modifier and Type: int +Method: getHorizontalScrollBarPolicy() +Description: It returns the horizontal scrollbar-display policy. + +Modifier and Type: JViewport +Method: getRowHeader() +Description: It returns the JViewport object that is the row header. + +Modifier and Type: JScrollBar +Method: getVerticalScrollBar() +Description: It returns the JScrollBar object that handles vertical scrolling. + +Modifier and Type: int +Method: getVerticalScrollBarPolicy() +Description: It returns the vertical scrollbar-display policy. + +Modifier and Type: JViewport +Method: getViewport() +Description: It returns the JViewport object that displays the scrollable contents. + +  + " +What is Java Applet?,Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side. +What is the Advantage of Applet?,"There are many advantages of applet. They are as follows: + +-It works at client side so less response time. +-Secured +-It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc." +What is Drawback of Applet?,"Plugin is required at client browser to execute applet. " +What is Lifecycle of Java Applet?,"1.Applet is initialized. +2.Applet is started. +3.Applet is painted. +4.Applet is stopped. +5.Applet is destroyed." +What is Lifecycle methods for Applet?,The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an applet. +What is java.applet.Applet class?,"For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet. + +1.public void init(): is used to initialized the Applet. It is invoked only once. +2.public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet. +3.public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized. +4.public void destroy(): is used to destroy the Applet. It is invoked only once." +What is java.awt.Component class?,"The Component class provides 1 life cycle method of applet. + +1.public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc." +Who is responsible to manage the life cycle of an applet?,Java Plug-in software. +How to run an Applet?,"There are two ways to run an applet + +1.By html file. +2.By appletViewer tool (for testing purpose)." +Can you provide an Simple example of Applet by html file,"To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file. + +//First.java +import java.applet.Applet; +import java.awt.Graphics; +public class First extends Applet{ + +public void paint(Graphics g){ +g.drawString(""welcome"",150,150); +} + +} +Note: class must be public because its object is created by Java Plugin software that resides on the browser. +myapplet.html + + + + + + " +What is Displaying Graphics in Applet?,"java.awt.Graphics class provides many methods for graphics programming. +Commonly used methods of Graphics class:" +What is Commonly used methods of Graphics class?,"1.public abstract void drawString(String str, int x, int y): is used to draw the specified string. +2.public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height. +3.public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height. +4.public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height. +5.public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height. +6.public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2). +7.public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image. +8.public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc. +9.public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc. +10.public abstract void setColor(Color c): is used to set the graphics current color to the specified color. +11.public abstract void setFont(Font font): is used to set the graphics current font to the specified font." +Can you provide an Example of Graphics in applet?,"import java.applet.Applet; +import java.awt.*; + +public class GraphicsDemo extends Applet{ + +public void paint(Graphics g){ +g.setColor(Color.red); +g.drawString(""Welcome"",50, 50); +g.drawLine(20,30,20,300); +g.drawRect(70,100,30,30); +g.fillRect(170,100,30,30); +g.drawOval(70,200,30,30); + +g.setColor(Color.pink); +g.fillOval(170,200,30,30); +g.drawArc(90,150,30,30,30,270); +g.fillArc(270,150,30,30,0,180); + +} +} +myapplet.html + + + + + + " +What is Displaying Image in Applet?,Applet is mostly used in games and animation. For this purpose image is required to be displayed. The java.awt.Graphics class provide a method drawImage() to display the image. +Can you give me Syntax of drawImage() method?,"public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image." +How to get the object of Image?,"The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax: +public Image getImage(URL u, String image){} " +Can you give me Other required methods of Applet class to display image?,"1.public URL getDocumentBase(): is used to return the URL of the document in which applet is embedded. +2.public URL getCodeBase(): is used to return the base URL." +Can you provide an Example of displaying image in applet?,"import java.awt.*; +import java.applet.*; + + +public class DisplayImage extends Applet { + + Image picture; + + public void init() { + picture = getImage(getDocumentBase(),""sonoo.jpg""); + } + + public void paint(Graphics g) { + g.drawImage(picture, 30,30, this); + } + + } +In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument of drawImage() method of is ImageObserver object. The Component class implements ImageObserver interface. So current class object would also be treated as ImageObserver because Applet class indirectly extends the Component class. +myapplet.html + + + + + + " +What is Animation in Applet?,Applet is mostly used in games and animation. For this purpose image is required to be moved. +Can you provide an Example of animation in applet?,"import java.awt.*; +import java.applet.*; +public class AnimationExample extends Applet { + + Image picture; + + public void init() { + picture =getImage(getDocumentBase(),""bike_1.gif""); + } + + public void paint(Graphics g) { + for(int i=0;i<500;i++){ + g.drawImage(picture, i,30, this); + + try{Thread.sleep(100);}catch(Exception e){} + } + } +} +In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument of drawImage() method of is ImageObserver object. The Component class implements ImageObserver interface. So current class object would also be treated as ImageObserver because Applet class indirectly extends the Component class. +myapplet.html + + + + + + " +What is EventHandling in Applet?,"As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple example of event handling in applet that prints a message by click on the button." +Can you provide an Example of EventHandling in applet?,"import java.applet.*; +import java.awt.*; +import java.awt.event.*; +public class EventApplet extends Applet implements ActionListener{ +Button b; +TextField tf; + +public void init(){ +tf=new TextField(); +tf.setBounds(30,40,150,20); + +b=new Button(""Click""); +b.setBounds(80,150,60,50); + +add(b);add(tf); +b.addActionListener(this); + +setLayout(null); +} + + public void actionPerformed(ActionEvent e){ + tf.setText(""Welcome""); + } +} +In the above example, we have created all the controls in init() method because it is invoked only once. +myapplet.html + + + + + + " +What is JApplet class in Applet?,As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet class extends the Applet class. +Example of EventHandling in JApplet,"import java.applet.*; +import javax.swing.*; +import java.awt.event.*; +public class EventJApplet extends JApplet implements ActionListener{ +JButton b; +JTextField tf; +public void init(){ + +tf=new JTextField(); +tf.setBounds(30,40,150,20); + +b=new JButton(""Click""); +b.setBounds(80,150,70,40); + +add(b);add(tf); +b.addActionListener(this); + +setLayout(null); +} + +public void actionPerformed(ActionEvent e){ +tf.setText(""Welcome""); +} +} +In the above example, we have created all the controls in init() method because it is invoked only once. +myapplet.html + + + + + + " +Painting in Applet,We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener. +Can you provide an Example of Painting in Applet?,"import java.awt.*; +import java.awt.event.*; +import java.applet.*; +public class MouseDrag extends Applet implements MouseMotionListener{ + +public void init(){ +addMouseMotionListener(this); +setBackground(Color.red); +} + +public void mouseDragged(MouseEvent me){ +Graphics g=getGraphics(); +g.setColor(Color.white); +g.fillOval(me.getX(),me.getY(),5,5); +} +public void mouseMoved(MouseEvent me){} + +} +In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis. The getGraphics() method of Component class returns the object of Graphics. +myapplet.html + + + + + + " +What is Digital clock in Applet?,Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's see the simple example: +Can you provide an Example of Digital clock in Applet?,"import java.applet.*; +import java.awt.*; +import java.util.*; +import java.text.*; + +public class DigitalClock extends Applet implements Runnable { + + Thread t = null; + int hours=0, minutes=0, seconds=0; + String timeString = """"; + + public void init() { + setBackground( Color.green); + } + + public void start() { + t = new Thread( this ); + t.start(); + } + + + public void run() { + try { + while (true) { + + Calendar cal = Calendar.getInstance(); + hours = cal.get( Calendar.HOUR_OF_DAY ); + if ( hours > 12 ) hours -= 12; + minutes = cal.get( Calendar.MINUTE ); + seconds = cal.get( Calendar.SECOND ); + + SimpleDateFormat formatter = new SimpleDateFormat(""hh:mm:ss""); + Date date = cal.getTime(); + timeString = formatter.format( date ); + + repaint(); + t.sleep( 1000 ); // interval given in milliseconds + } + } + catch (Exception e) { } + } + + + public void paint( Graphics g ) { + g.setColor( Color.blue ); + g.drawString( timeString, 50, 50 ); + } +} +In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis. The getGraphics() method of Component class returns the object of Graphics. +myapplet.html + + + + + + " +What is Analog clock in Applet?,Analog clock can be created by using the Math class. Let's see the simple example: +Can you provide an Example of Analog clock in Applet?,"import java.applet.*; +import java.awt.*; +import java.util.*; +import java.text.*; + +public class MyClock extends Applet implements Runnable { + + int width, height; + Thread t = null; + boolean threadSuspended; + int hours=0, minutes=0, seconds=0; + String timeString = """"; + + public void init() { + width = getSize().width; + height = getSize().height; + setBackground( Color.black ); + } + + public void start() { + if ( t == null ) { + t = new Thread( this ); + t.setPriority( Thread.MIN_PRIORITY ); + threadSuspended = false; + t.start(); + } + else { + if ( threadSuspended ) { + threadSuspended = false; + synchronized( this ) { + notify(); + } + } + } + } + + public void stop() { + threadSuspended = true; + } + + public void run() { + try { + while (true) { + + Calendar cal = Calendar.getInstance(); + hours = cal.get( Calendar.HOUR_OF_DAY ); + if ( hours > 12 ) hours -= 12; + minutes = cal.get( Calendar.MINUTE ); + seconds = cal.get( Calendar.SECOND ); + + SimpleDateFormat formatter + = new SimpleDateFormat( ""hh:mm:ss"", Locale.getDefault() ); + Date date = cal.getTime(); + timeString = formatter.format( date ); + + // Now the thread checks to see if it should suspend itself + if ( threadSuspended ) { + synchronized( this ) { + while ( threadSuspended ) { + wait(); + } + } + } + repaint(); + t.sleep( 1000 ); // interval specified in milliseconds + } + } + catch (Exception e) { } + } + + void drawHand( double angle, int radius, Graphics g ) { + angle -= 0.5 * Math.PI; + int x = (int)( radius*Math.cos(angle) ); + int y = (int)( radius*Math.sin(angle) ); + g.drawLine( width/2, height/2, width/2 + x, height/2 + y ); + } + + void drawWedge( double angle, int radius, Graphics g ) { + angle -= 0.5 * Math.PI; + int x = (int)( radius*Math.cos(angle) ); + int y = (int)( radius*Math.sin(angle) ); + angle += 2*Math.PI/3; + int x2 = (int)( 5*Math.cos(angle) ); + int y2 = (int)( 5*Math.sin(angle) ); + angle += 2*Math.PI/3; + int x3 = (int)( 5*Math.cos(angle) ); + int y3 = (int)( 5*Math.sin(angle) ); + g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y ); + g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y ); + g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 ); + } + + public void paint( Graphics g ) { + g.setColor( Color.gray ); + drawWedge( 2*Math.PI * hours / 12, width/5, g ); + drawWedge( 2*Math.PI * minutes / 60, width/3, g ); + drawHand( 2*Math.PI * seconds / 60, width/2, g ); + g.setColor( Color.white ); + g.drawString( timeString, 10, height-10 ); + } +} +myapplet.html + + + + + + " +What is Parameter in Applet?,"We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a method named getParameter(). Syntax: + +public String getParameter(String parameterName) " +Can you provide an Example of using parameter in Applet?,"import java.applet.Applet; +import java.awt.Graphics; + +public class UseParam extends Applet{ + +public void paint(Graphics g){ +String str=getParameter(""msg""); +g.drawString(str,50, 50); +} + +} +myapplet.html + + + + + + + " +What is Applet Communication?,"java.applet.AppletContext class provides the facility of communication between applets. We provide the name of applet through the HTML file. It provides getApplet() method that returns the object of Applet. Syntax: + +public Applet getApplet(String name){} " +Can you provide an Example of Applet Communication?,"import java.applet.*; +import java.awt.*; +import java.awt.event.*; +public class ContextApplet extends Applet implements ActionListener{ +Button b; + +public void init(){ +b=new Button(""Click""); +b.setBounds(50,50,60,50); + +add(b); +b.addActionListener(this); +} + +public void actionPerformed(ActionEvent e){ + +AppletContext ctx=getAppletContext(); +Applet a=ctx.getApplet(""app2""); +a.setBackground(Color.yellow); +} +} +myapplet.html + + + + + + + + + " +What is Java Reflection API?,"Java Reflection is a process of examining or modifying the run time behavior of a class at run time. + +The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class. + +The java.lang and java.lang.reflect packages provide classes for java reflection." +What is java.lang.Class class?,"The java.lang.Class class performs mainly two tasks: + +provides methods to get the metadata of a class at run time. +provides methods to examine and change the run time behavior of a class." +Can you give me Commonly used methods of Class class?,"Commonly used methods of Class class: + +Method: public String getName() +Description: returns the class name + +Method: public static Class forName(String className)throws ClassNotFoundException +Description: loads the class and returns the reference of Class class. + +Method: public Object newInstance()throws InstantiationException,IllegalAccessException +Description: creates new instance. + +Method: public boolean isInterface() +Description: checks if it is interface. + +Method: public boolean isArray() +Description: checks if it is array. + +Method: public boolean isPrimitive() +Description: checks if it is primitive. + +Method: public Class getSuperclass() +Description: returns the superclass class reference. + +Method: public Field[] getDeclaredFields()throws SecurityException +Description: returns the total number of fields of this class. + +Method: public Method[] getDeclaredMethods()throws SecurityException +Description: returns the total number of methods of this class. +Method: public Constructor[] getDeclaredConstructors()throws SecurityException +Description: returns the total number of constructors of this class. + +Method: public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException +Description: returns the method class instance. + " +How to get the object of Class class?,"There are 3 ways to get the instance of Class class. They are as follows: + +-forName() method of Class class +-getClass() method of Object class +-the .class syntax" +What is Determining the class object?,"The following methods of Class class are used to determine the class object: + +1) public boolean isInterface(): determines if the specified Class object represents an interface type. + +2) public boolean isArray(): determines if this Class object represents an array class. + +3) public boolean isPrimitive(): determines if the specified Class object represents a primitive type." +What are the Pros and Cons of Reflection?,"Java reflection should always be used with caution. While the reflection provides a lot of advantages, it has some disadvantages too. Let's discuss the advantages first. + +Pros: Inspection of interfaces, classes, methods, and fields during runtime is possible using reflection, even without using their names during the compile time. It is also possible to call methods, instantiate a clear or to set the value of fields using reflection. It helps in the creation of Visual Development Environments and class browsers which provides aid to the developers to write the correct code. + +Cons: Using reflection, one can break the principles of encapsulation. It is possible to access the private methods and fields of a class using reflection. Thus, reflection may leak important data to the outside world, which is dangerous. For example, if one access the private members of a class and sets null value to it, then the other user of the same class can get the NullReferenceException, and this behaviour is not expected. + +Another demerit is the overhead in performance. Since the types in reflection are resolved dynamically, JVM (Java Virtual Machine) optimization cannot take place. Therefore, the operations performed by reflections are usually slow." +What is Instance() method?,"The newInstance() method of Class class and Constructor class is used to create a new instance of the class. + +The newInstance() method of Class class can invoke zero-argument constructor, whereas newInstance() method of Constructor class can invoke any number of arguments. So, Constructor class is preferred over Class class.." +What is Syntax of newInstance() method of Class class?,"public T newInstance()throws InstantiationException,IllegalAccessException + +Here T is the generic version. You can think of it as Object class. You will learn about generics later." +What is Understanding javap tool?,"The javap command disassembles a class file. The javap command displays information about the fields, constructors and methods present in a class file." +What is Syntax to use javap tool?,"Let's see how to use javap tool or command. + +javap fully_class_name " +"Can you provide an Example to use javap tool? +","javap java.lang.Object +Output: + +Compiled from ""Object.java"" +public class java.lang.Object { + public java.lang.Object(); + public final native java.lang.Class getClass(); + public native int hashCode(); + public boolean equals(java.lang.Object); + protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException; + public java.lang.String toString(); + public final native void notify(); + public final native void notifyAll(); + public final native void wait(long) throws java.lang.InterruptedException; + public final void wait(long, int) throws java.lang.InterruptedException; + public final void wait() throws java.lang.InterruptedException; + protected void finalize() throws java.lang.Throwable; + static {}; +}" +Can you create a program that works as javap tool?,"Following methods of java.lang.Class class can be used to display the metadata of a class. +Method: public Field[] getDeclaredFields()throws SecurityException +Description: returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. + +Method: public Constructor[] getDeclaredConstructors()throws SecurityException +Description: returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. + +Method: public Method[] getDeclaredMethods()throws SecurityException +Description: returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. + + " +Can you provide an Example of creating javap tool?,"Let's create a program that works like javap tool. + +import java.lang.reflect.*; + +public class MyJavap{ + public static void main(String[] args)throws Exception { + Class c=Class.forName(args[0]); + + System.out.println(""Fields........""); + Field f[]=c.getDeclaredFields(); + for(int i=0;i, Serializable " +What are the Methods of Java LocalTime Class?,"Methods of Java LocalTime Class +Method: LocalDateTime atDate(LocalDate date) +Description: It is used to combine this time with a date to create a LocalDateTime. + +Method: int compareTo(LocalTime other) +Description: It is used to compare this time to another time. + +Method: String format(DateTimeFormatter formatter) +Description: It is used to format this time using the specified formatter. + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this time as an int. + +Method: LocalTime minusHours(long hoursToSubtract) +Description: It is used to return a copy of this LocalTime with the specified number of hours subtracted. + +Method: LocalTime minusMinutes(long minutesToSubtract) +Description: It is used to return a copy of this LocalTime with the specified number of minutes subtracted. + +Method: static LocalTime now() +Description: It is used to obtain the current time from the system clock in the default time-zone. + +Method: static LocalTime of(int hour, int minute, int second) +Description: It is used to obtain an instance of LocalTime from an hour, minute and second. + +Method: LocalTime plusHours(long hoursToAdd) +Description: It is used to return a copy of this LocalTime with the specified number of hours added. + +Method: LocalTime plusMinutes(long minutesToAdd) +Description: It is used to return a copy of this LocalTime with the specified number of minutes added. + " +Can you provide an example of Java LocalTime: now()?,"LocalTimeExample1.java + +import java.time.LocalTime; +public class LocalTimeExample1 { + public static void main(String[] args) { + LocalTime time = LocalTime.now(); + System.out.println(time); + } +} + +Output: + +15:19:47.459" +Can you provide an example of Java LocalTime: of()?,"LocalTimeExample2.java + +import java.time.LocalTime; +public class LocalTimeExample2 { + public static void main(String[] args) { + LocalTime time = LocalTime.of(10,43,12); + System.out.println(time); + } +} +Output: + +10:43:12" +Can you provide an example of Java localtime minusHours() and minusMinutes()?,"LocalTimeExample3.java + +import java.time.LocalTime; +public class LocalTimeExample3 { + public static void main(String[] args) { + LocalTime time1 = LocalTime.of(10,43,12); + System.out.println(time1); + LocalTime time2=time1.minusHours(2); + LocalTime time3=time2.minusMinutes(34); + System.out.println(time3); + } +} + +Output: + +10:43:12 +08:09:12" +Can you provide an example of Java localtime : plusHours() and plusMinutes()?,"LocalTimeExample5.java + +import java.time.*; +import java.time.temporal.ChronoUnit; +public class LocalTimeExample5 { + public static void main(String... args) { + ZoneId zone1 = ZoneId.of(""Asia/Kolkata""); + ZoneId zone2 = ZoneId.of(""Asia/Tokyo""); + LocalTime time1 = LocalTime.now(zone1); + System.out.println(""India Time Zone: ""+time1); + LocalTime time2 = LocalTime.now(zone2); + System.out.println(""Japan Time Zone: ""+time2); + long hours = ChronoUnit.HOURS.between(time1, time2); + System.out.println(""Hours between two Time Zone: ""+hours); + long minutes = ChronoUnit.MINUTES.between(time1, time2); + System.out.println(""Minutes between two time zone: ""+minutes); + } +} + +Output: + +India Time Zone: 14:56:43.087 +Japan Time Zone: 18:26:43.103 +Hours between two Time Zone: 3 +Minutes between two time zone: 210" +Can you provide an example of Java LocalTime?,"import java.time.LocalTime; +public class LocalTimeExample1 { + public static void main(String[] args) { + LocalTime time = LocalTime.now(); + System.out.println(time); + } +} + +Output: + +15:19:47.459" +What is Java LocalDateTime class?,"Java LocalDateTime class is an immutable date-time object that represents a date-time, with the default format as yyyy-MM-dd-HH-mm-ss.zzz. It inherits object class and implements the ChronoLocalDateTime interface." +What is Java LocalDateTime class declaration?,"Let's see the declaration of java.time.LocalDateTime class. + +public final class LocalDateTime extends Object +implements Temporal, TemporalAdjuster, ChronoLocalDateTime, Serializable " +What are the Methods of Java local DateTime?,"Methods of Java LocalDateTime +Method: String format(DateTimeFormatter formatter) +Description: It is used to format this date-time using the specified formatter. + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this date-time as an int. + +Method: LocalDateTime minusDays(long days) +Description: It is used to return a copy of this LocalDateTime with the specified number of days subtracted. + + +Method: static LocalDateTime now() +Description: It is used to obtain the current date-time from the system clock in the default time-zone. + +Method: static LocalDateTime of(LocalDate date, LocalTime time) +Description: It is used to obtain an instance of LocalDateTime from a date and time. + +Method: LocalDateTime plusDays(long days) +Description: It is used to return a copy of this LocalDateTime with the specified number of days added. + +Method: boolean equals(Object obj) +Description: It is used to check if this date-time is equal to another date-time. + + + +" +Can you provide an example of Java localDateTime?,"import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +public class LocalDateTimeExample1 { + public static void main(String[] args) { + LocalDateTime now = LocalDateTime.now(); + System.out.println(""Before Formatting: "" + now); + DateTimeFormatter format = DateTimeFormatter.ofPattern(""dd-MM-yyyy HH:mm:ss""); + String formatDateTime = now.format(format); + System.out.println(""After Formatting: "" + formatDateTime); + } +} + +Output: + +Before Formatting: 2017-01-13T17:09:42.411 +After Formatting: 13-01-2017 17:09:42" +Can you provide an example of Java localDateTime: now()?,"import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +public class LocalDateTimeExample2 { + public static void main(String[] args) { + LocalDateTime datetime1 = LocalDateTime.now(); + DateTimeFormatter format = DateTimeFormatter.ofPattern(""dd-MM-yyyy HH:mm:ss""); + String formatDateTime = datetime1.format(format); + System.out.println(formatDateTime); + } +} +Output: + +14-01-2017 11:42:32" +Java LocalDateTime Example: get() Can you provide an example of Java localDateTime: get()?,"import java.time.LocalDateTime; +import java.time.temporal.ChronoField; +public class LocalDateTimeExample3 { + public static void main(String[] args) { + LocalDateTime a = LocalDateTime.of(2017, 2, 13, 15, 56); + System.out.println(a.get(ChronoField.DAY_OF_WEEK)); + System.out.println(a.get(ChronoField.DAY_OF_YEAR)); + System.out.println(a.get(ChronoField.DAY_OF_MONTH)); + System.out.println(a.get(ChronoField.HOUR_OF_DAY)); + System.out.println(a.get(ChronoField.MINUTE_OF_DAY)); + } +} +Output: + +1 +44 +13 +15 +956" +Can you provide an example of Java localDateTime: minusDays()?,"import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +public class LocalDateTimeExample4 { +public static void main(String[] args) { + LocalDateTime datetime1 = LocalDateTime.of(2017, 1, 14, 10, 34); + LocalDateTime datetime2 = datetime1.minusDays(100); + System.out.println(""Before Formatting: "" + datetime2); + DateTimeFormatter format = DateTimeFormatter.ofPattern(""dd-MM-yyyy HH:mm""); + String formatDateTime = datetime2.format(format); + System.out.println(""After Formatting: "" + formatDateTime ); +} +} + +Output: + +Before Formatting: 2016-10-06T10:34 +After Formatting: 06-10-2016 10:34" +"Can you provide an example of Java localDateTime: plusDays()? +","import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +public class LocalDateTimeExample5 { +public static void main(String[] args) { + LocalDateTime datetime1 = LocalDateTime.of(2017, 1, 14, 10, 34); + LocalDateTime datetime2 = datetime1.plusDays(120); + System.out.println(""Before Formatting: "" + datetime2); + DateTimeFormatter format = DateTimeFormatter.ofPattern(""dd-MM-yyyy HH:mm""); + String formatDateTime = datetime2.format(format); + System.out.println(""After Formatting: "" + formatDateTime ); +} +} + +Output: + +Before Formatting: 2017-05-14T10:34 +After Formatting: 14-05-2017 10:34" +What is Java MonthDay Class?,Java MonthDay class is an immutable date-time object that represents the combination of a month and day-of-month. It inherits Object class and implements the Comparable interface. +What is Java MonthDay Class Declaration?,"Let's see the declaration of java.time.MonthDay class. + +public final class MonthDay extends Object +implements TemporalAccessor, TemporalAdjuster, Comparable, Serializable " +What are the Methods of Java MonthDay Class?,"Methods of Java MonthDay Class +Method: LocalDate atYear(int year) +Description: It is used to combine this month-day with a year to create a LocalDate. + +Method: String format(DateTimeFormatter formatter) +Description: It is used to format this month-day using the specified formatter. + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this month-day as an int. + +Method: boolean isValidYear(int year) +Description: It is used to check if the year is valid for this month-day. + +Method: static MonthDay now() +Description: It is used to obtain the current month-day from the system clock in the default time-zone. + +Method: static MonthDay of(int month, int dayOfMonth) +Description: It is used to obtain an instance of MonthDay. + +Method: ValueRange range(TemporalField field) +Description: It is used to get the range of valid values for the specified field. + +Method: int getDayOfMonth() +Description: It gets the day-of-month field. + +Method: Month getMonth() +Description: It gets the month-of-year field using the Month enum. + +Method: int getMonthValue() +Description: It gets the month-of-year field from 1 to 12. + +Method: int hashCode() +Description: It returns a hash code for this month-day. + +Method: boolean isAfter(MonthDay other) +Description: It checks if this month-day is after the specified month-day. + +Method: static MonthDay now() +Description: It obtains the current month-day from the system clock in the default time-zone. + +Method: static MonthDay now(Clock clock) +Description: It obtains the current month-day from the specified clock. + +Method: static MonthDay of(int month, int dayOfMonth) +Description: It obtains an instance of MonthDay. + +Method: R query(TemporalQuery query) +Description: It queries this month-day using the specified query. + +Method: ValueRange range(TemporalField field) +Description: It gets the range of valid values for the specified field. + +Method: String toString() +Description: It outputs this month-day as a String, such as -12-03. + +Method: MonthDay with(Month month) +Description: It returns a copy of this MonthDay with the month-of-year altered. + +Method: MonthDay withDayOfMonth(int dayOfMonth) +Description: It returns a copy of this MonthDay with the day-of-month altered. + +Method: MonthDay withMonth(int month) +Description: It returns a copy of this MonthDay with the month-of-year altered. + " +Can you provide an example of Java MonthDay Class?,"MonthDayExample1.java + +import java.time.*; +public class MonthDayExample1 { + public static void main(String[] args) { + MonthDay month = MonthDay.now(); + LocalDate date = month.atYear(1994); + System.out.println(date); + } +} + +Output: + +1994-01-17" +Can you provide an example of Java MonthDay Class: isValidYear()?,"MonthDayExample2.java + +import java.time.*; +public class MonthDayExample2 { + public static void main(String[] args) { + MonthDay month = MonthDay.now(); + boolean b = month.isValidYear(2012); + System.out.println(b); + } +} + +Output: + +true" +Can you provide an example of Java MonthDay Class: get()?,"MonthDayExample3.java + +import java.time.*; +import java.time.temporal.*; +public class MonthDayExample3{ + public static void main(String[] args) { + MonthDay month = MonthDay.now(); + long n = month.get(ChronoField.MONTH_OF_YEAR); + System.out.println(n); + } +} + +Output: + +1" +Can you provide an example of Java MonthDay Class: range()?,"MonthDayExample4.java + +import java.time.*; +import java.time.temporal.*; +public class MonthDayExample4 { + public static void main(String[] args) { + MonthDay month = MonthDay.now(); + ValueRange r1 = month.range(ChronoField.MONTH_OF_YEAR); + System.out.println(r1); + ValueRange r2 = month.range(ChronoField.DAY_OF_MONTH); + System.out.println(r2); + } +} +Output: + +1 - 12 +1 - 31" +What is Java OffsetTime Class Declaration?,"Let's see the declaration of java.time.OffsetTime class. + +public final class OffsetTime extends Object +implements Temporal, TemporalAdjuster, Comparable, Serializable " +"What are the Methods of Java OffsetTime Class? +","Methods of Java OffsetTime Class +Method: String format(DateTimeFormatter formatter) +Description: It is used to format this time using the specified formatter. + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this time as an int. + +Method: int getHour() +Description: It is used to get the hour-of-day field. + +Method: int getMinute() +Description: It is used to get the minute-of-hour field. + +Method: int getSecond() +Description: It is used to get the second-of-minute field. + +Method: static OffsetTime now() +Description: It is used to obtain the current time from the system clock in the default time-zone. + +Method: static OffsetTime of(LocalTime time, ZoneOffset offset) +Description: It is used to obtain an instance of OffsetTime from a local time and an offset. + +Method: ValueRange range(TemporalField field) +Description: It is used to get the range of valid values for the specified field. + +Method: VLocalTime toLocalTime() +Description: It is used to get the LocalTime part of this date-time. + +Method: boolean isAfter(OffsetTime other) +Description: It checks if the instant of this OffsetTime is after that of the specified time applying both times to a common date. + +Method: boolean isBefore(OffsetTime other) +Description: It checks if the instant of this OffsetTime is before that of the specified time applying both times to a common date. + +Method: boolean isEqual(OffsetTime other) +Description: It checks if the instant of this OffsetTime is equal to that of the specified time applying both times to a common date. + +Method: boolean isSupported(TemporalField field) +Description: It checks if the specified field is supported. + +Method: OffsetTime minus(long amountToSubtract, TemporalUnit unit) +Description: It returns a copy of this time with the specified amount subtracted. + +Method: OffsetTime minus(TemporalAmount amountToSubtract) +Description: It returns a copy of this time with the specified amount subtracted. + +Method: OffsetTime minusHours(long hoursToSubtract) +Description: It returns a copy of this OffsetTime with the specified number of hours subtracted. + +Method: OffsetTime minusMinutes(long minutesToSubtract) +Description: It returns a copy of this OffsetTime with the specified number of minutes subtracted. + +Method: OffsetTime minusNanos(long nanos) +Description: It returns a copy of this OffsetTime with the specified number of nanoseconds subtracted. + +Method: OffsetTime minusSeconds(long seconds) +Description: It returns a copy of this OffsetTime with the specified number of seconds subtracted. + +Method: static OffsetTime of(int hour, int minute, int second, int nanoOfSecond, ZoneOffset offset) +Description: It obtains an instance of OffsetTime from an hour, minute, second, nanosecond and an offset. + +Method: static OffsetTime parse(CharSequence text, DateTimeFormatter formatter) +Description: It obtains an instance of OffsetTime from a text string using a specific formatter. + + + + +" +"Can you provide an example of Java OffsetTime class? +","OffsetTimeExample1.java + +import java.time.OffsetTime; +import java.time.temporal.ChronoField; +public class OffsetTimeExample1 { + public static void main(String[] args) { + OffsetTime offset = OffsetTime.now(); + int h = offset.get(ChronoField.HOUR_OF_DAY); + System.out.println(h); + int m = offset.get(ChronoField.MINUTE_OF_DAY); + System.out.println(m); + int s = offset.get(ChronoField.SECOND_OF_DAY); + System.out.println(s); + } +} + +Output: + +16 +970 +58224" +"What is Java OffsetDateTime Class? +","Java OffsetDateTime class is an immutable representation of a date-time with an offset. It inherits Object class and implements the Comparable interface. + +OffsetDateTime class is used to store the date and time fields, to a precision of nanoseconds." +What is the class declaration for Java OffsetDateTime?,"Let's see the declaration of java.time.OffsetDateTime class. + +public final class OffsetDateTime extends Object +implements Temporal, TemporalAdjuster, Comparable, Serializable " +What are the Methods of Java OffsetDateTime Class?,"Java OffsetDateTime class is an immutable representation of a date-time with an offset. It inherits Object class and implements the Comparable interface. + +OffsetDateTime class is used to store the date and time fields, to a precision of nanoseconds." +"Can you provide an example of Java OffsetDateTime Class? + ","import java.time.OffsetDateTime; +public class OffsetDateTimeExample1 { + public static void main(String[] args) { + OffsetDateTime offsetDT = OffsetDateTime.now(); + System.out.println(offsetDT.getDayOfMonth()); + } +} + +Output: +18" +"What is Java Clock class? +","Java Clock class is used to provide an access to the current, date and time using a time zone. It inherits the Object class. + +Because all date-time classes contain a now() function that uses the system clock in the default time zone, using the Clock class is not required. The aim of the Clock class is to allow you to plug in another clock whenever you need it. Instead of using a static method, applications utilise an object to get the current time. It simplifies the testing process. A method that requires a current instant can take a Clock as a parameter." +What is the class declaration for Java Clock class?,"Let's see the declaration of java.time.Clock class. + +public abstract class Clock extends Object " +What are the Methods of Java OffsetDateTime Class?,"Methods of Java OffsetDateTime Class +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this date-time as an int. + +Method: int getDayOfMonth() +Description: It is used to get the day-of-month field. + +Method: iint getDayOfYear() +Description: It is used to get the day-of-year field. + +Method: DayOfWeek getDayOfWeek() +Description: It is used to get the day-of-week field, which is an enum DayOfWeek. + +Method: OffsetDateTime minusDays(long days) +Description: It is used to return a copy of this OffsetDateTime with the specified number of days subtracted. + +Method: static OffsetDateTime now() +Description: It is used to obtain the current date-time from the system clock in the default time-zone. + +Method: OffsetDateTime plusDays(long days) +Description: It is used to return a copy of this OffsetDateTime with the specified number of days added. + +Method: LocalDate toLocalDate() +Description: It is used to get the LocalDate part of this date-time. + +Method: Temporal adjustInto(Temporal temporal) +Description: It adjusts the specified temporal object to have the same date and time as this object. + +Method: TZonedDateTime atZoneSameInstant(ZoneId zone) +Description: It combines this date-time with a time-zone to create a ZonedDateTime ensuring that the result has the same instant. + +Method: TZonedDateTime atZoneSimilarLocal(ZoneId zone) +Description: It combines this date-time with a time-zone to create a ZonedDateTime trying to keep the same local date and time. + +Method: Tint compareTo(OffsetDateTime other) +Description: It compares this date-time to another date-time. + +Method: Tboolean equals(Object obj) +Description: It checks if this date-time is equal to another date-time. + +Method: TString format(DateTimeFormatter formatter) +Description: It formats this date-time using the specified formatter. + +Method: Tstatic OffsetDateTime from(TemporalAccessor temporal) +Description: It obtains an instance of OffsetDateTime from a temporal object. + +Method: Tint getHour() +Description: It gets the hour-of-day field. + +Method: Tlong getLong(TemporalField field) +Description: It gets the value of the specified field from this date-time as a long. + +Method: TMonth getMinute() +Description: It gets the minute-of-hour field. + +Method: TMonth getMonth() +Description: It gets the month-of-year field using the Month enum. + +Method: Tint getMonthValue() +Description: It gets the month-of-year field from 1 to 12. + +Method: Tint getNano() +Description: It gets the nano-of-second field. + +Method: TZoneOffset getOffset() +Description: It gets the zone offset, such as '+01:00'. + +Method: Tint getSecond() +Description: It gets the second-of-minute field. + +Method: Tint getYear() +Description: It gets the year field. + +Method: Tint hashCode() +Description: It returns hash code for this date-time. + +Method: Tboolean isAfter(OffsetDateTime other) +Description: It checks if this date-time is after the specified date-time. + +Method: Tboolean isBefore(OffsetDateTime other) +Description: It checks if this date-time is before the specified date-time. + +Method: Tboolean isEqual(OffsetDateTime other) +Description: It checks if this date-time is equal to the specified date-time. + +Method: Tboolean isSupported(TemporalField field) +Description: It checks if the specified field is supported. + +Method: Tboolean isSupported(TemporalUnit unit) +Description: It checks if the specified unit is supported. + +Method: TOffsetDateTime minus(long amountToSubtract, TemporalUnit unit) +Description: It returns a copy of this date-time with the specified amount subtracted. + +Method: TOffsetDateTime minus(TemporalAmount amountToSubtract) +Description: It returns a copy of this date-time with the specified amount subtracted. + +Method: TOffsetDateTime minusMonths(long monthsToSubtract) +Description: It returns a copy of this OffsetDateTime with the specified number of months subtracted. + +Method: TOffsetDateTime minusHours(long hoursToSubtract) +Description: It returns a copy of this OffsetDateTime with the specified number of hours subtracted. + +Method: TOffsetDateTime minusMinutes(long minutesToSubtract) +Description: It returns a copy of this OffsetDateTime with the specified number of minutes subtracted. + +Method: TOffsetDateTime minusNanos(long nanos) +Description: It returns a copy of this OffsetDateTime with the specified number of nanoseconds subtracted. + +Method: Tstatic OffsetDateTime of(LocalDate date, LocalTime time, ZoneOffset offset) +Description: It obtains an instance of OffsetDateTime from a date, time and offset. + +Method: Tstatic OffsetDateTime ofInstant(Instant instant, ZoneId zone) +Description: It obtains an instance of OffsetDateTime from an Instant and zone ID. + +Method: Tstatic OffsetDateTime parse(CharSequence text) +Description: It obtains an instance of OffsetDateTime from a text string such as 2007-12-03T10:15:30. + +Method: TValueRange range(TemporalField field) +Description: It gets the range of valid values for the specified field. + +Method: Tlong toEpochSecond() +Description: It converts this date-time to the number of seconds from the epoch of 1970-01-01T00:00:00Z. + +Method: TOffsetDateTime truncatedTo(TemporalUnit unit) +Description: It returns a copy of this OffsetDateTime with the time truncated. + +Method: TOffsetDateTime with(TemporalAdjuster adjuster) +Description: It returns an adjusted copy of this date-time." +"Can you provide an example of Java OffsetDateTime Class: getDayOfMonth()? +","OffsetDateTimeExample1.java + +import java.time.OffsetDateTime; +public class OffsetDateTimeExample1 { + public static void main(String[] args) { + OffsetDateTime offsetDT = OffsetDateTime.now(); + System.out.println(offsetDT.getDayOfMonth()); + } +} + +Output: +18" +Can you provide an example of Java OffsetDateTime Class: getDayOfYear()?,"OffsetDateTimeExample2.java + +import java.time.OffsetDateTime; +public class OffsetDateTimeExample2 { + public static void main(String[] args) { + OffsetDateTime offsetDT = OffsetDateTime.now(); + System.out.println(offsetDT.getDayOfYear()); + } +} + +Output: + +18" +Can you provide an example of Java OffsetDateTime Class: getDayOfWeek()?,"OffsetDateTimeExample3.java + +import java.time.OffsetDateTime; +public class OffsetDateTimeExample3 { + public static void main(String[] args) { + OffsetDateTime offsetDT = OffsetDateTime.now(); + System.out.println(offsetDT.getDayOfWeek()); + } +} + +Output: + +WEDNESDAY" +"Can you provide an example of Java OffsetDateTime Class: toLocalDate()? +","OffsetDateTimeExample4.java + +import java.time.OffsetDateTime; +public class OffsetDateTimeExample4 { + public static void main(String[] args) { + OffsetDateTime offsetDT = OffsetDateTime.now(); + System.out.println(offsetDT.toLocalDate()); + } +} + +Output: + +2017-01-18" +"Can you provide an example of Java OffsetDateTime Class: minusDays()? +","OffsetDateTimeExample5.java + +import java.time.OffsetDateTime; +public class OffsetDateTimeExample5 { + public static void main(String[] args) { + OffsetDateTime offset = OffsetDateTime.now(); + OffsetDateTime value = offset.minusDays(240); + System.out.println(value); + } +} + +Output: + +2016-05-23T12:12:31.642+05:30 +" +"Can you provide an example of Java OffsetDateTime Class: plusDays()? +","OffsetDateTimeExample6.java + +import java.time.OffsetDateTime; +public class OffsetDateTimeExample6 { + public static void main(String[] args) { + OffsetDateTime offset = OffsetDateTime.now(); + OffsetDateTime value = offset.plusDays(240); + System.out.println(value); + } +} + +Output: + +2017-09-15T13:50:30.526+05:30" +"What is Java Clock class? +","Java Clock class is used to provide an access to the current, date and time using a time zone. It inherits the Object class. + +Because all date-time classes contain a now() function that uses the system clock in the default time zone, using the Clock class is not required. The aim of the Clock class is to allow you to plug in another clock whenever you need it. Instead of using a static method, applications utilise an object to get the current time. It simplifies the testing process. A method that requires a current instant can take a Clock as a parameter." +"What is the class declaration for Java Clock Class? +","et's see the declaration of java.time.Clock class. + +public abstract class Clock extends Object " +"What are the Methods of Java Clock Class? +","Methods of Java Clock Class + +Method: abstract ZoneId getZone() +Description: It is used to get the time-zone being used to create dates and times. + +Method: abstract Instant instant() +Description: It is used to get the current instant of the clock. + +Method: static Clock offset(Clock baseClock, Duration offsetDuration) +Description: It is used to obtain a clock that returns instants from the specified clock with the specified duration added + +Method: static Clock systemDefaultZone() +Description: It is used to obtain a clock that returns the current instant using the best available system clock, converting to date and time using the default time-zone. + +Method: static Clock systemUTC() +Description: It is used to obtain a clock that returns the current instant using the best available system clock, converting to date and time using the UTC time zone. + +Method: boolean equals(Object obj) +Description: It checks if this clock is equal to another clock. + +Method: static Clock fixed(Instant fixedInstant, ZoneId zone) +Description: It obtains a clock that always returns the same instant. + +Method: static Clock system(ZoneId zone) +Description: It obtains a clock that returns the current instant using best available system clock. + +Method: int hashCode() +Description: It gets the time-zone being used to create dates and times. + +Method: long millis() +Description: It gets the current millisecond instant of the clock. + +Method: static Clock tick(Clock baseClock, Duration tickDuration) +Description: It obtains a clock that returns instants from the specified clock truncated to the nearest occurrence of the specified duration. + +Method: static Clock tickMinutes(ZoneId zone) +Description: It obtains a clock that returns the current instant ticking in whole minutes using best available system clock. + +Method: static Clock tickSeconds(ZoneId zone) +Description: It obtains a clock that returns the current instant ticking in whole seconds using best available system clock. + +Method: static Clock withZone(ZoneId zone) +Description: It returns a copy of this clock with a different time-zone. " +"Can you provide an example of Java Clock class: getZone()? +","ClockExample1.java + +import java.time.Clock; +public class ClockExample1 { + public static void main(String[] args) { + Clock c = Clock.systemDefaultZone(); + System.out.println(c.getZone()); + } +} + +Output: + +Asia/Calcutta " +"Can you provide an example of Java Clock class: instant()? +","ClockExample2.java + +import java.time.Clock; +public class ClockExample2 { + public static void main(String[] args) { + Clock c = Clock.systemUTC(); + System.out.println(c.instant()); + } +} + +Output: +2017-01-14T07:11:07.748Z" +"Can you provide an example of Java Clock class: systemUTC()? +","ClockExample3.java + +import java.time.Clock; +public class ClockExample3 { + public static void main(String[] args) { + Clock c = Clock.systemUTC(); + System.out.println(c.instant()); + } +} + +Output: +2017-01-14T07:11:07.748Z" +"Can you provide an example of Java Clock class: offset()? +","ClockExample4.java + +import java.time.Clock; +import java.time.Duration; +public class ClockExample4 { + public static void main(String[] args) { + Clock c = Clock.systemUTC(); + Duration d = Duration.ofHours(5); + Clock clock = Clock.offset(c, d); + System.out.println(clock.instant()); + } +} + +Output: +2017-01-14T14:15:25.389Z " +"What is Java ZonedDateTime class? +","Java ZonedDateTime class is an immutable representation of a date-time with a time-zone. It inherits Object class and implements the ChronoZonedDateTime interface. + +ZonedDateTime class is used to store all date and time fields, to a precision of nanoseconds, and a time-zone with a zone offset used to handle ambiguous local date-times." +"What is the class declaration for Java ZonedDateTime class? +","Let's see the declaration of java.time.ZonedDateTime class. + +public final class ZonedDateTime extends Object +implements Temporal, ChronoZonedDateTime, Serializable " +"What are the Methods of Java ZonedDateTime? +","Methods of Java ZonedDateTime + +Method: String format(DateTimeFormatter formatter) +Description: It is used to format this date-time using the specified formatter. + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this date-time as an int. + +Method: ZoneId getZone() +Description: It is used to get the time-zone, such as 'Asia/Kolkata'. + +Method: ZonedDateTime withZoneSameInstant(ZoneId zone) +Description: It is used to return a copy of this date-time with a different time-zone, retaining the instant. + +Method: static ZonedDateTime now() +Description: It is used to obtain the current date-time from the system clock in the default time-zone. + +Method: static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone) +Description: It is used to obtain an instance of ZonedDateTime from a local date and time. + +Method: ZonedDateTime minus(long amountToSubtract, TemporalUnit unit) +Description: It is used to return a copy of this date-time with the specified amount subtracted. + +Method: ZonedDateTime plus(long amountToAdd, TemporalUnit unit) +Description: It is used to return a copy of this date-time with the specified amount added. " +"Can you provide an example of Java ZonedDateTime class? +","import java.time.ZonedDateTime; +public class ZonedDateTimeExample1{ + public static void main(String[] args) { + ZonedDateTime zone = ZonedDateTime.parse(""2016-10-05T08:20:10+05:30[Asia/Kolkata]""); + System.out.println(zone); + } +} + +Output: +2016-10-05T08:20:10+05:30[Asia/Kolkata] " +"What is Java ZoneId Class? + +","Java ZoneId class specifies a time zone identifier and provides a rule for converting between an Instant and a LocalDateTime. It inherits Object class and implements the Serializable interface. + +There are two sorts of ID: + +Fixed offsets are fully resolved offsets from UTC/Greenwich that apply to all local date-times. +Geographical regions are areas where a set of rules for determining the offset from UTC/Greenwich apply." +"What is the class declaration for Java Zoneld Class? +","Let's see the declaration of java.time.ZoneId class. + +public abstract class ZoneId extends Object implements Serializable +To allow for the use of short time-zone names, a zone map overrides are employed. In java.util.TimeZone, the usage of short zone IDs is discouraged. The IDs can still be utilised using the of(String, Map) factory function thanks to the map. The map contains a mapping of the IDs that is compatible with TZDB 2005r and later, where 'EST,' 'MST,' and 'HST' correspond to IDs that do not include daylight savings time." +"What are the Methods of Java ZoneId Class? +","Methods of Java ZoneId Class + +Method: String getDisplayName(TextStyle style, Locale locale) +Description: It s used to get the textual representation of the zone, such as 'India Time' or '+05:30'. + +Method: abstract String getId() +Description: It is used to get the unique time-zone ID. + +Method: static ZoneId of(String zoneId) +Description: It is used to obtain an instance of ZoneId from an ID ensuring that the ID is valid and available for use. + +Method: static ZoneId systemDefault() +Description: It is used to get the system default time-zone. + +Method: boolean equals(Object obj) +Description: It is used to check if this time-zone ID is equal to another time-zone ID. + +Method: static ZoneId from(TemporalAccessor temporal) +Description: It obtains an instance of ZoneId from a temporal object. + +Method: static Set getAvailableZoneIds() +Description: It gets the set of available zone IDs. + +Method: abstract ZoneRules getRules() +Description: It gets the time-zone rules for this ID allowing calculations to be performed. + +Method: int hashCode() +Description: It returns a hash code for this time-zone ID. + +Method: ZoneId normalized() +Description: It normalizes the time-zone ID, returning a ZoneOffset where possible. + +Method: static ZoneId of(String zoneId, Map aliasMap) +Description: It obtains an instance of ZoneId using its ID using a map of aliases to supplement the standard zone IDs. + +Method: static ZoneId ofOffset(String prefix, ZoneOffset offset) +Description: It obtains an instance of ZoneId wrapping an offset. + +Method: String toString() +Description: It outputs this zone as a String, using the ID." +"Can you provide an example of Java Zoneld Class? +","ZoneIdExample1.java + +import java.time.*; +public class ZoneIdExample1 { + public static void main(String... args) { + ZoneId zoneid1 = ZoneId.of(""Asia/Kolkata""); + ZoneId zoneid2 = ZoneId.of(""Asia/Tokyo""); + LocalTime id1 = LocalTime.now(zoneid1); + LocalTime id2 = LocalTime.now(zoneid2); + System.out.println(id1); + System.out.println(id2); + System.out.println(id1.isBefore(id2)); + } +} + +Output: +14:28:58.230 +17:58:58.230 +true" +"What is Java ZoneOffset class? +","Java ZoneOffset class +Java ZoneOffset class is used to represent the fixed zone offset from UTC time zone. It inherits the ZoneId class and implements the Comparable interface. + +The ZoneOffset class declares three constants: +MAX: It is the maximum supported zone offsets. +MIN: It is the minimum supported zone offsets. +UTC: It is the time zone offset constant for UTC." +"What is the class declaration for Java ZoneOffset? +","public final class ZoneOffset extends ZoneId +implements TemporalAccessor, TemporalAdjuster, Comparable, Serializable " +"What are the Methods of Java ZoneOffset ? +","Method: Temporal adjustInto(Temporal temporal) +Description: It is used to adjust the specified temporal object to have the same offset as this object. +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this offset as an int. +Method: boolean isSupported(TemporalField field) +Description: It is used to check if the specified field is supported. +Method: static ZoneOffset of(String offsetId) +Description: It is used to obtain an instance of ZoneOffset using the ID. +Method: static ZoneOffset ofHours(int hours) +Description: It is used to obtain an instance of ZoneOffset using an offset in hours. +Method: static ZoneOffset ofHoursMinutes(int hours, int minutes) +Description: It is used to obtain an instance of ZoneOffset using an offset in hours and minutes. +Method: ValueRange range(TemporalField field) +Description: It is used to get the range of valid values " +"Can you provide an example of Java ZoneOffset? +","import java.time.*; +import java.time.temporal.Temporal; +public class ZoneOffsetExample1 { + public static void main(String[] args) { + ZoneOffset zone = ZoneOffset.UTC; + Temporal temp = zone.adjustInto(ZonedDateTime.now()); + System.out.println(temp); + } +} +Output: 2017-01-29T12:43:00.702+05:30[Asia/Calcutta]" +"Can you provide an example of Java ZoneOffset: ofHours()? +","import java.time.ZoneOffset; +public class ZoneOffsetExample2 { + public static void main(String[] args) { + ZoneOffset zone = ZoneOffset.ofHours(5); + System.out.println(zone); + } +} +Output: +05:00" +"Can you provide an example of Java ZoneOffset: ofHoursMinutes()? +","import java.time.ZoneOffset; +public class ZoneOffsetExample3 { + public static void main(String[] args) { + ZoneOffset zone = ZoneOffset.ofHoursMinutes(5,30); + System.out.println(zone); + } +} +Output: +05:30" +"Can you provide an example of Java ZoneOffset: isSupported()? +","import java.time.ZoneOffset; +import java.time.temporal.ChronoField; +public class ZoneOffsetExample4 { + public static void main(String[] args) { + ZoneOffset zone = ZoneOffset.UTC; + boolean b1 = zone.isSupported(ChronoField.OFFSET_SECONDS); + System.out.println(b1); + boolean b2 = zone.isSupported(ChronoField.SECOND_OF_MINUTE); + System.out.println(b2); + } +} +Output: true + false" +"What is Java Year class? +",Java Year class is an immutable date-time object that represents a year. It inherits the Object class and implements the Comparable interface. +"What is the class declaration for Java Year class? +","public final class Year extends Object implements Temporal, TemporalAdjuster, Comparable, Serializable " +"What are the Methods of Java Year? +","Method: LocalDate atDay(int dayOfYear) +Description: It is used to combine this year with a day-of-year to create a LocalDate. + +Method: String format(DateTimeFormatter formatter) +Description: It is used to format this year using the specified formatter. + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this year as an int. + +Method: boolean isAfter(Year other) +Description: It is used to check if this year is after the specified year. + +Method: boolean isBefore(Year other) +Description: It is used to check if this year is before the specified year. + +Method: boolean isLeap() +Description: It is used to check if the year is a leap year, according to the ISO proleptic calendar system rules. + +Method: int length() +Description: It is used to get the length of this year in days. + +Method: static Year now() +Description: It is used to obtain the current year from the system clock in the default time-zone. " +"Can you provide an example of Java Year: now()? +","import java.time.Year; +public class YearExample1 { + public static void main(String[] args) { + Year y = Year.now(); + System.out.println(y); + } +} +Output: 2017" +"Can you provide an example of Java Year: atDay()? +","import java.time.LocalDate; +import java.time.Year; +public class YearExample2{ + public static void main(String[] args) { + Year y = Year.of(2017); + LocalDate l = y.atDay(123); + System.out.println(l); + } +} +Output: 2017-05-03" +"Can you provide an example of Java Year: length()? +","import java.time.Year; +public class YearExample3 { + public static void main(String[] args) { + Year year = Year.of(2017); + System.out.println(year.length()); + } +} +Output: 365" +"Can you provide an example of Java Year: isLeap()? +","import java.time.Year; +public class YearExample4 { + public static void main(String[] args) { + Year year = Year.of(2016); + System.out.println(year.isLeap()); + } +} +Output: true" +"What is Java YearMonth class? +",Java YearMonth class is an immutable date-time object that represents the combination of a year and month. It inherits the Object class and implements the Comparable interface. +"What is the class declaration for Java YearMonth class? +","public final class YearMonth extends Object +implements Temporal, TemporalAdjuster, Comparable, Serializable " +"What are the Methods of Java YearMonth? +","Method: Temporal adjustInto(Temporal temporal) +Description: It is used to adjust the specified temporal object to have this year-month. + +Method: String format(DateTimeFormatter formatter) +Description: It is used to format this year-month using the specified formatter. + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this year-month as an int. + +Method: boolean isLeapYear() +Description: It is used to check if the year is a leap year, according to the ISO proleptic calendar system rules. + +Method: static YearMonth now() +Description: It is used to obtain the current year-month from the system clock in the default time zone. + +Method: static YearMonth of(int year, int month) +Description: It is used to obtain an instance of YearMonth from a year and month. + +Method: YearMonth plus(TemporalAmount amountToAdd) +Description: It is used to return a copy of this year-month with the specified amount added. + +Method: YearMonth minus (TemporalAmount amountToSubtract) +Description: It is used to return a copy of this year-month with the specified amount subtracted. + +Method: LocalDate atEndOfMonth() +Description: It returns a LocalDate at the end of the month. + +Method: int compareTo(YearMonth other) +Description: It compares this year-month to another year-month. + +Method: boolean equals(Object obj) +Description: It checks if this year-month is equal to another year-month. + +Method: static YearMonth now(Clock clock) +Description: It obtains the current year-month from the specified clock. + +Method: static YearMonth of(int year, int month) +Description: It obtains an instance of YearMonth from a year and month. + +Method: long until(Temporal endExclusive, TemporalUnit unit) +Description: It calculates the amount of time until another year-month in terms of the specified unit. + +Method: YearMonth withMonth(int month) +Description: It returns a copy of this YearMonth with the month-of-year altered. + +Method: YearMonth withYear(int year) +Description: It returns a copy of this YearMonth with the year altered. " +"Can you provide an example of Java YearMonth: now()? +","import java.time.YearMonth; +public class YearMonthExample1 { +public static void main(String[] args) { + YearMonth ym = YearMonth.now(); + System.out.println(ym); +} +} +Output: 2017-01 " +"Can you provide an example of Java YearMonth: format()? +","import java.time.YearMonth; +import java.time.format.DateTimeFormatter; +public class YearMonthExample2 { + public static void main(String[] args) { + YearMonth ym = YearMonth.now(); + String s = ym.format(DateTimeFormatter.ofPattern(""MM yyyy"")); + System.out.println(s); + } +} +Output: 01 2017" +"Can you provide an example of Java YearMonth: get()? + ","import java.time.YearMonth; +import java.time.temporal.ChronoField; +public class YearMonthExample3 { + public static void main(String[] args) { + YearMonth y = YearMonth.now(); + long l1 = y.get(ChronoField.YEAR); + System.out.println(l1); + long l2 = y.get(ChronoField.MONTH_OF_YEAR); + System.out.println(l2); + } +} +Output: 2017 + 1" +"Can you provide an example of Java YearMonth: plus()? +","import java.time.*; +public class YearMonthExample4 { + public static void main(String[] args) { + YearMonth ym1 = YearMonth.now(); + YearMonth ym2 = ym1.plus(Period.ofYears(2)); + System.out.println(ym2); + } +} +Output: 2019-01 +" +"Can you provide an example of Java YearMonth: minus()? +","import java.time.*; +public class YearMonthExample5 { + public static void main(String[] args) { + YearMonth ym1 = YearMonth.now(); + YearMonth ym2 = ym1.minus(Period.ofYears(2)); + System.out.println(ym2); + } +} +Output: 2015-01" +"What is Java Period class? +","Java Period class is used to measures time in years, months and days. It inherits the Object class and implements the ChronoPeriod interface." +"What is the class declaration for Java Period class? +","public final class Period extends Object implements ChronoPeriod, Serializable" +"What are the Methods of Java Period? +","Methods of Java Period + +Method: Temporal addTo(Temporal temporal) +Description: It is used to add this period to the specified temporal object. + +Method: long get(TemporalUnit unit) +Description: It is used to get the value of the requested unit. + +Method: int getYears() +Description: It is used to get the amount of years of this period. + +Method: boolean isZero() +Description: It is used to check if all three units of this period are zero. + +Method: Period minus(TemporalAmount amountToSubtract) +Description: It is used to return a copy of this period with the specified period subtracted. + +Method: static Period of(int years, int months, int days) +Description: It is used to obtain a Period representing a number of years, months and days. + +Method: Period plus(TemporalAmount amountToAdd) +Description: It is used to return a copy of this period with the specified period added. + +Method: static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) +Description: It obtains a Period consisting of the number of years, months, and days between two dates. + +Method: boolean equals(Object obj) +Description: It checks if this period is equal to another period. + +Method: IsoChronology getChronology() +Description: It gets the chronology of this period, which is the ISO calendar system. + +Method: int getDays() +Description: It gets the amount of days of this period. + +Method: int getMonths() +Description: It gets the amount of months of this period. + +Method: List getUnits() +Description: It gets the set of units supported by this period. + +Method: Period multipliedBy(int scalar) +Description: It returns a new instance with each element in this period multiplied by the specified scalar. + +Method: Period normalized() +Description: It returns a copy of this period with the years and months normalized. + +Method: Period plusDays(long daysToAdd) +Description: It returns a copy of this period with the specified days added. + +Method: Period plusMonths(long monthsToAdd) +Description: It returns a copy of this period with the specified months added. + +Method: Period plusYears(long yearsToAdd) +Description: It returns a copy of this period with the specified years added. + +Method: Temporal subtractFrom(Temporal temporal) +Description: It subtracts this period from the specified temporal object. + +Method: Period negated() +Description: It returns a new instance with each amount in this period negated." +"Can you provide an example of Java Period: addTo()? +","PeriodExample1.java + +import java.time.*; +import java.time.temporal.Temporal; +public class PeriodExample1 { + public static void main(String[] args) { + Period period = Period.ofDays(24); + Temporal temp = period.addTo(LocalDate.now()); + System.out.println(temp); + } +} + +Output: +2017-02-24" +"Can you provide an example of Java Period: of()? +","PeriodExample2.java + +import java.time.Period; +public class PeriodExample2 { +public static void main(String[] args) { + Period period = Period.of(2017,02,16); + System.out.println(period.toString()); +} +} + +Output: +P2017Y2M16D" +"Can you provide an example of Java Period: minus()? +","PeriodExample3.java + +import java.time.Period; +public class PeriodExample3 { + public static void main(String[] args) { + Period period1 = Period.ofMonths(4); + Period period2 = period1.minus(Period.ofMonths(2)); + System.out.println(period2); + } +} + +Output: +P2M" +"Can you provide an example of Java Period: plus()? +","PeriodExample4.java + +import java.time.Period; +public class PeriodExample4 { + public static void main(String[] args) { + Period period1 = Period.ofMonths(4); + Period period2 = period1.plus(Period.ofMonths(2)); + System.out.println(period2); + } +} + +Output: +P6M" +"What is Java Duration class? +",Java Duration class is used to measures time in seconds and nanoseconds. It inherits the Object class and implements the Comparable interface. +"What is the class declaration for Java Duration class? +","Let's see the declaration of java.time.Duration class. + +public final class Duration extends Object +implements TemporalAmount, Comparable, Serializable " +"What are the Methods of Java Duration? +","Methods of Java Duration + +Method: Temporal addTo(Temporal temporal) +Description: It is used to add this duration to the specified temporal object. + +Method: static Duration between(Temporal startInclusive, Temporal endExclusive) +Description: It is used to obtain a Duration representing the duration between two temporal objects. + +Method: long get(TemporalUnit unit) +Description: It is used to get the value of the requested unit. + +Method: boolean isNegative() +Description: It is used to check if this duration is negative, excluding zero. + +Method: boolean isZero() +Description: It is used to check if this duration is zero length. + +Method: Duration minus(Duration duration) +Description: It is used to return a copy of this duration with the specified duration subtracted. + +Method: Duration plus(Duration duration) +Description: It is used to return a copy of this duration with the specified duration added. + +Method: Duration abs() +Description: It returns a copy of this duration with a positive length. + +Method: static Duration between(Temporal startInclusive, Temporal endExclusive) +Description: It obtains a Duration representing the duration between two temporal objects. + +Method: int compareTo(Duration otherDuration) +Description: It compares the given duration to the specified Duration. + +Method: int getNano() +Description: It gets the number of nanoseconds within the second in this duration. + +Method: long getSeconds() +Description: It gets the number of seconds in this duration. + +Method: static Duration of(long amount, TemporalUnit unit) +Description: It obtains a Duration representing an amount in the specified unit. + +Method: static Duration ofDays(long days) +Description: It obtains a Duration representing a number of standard 24 hour days. + +Method: static Duration ofHours(long hours) +Description: It obtains a Duration representing a number of standard hours. + +Method: static Duration ofMillis(long millis) +Description: It obtains a Duration representing a number of milliseconds. + +Method: static Duration ofMinutes(long minutes) +Description: It obtains a Duration representing a number of standard minutes. + +Method: static Duration ofNanos(long nanos) +Description: It obtains a Duration representing a number of nanoseconds. + +Method: static Duration ofSeconds(long seconds) +Description: It obtains a Duration representing a number of seconds." +"Can you provide an example of Java Duration: get()? +","DurationExample1.java + +import java.time.*; +import java.time.temporal.ChronoUnit; +public class DurationExample1 { + public static void main(String[] args) { + Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX); + System.out.println(d.get(ChronoUnit.SECONDS)); + } +} + +Output: +43199" +"Can you provide an example of Java Duration: isNegative()? +","DurationExample2.java + +import java.time.*; +public class DurationExample2 { + public static void main(String[] args) { + Duration d1 = Duration.between(LocalTime.MAX,LocalTime.NOON); + System.out.println(d1.isNegative()); + Duration d2 = Duration.between(LocalTime.NOON,LocalTime.MAX); + System.out.println(d2.isNegative()); + } +} + +Output: +true +false" +"Can you provide an example of Java Duration: between()? +","DurationExample3.java + +import java.time.*; +import java.time.temporal.ChronoUnit; +public class DurationExample3 { + public static void main(String[] args) { + Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX); + System.out.println(d.get(ChronoUnit.SECONDS)); + } +} + +Output: +43199" +"Can you provide an example of Java Duration: minus()? +","DurationExample4.java + +import java.time.*; +public class DurationExample4 { + public static void main(String[] args) { + Duration d1 = Duration.between(LocalTime.NOON,LocalTime.MAX); + System.out.println(d1.getSeconds()); + Duration d2 = d1.minus(d1); + System.out.println(d2.getSeconds()); + } +} + +Output: +43199 +0" +"Can you provide an example of Java Duration: plus()? +","DurationExample5.java + +import java.time.*; +public class DurationExample5 { + public static void main(String[] args) { + Duration d1 = Duration.between(LocalTime.NOON,LocalTime.MAX); + System.out.println(d1.getSeconds()); + Duration d2 = d1.plus(d1); + System.out.println(d2.getSeconds()); + } +} + +Output: +43199 +86399" +"What is Java Instant Class? +","DurationExample5.java + +import java.time.*; +public class DurationExample5 { + public static void main(String[] args) { + Duration d1 = Duration.between(LocalTime.NOON,LocalTime.MAX); + System.out.println(d1.getSeconds()); + Duration d2 = d1.plus(d1); + System.out.println(d2.getSeconds()); + } +} + +Output: +43199 +86399" +"What is the class declaration for Java Instant class? +","Let's see the declaration of java.time.Instant class. + +public final class Instant extends Object +implements Temporal, TemporalAdjuster, Comparable, Serializable " +"What are the Methods of Java Instant? +","Methods of Java Instant + +Method: Temporal adjustInto(Temporal temporal). +Description: It is used to adjust the specified temporal object to have this instant. + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this instant as an int. + +Method: boolean isSupported(TemporalField field) +Description: It is used to check if the specified field is supported. + +Method: Instant minus(TemporalAmount amountToSubtract) +Description: It is used to return a copy of this instant with the specified amount subtracted. + +Method: static Instant now() +Description: It is used to obtain the current instant from the system clock. + +Method: static Instant parse(CharSequence text) +Description: It is used to obtain an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z. + +Method: Instant plus(TemporalAmount amountToAdd) +Description: It is used to return a copy of this instant with the specified amount added. + +Method: Instant with(TemporalAdjuster adjuster) +Description: It is used to return an adjusted copy of this instant. + +Method: Instant plus(long amountToAdd, TemporalUnit unit) +Description: It returns a copy of this instant with the specified amount added. + +Method: OffsetDateTime atOffset(ZoneOffset offset) +Description: It combines the instant with an offset to create an OffsetDateTime. + +Method: ZonedDateTime atZone(ZoneId zone) +Description: It combines the instant with a time-zone to create a ZonedDateTime. + +Method: int compareTo(Instant otherInstant) +Description: It compares the instant to the specified instant. + +Method: boolean equals(Object otherInstant) +Description: It checks if the instant is equal to the specified instant. + +Method: static Instant from(TemporalAccessor temporal) +Description: It obtains an instance of Instant from a temporal object. + +Method: int get(TemporalField field) +Description: It gets the value of the specified field from this instant as an int. + +Method: long getEpochSecond() +Description: It gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. + +Method: long getLong(TemporalField field) +Description: It gets the value of the specified field from this instant as a long. + +Method: int getNano() +Description: It gets the number of nanoseconds, later along the time-line, from the start of the second. + +Method: int hashCode() +Description: It returns a hash code for this instant. + +Method: boolean isAfter(Instant otherInstant) +Description: It checks if the instant is after the specified instant. + +Method: boolean isBefore(Instant otherInstant) +Description: It checks if the instant is before the specified instant. + +Method: static Instant ofEpochMilli(long epochMilli) +Description: It obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z. + +Method: static Instant ofEpochSecond(long epochSecond) +Description: It obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z. + +Method: Instant truncatedTo(TemporalUnit unit) +Description: It returns a copy of the Instant truncated to the specified unit. + +Method: long until(Temporal endExclusive, TemporalUnit unit) +Description: It calculates the amount of time until another instant in terms of the specified unit. + +Method: String toString() +Description: A string representation of the instant using ISO-8601 representation." +"Can you provide an example of Java Instant: parse()? +","InstantExample1.java + +import java.time.Instant; +public class InstantExample1 { + public static void main(String[] args) { + Instant inst = Instant.parse(""2017-02-03T10:37:30.00Z""); + System.out.println(inst); + } +} + +Output: +2017-02-03T10:37:30Z" +"Can you provide an example of Java Instant: now()? +","InstantExample2.java + +import java.time.Instant; +public class InstantExample2 { + public static void main(String[] args) { + Instant instant = Instant.now(); + System.out.println(instant); + } +} + +Output: +2017-02-03T06:11:01.194Z" +"Can you provide an example of Java Instant: minus()? +","InstantExample3.java + +import java.time.*; +public class InstantExample3 { + public static void main(String[] args) { + Instant instant = Instant.parse(""2017-02-03T11:25:30.00Z""); + instant = instant.minus(Duration.ofDays(125)); + System.out.println(instant); + } +} + +Output: +2016-10-01T11:25:30Z" +"Can you provide an example of Java Instant: plus()? +","InstantExample4.java + +import java.time.*; +public class InstantExample4 { + public static void main(String[] args) { + Instant inst1 = Instant.parse(""2017-02-03T11:25:30.00Z""); + Instant inst2 = inst1.plus(Duration.ofDays(125)); + System.out.println(inst2); + } +} + +Output: +2017-06-08T11:25:30Z" +"Can you provide an example of Java Instant: isSupported()? +","InstantExample5.java + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +public class InstantExample5 { + public static void main(String[] args) { + Instant inst = Instant.parse(""2017-02-03T11:35:30.00Z""); + System.out.println(inst.isSupported(ChronoUnit.DAYS)); + System.out.println(inst.isSupported(ChronoUnit.YEARS)); + } +} + +Output: +true +false" +"What is Java DayOfWeek enum? +","In Java the DayOfWeek is an enum representing the 7 days of the week. In addition with the textual enum name, every day-of-week has an int value." +"What is the class declaration for Java DayOfWeek enum? +","Let's see the declaration of java.time.DayOfWeek. + +public enum DayOfWeek extends Enum implements TemporalAccessor, TemporalAdjuster " +"What are Enum constants? +","Enum Constants + +Constants: SUNDAY +Description: The singleton instance for the day-of-week of Sunday. + +Constants: MONDAY +Description: The singleton instance for the day-of-week of Monday. + +Constants: TUESDAY +Description: The singleton instance for the day-of-week of Tuesday. + +Constants: WEDNESDAY +Description: The singleton instance for the day-of-week of Wednesday. + +Constants: THURSDAY +Description: The singleton instance for the day-of-week of Thursday. + +Constants: FRIDAY +Description: The singleton instance for the day-of-week of Friday. + +Constants: SATURDAY +Description: The singleton instance for the day-of-week of Saturday." +"What are the Methods of Java DayOfWeek? +","Methods of Java DayOfWeek + + + + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this day-of-week as an int. + +Method: boolean isSupported(TemporalField field) +Description: It is used to check if the specified field is supported. + +Method: DayOfWeek minus(long days) +Description: It is used to return the day-of-week that is the specified number of days before this one. + +Method: DayOfWeek plus(long days) +Description: It is used to return the day-of-week that is the specified number of days after this one. + +Method: static DayOfWeek of(int dayOfWeek) +Description: It is used to obtain an instance of DayOfWeek from an int value. + +Method: static DayOfWeek[] values() +Description: It is used to return an array containing the constants of this enum type, in the order they are declared. + +Method: Temporal adjustInto(Temporal temporal) +Description: It adjusts the specified temporal object to have this day-of-week. + +Method: long getLong(TemporalField field) +Description: It gets the value of the specified field from this day-of-week as a long. + +Method: String getDisplayName(TextStyle style, Locale locale) +Description: It gets the textual representation, such as 'Mon' or 'Friday'. + +Method: int getValue() +Description: It gets the day-of-week int value. + +Method: R query(TemporalQuery query) +Description: It queries this day-of-week using the specified query. + +Method: ValueRange range(TemporalField field) +Description: It gets the range of valid values for the specified field. + +Method: static DayOfWeek valueOf(String name) +Description: It returns the enum constant of this type with the specified name." +"What are the Methods inherited from class java.lang.Enum? +","1. clone +2. compareTo +3. equals +4. finalize +5. getDeclaringClass +6. hashCode +7. name +8. ordinal +9. toString +10. valueOf" +"Can you provide an example of Java DayOfWeek: get()? +","DayOfWeekExample1.java + +import java.time.*; +import java.time.temporal.ChronoField; +public class DayOfWeekExample1 { + public static void main(String[] args) { + LocalDate localDate = LocalDate.of(2017, Month.JANUARY, 25); + DayOfWeek dayOfWeek = DayOfWeek.from(localDate); + System.out.println(dayOfWeek.get(ChronoField.DAY_OF_WEEK)); + } +} + +Output: +3" +"Can you provide an example of Java DayOfWeek: of()? +","Java DayOfWeek Example: of() +DayOfWeekExample2.java + +import java.time.DayOfWeek; +public class DayOfWeekExample2 { + public static void main(String[] args) { + DayOfWeek day = DayOfWeek.of(5); + System.out.println(day.name()); + System.out.println(day.ordinal()); + System.out.println(day.getValue()); + } +} + +Output: +FRIDAY +4 +5" +"Can you provide an example of Java DayOfWeek: plus()? +","DayOfWeekExample3.java + +import java.time.*; +public class DayOfWeekExample3 { + public static void main(String[] args) { + LocalDate date = LocalDate.of(2017, Month.JANUARY, 31); + DayOfWeek day = DayOfWeek.from(date); + System.out.println(day.getValue()); + day = day.plus(3); + System.out.println(day.getValue()); + } +} + +Output: +2 +5" +"Can you provide an example of Java DayOfWeek: minus()? +","DayOfWeekExample4.java + +import java.time.*; +public class DayOfWeekExample4 { + public static void main(String[] args) { + LocalDate date = LocalDate.of(2017, Month.JANUARY, 31); + DayOfWeek day = DayOfWeek.from(date); + System.out.println(day.getValue()); + day = day.minus(3); + System.out.println(day.getValue()); + } +} + +Output: +2 +6" +"Can you provide an example of Java DayOfWeek: getValue()? +","DayOfWeekExample5.java + +import java.time.*; +import java.time.DayOfWeek; + +public class DayOfWeekExample5 +{ + public static void main(String ar[]) + { + LocalDate localDate = LocalDate.of(2021, Month.SEPTEMBER, 13); + DayOfWeek dayOfWeek = DayOfWeek.from(localDate); + System.out.println(""Day of the Week on"" + "" 13th September 2021 - "" + dayOfWeek.name()); + int val = dayOfWeek.getValue(); + System.out.println(""Int Value of "" + dayOfWeek.name() + "" - "" + val); + } +} + +Output: +Day of the Week on 13th September 2021 - MONDAY +Int Value of MONDAY - 1" +"What is Java Month enum? +","In Java, the Month is an enum represents the 12 months of a year. In addition with the textual enum name, every month-of-year has an integer value." +"What is the class declaration for Java Month enum? +","Let's see the declaration of java.time.Month. + +public enum Month extends Enum implements TemporalAccessor, TemporalAdjuster" +"What are enum Constants? +","enum Constants + + + +enum constant: enum constant: JANUARY +Description: The singleton instance for the month of January with 31 days. + +enum constant: FEBRUARY +Description: The singleton instance for the month of February with 28 days, or 29 in a leap year. + +enum constant: MARCH +Description: The singleton instance for the month of March with 31 days. + +enum constant: APRIL +Description: The singleton instance for the month of April with 30 days. + +enum constant: MAY +Description: The singleton instance for the month of May with 31 days. + +enum constant: JUNE +Description: The singleton instance for the month of June with 30 days. + +enum constant: JULY +Description: The singleton instance for the month of July with 31 days. + +enum constant: AUGUST +Description: The singleton instance for the month of August with 31 days. + +enum constant: SEPTEMBER +Description: The singleton instance for the month of September with 30 days. + +enum constant: OCTOBER +Description: The singleton instance for the month of October with 31 days. + +enum constant: NOVEMBER +Description: The singleton instance for the month of November with 30 days. + +enum constant: DECEMBER +Description: The singleton instance for the month of December with 31 days." +"What are the Methods of Java Month? + +","Methods of Java Month + + + +Method: int getValue() +Description: It is used to get the month-of-year int value + +Method: int get(TemporalField field) +Description: It is used to get the value of the specified field from this month-of-year as an int. + +Method: int length(boolean leapYear) +Description: It is used to get the length of this month in days. + +Method: int maxLength() +Description: It is used to get the maximum length of this month in days. + +Method: int minLength() +Description: It is used to get the minimum length of this month in days. + +Method: Month minus(long months) +Description: It is used to return the month-of-year that is the specified number of months before this one. + +Method: Month plus(long months) +Description: It is used to return the month-of-year that is the specified number of quarters after this one. + +Method: static Month of(int month) +Description: It is used to obtain an instance of Month from an int value. + +Method: Temporal adjustInto(Temporal temporal) +Description: It adjusts the specified temporal object to have the same month-of-year as this object. + +Method: int firstDayOfYear(boolean leapYear) +Description: It gets the day-of-year corresponding to the first day of this month. + +Method: Month firstMonthOfQuarter() +Description: It gets the month corresponding to the first month of this quarter. + +Method: static Month from(TemporalAccessor temporal) +Description: It obtains an instance of Month from a temporal object. + +Method: String getDisplayName(TextStyle style, Locale locale) +Description: It gets the textual representation, such as 'Jan' or 'December'. + +Method: long getLong(TemporalField field) +Description: It gets the value of the specified field from this month-of-year as a long. + +Method: boolean isSupported(TemporalField field) +Description: It checks if the specified field is supported. + +Method: R query(TemporalQuery query) +Description: It queries the offset using the specified query. + +Method: ValueRange range(TemporalField field) +Description: It gets the range of valid values for the specified field. + +Method: static Month valueOf(String name) +Description: It returns the enum constant of this type with the specified name. + +Method: static Month[] values() +Description: It returns an array containing the constants of this enum type, in the order they are declared." +"Can you provide an example of Java Month enum? +","MonthEnumExample1.java + +import java.time.*; +import java.time.temporal.*; +public class MonthEnumExample1 { + public static void main(String[] args) { + Month month = Month.valueOf(""January"".toUpperCase()); + System.out.printf(""For the month of %s all Sunday are:%n"", month); + LocalDate localdate = Year.now().atMonth(month).atDay(1). + with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY)); + Month mi = localdate.getMonth(); + while (mi == month) { + System.out.printf(""%s%n"", localdate); + localdate = localdate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); + mi = localdate.getMonth(); + } + } +} +Output: +For the month of JANUARY all Sunday are: +2017-01-01 +2017-01-08 +2017-01-15 +2017-01-22 +2017-01-29" +"What is java.util.Date? +","The java.util.Date class represents date and time in java. It provides constructors and methods to deal with date and time in java. + +The java.util.Date class implements Serializable, Cloneable and Comparable interface. It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces. + +After Calendar class, most of the constructors and methods of java.util.Date class has been deprecated. Here, we are not giving list of any deprecated constructor and method. + " +"What is java.util.Date Constructors? +","java.util.Date Constructors + +Constructor: Date() +Description: Creates a date object representing current date and time. + +Constructor: Date(long milliseconds) +Description: Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.." +What are the Methods of java.util.Date?,"java.util.Date Methods + +Method: boolean after(Date date) +Description: tests if current date is after the given date. + +Method: boolean before(Date date) +Description: tests if current date is before the given date. + +Method: Object clone() +Description: returns the clone object of current date. + +Method: int compareTo(Date date) +Description: compares current date with given date. + +Method: boolean equals(Date date) +Description: compares current date with given date for equality. + +Method: static Date from(Instant instant) +Description: returns an instance of Date object from Instant date. + +Method: long getTime() +Description: returns the time represented by this date object. + +Method: int hashCode() +Description: returns the hash code value for this date object. + +Method: void setTime(long time) +Description: changes the current date and time to given time. + +Method: Instant toInstant() +Description: converts current date into Instant object. + +Method: String toString() +Description: converts this date into Instant object." +" Can you provide an example of Java.util.Date? +","Let's see the example to print date in java using java.util.Date class. + +1st way: + +java.util.Date date=new java.util.Date(); +System.out.println(date); + +Output: +Wed Mar 27 08:22:02 IST 2015 + + +2nd way: + +long millis=System.currentTimeMillis(); +java.util.Date date=new java.util.Date(millis); +System.out.println(date); + +Output: +Wed Mar 27 08:22:02 IST 2015" +"What is java.sql.Date? +","The java.sql.Date class represents the only date in Java. It inherits the java.util.Date class. + +The java.sql.Date instance is widely used in the JDBC because it represents the date that can be stored in a database. + +Some constructors and methods of java.sql.Date class has been deprecated. Here, we are not giving the list of any deprecated constructor and method." +"What is java.sql.Date Constructor? +","java.sql.Date Constructor + +Constructor: Date(long milliseconds) +Description: Creates a sql date object for the given milliseconds since January 1, 1970, 00:00:00 GMT." +"What are the Methods of java.sql.Date? +","java.sql.Date Methods + +Method: void setTime(long time) +Description: changes the current sql date to given time. + +Method: Instant toInstant() +Description: converts current sql date into Instant object. + +Method: LocalDate toLocalDate() +Description: converts current sql date into LocalDate object. + +Method: String toString() +Description: converts this sql date object to a string. + +Method: static Date valueOf(LocalDate date) +Description: returns sql date object for the given LocalDate. + +Method: static Date valueOf(String date) +Description: returns sql date object for the given String." +"Can you provide an example of Java.sql.Date: get current date? +","Let's see the example to print date in java using the java.sql.Date class. + +FileName: SQLDateExample.java + +public class SQLDateExample { + public static void main(String[] args) { + long millis=System.currentTimeMillis(); + java.sql.Date date=new java.sql.Date(millis); + System.out.println(date); + } +} + +Output: +2015-03-30" +"Can you provide an example of Java String to java.sql.Date? +","Let's see the example to convert string into java.sql.Date using the valueOf() method. + +FileName: StringToSQLDateExample.java + +import java.sql.Date; +public class StringToSQLDateExample { +public static void main(String[] args) { + String str=""2015-03-31""; + Date date=Date.valueOf(str);//converting string into sql date + System.out.println(date); +} +} + +Output: +2015-03-31" +"Can you provide an example of java.sql.Date: void setTime()? +","Let's see the working of the setTime() method. + +FileName: SetTimeExample.java + +// important import statements +import java.util.Calendar; +import java.util.Date; +public class SetTimeExample +{ +// main method +public static void main(String[] argvs) +{ +// A date object is created with the specified time. +Date d = new Date(); +System.out.println(""Initial date is: "" + d); +// setting the time for 1000000 milliseconds after +// 01 January, 1970, 00:00:00 GMT. +d.setTime(1000000); +// Printing the time +System.out.println(""Date after the setting the time is: "" + d); +} +} + +Output: +Initial date is: Fri Nov 26 11:52:20 GMT 2021 +Date after the setting the time is: Thu Jan 01 00:16:40 GMT 1970 +" +"Can you provide an example of java.sql.Date: void toLocalDate()? +","Let's see the working of the toLocalDate() method. + +FileName: ToLocalDateExample.java + +// important import statement +import java.util.*; +import java.time.*; +public class ToLocalDateExample +{ +// main method +public static void main(String[] argvs) +{ +// Getting the instance of LocalDateTime +LocalDateTime dtm = LocalDateTime.now(); +// Getting the LocalDate representation of the LocalDateTime +// using the toLocalDate() method +System.out.println(""The date is: "" + dtm.toLocalDate()); +} +} + +Output: +The date is: 2021-11-26" +"Can you provide an example of java.sql.Date: void toInstant()? +","Let's see the working of the toInstant() method. + +FileName: ToInstantExample.java + +// important import statement +import java.util.Calendar; +import java.util.Date; +import java.time.Instant; +public class ToInstantExample +{ +// main method +public static void main(String argvs[]) +{ +// Creating an object of Calendar +// by invoking the getInstance method +Calendar cln = Calendar.getInstance(); +// Setting the Month +// The months begin with 0. 0 means January +cln.set(Calendar.MONTH, 07); +// Setting Date +cln.set(Calendar.DATE, 12); +// Setting Year +cln.set(Calendar.YEAR, 2021); +// Creating an object of the class Date +// with the mentioned time. +Date d = cln.getTime(); +Instant instt = d.toInstant(); +System.out.println(""The original Date is: "" + d.toString()); +System.out.println(""The instant is: "" + instt); +} +} + +Output: +The original Date is: Thu Aug 12 12:41:01 GMT 2021 +The instant is: 2021-08-12T12:41:01.635Z" +"What is Java Calendar Class? +","Java Calendar class is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the Comparable interface." +"What is the class declaration for Java Calendar class? +","public abstract class Calendar extends Object +implements Serializable, Cloneable, Comparable " +"What are the List of Calendar Methods? +","Method: public void add(int field, int amount) +Description: Adds the specified (signed) amount of time to the given calendar field. + +Method: public boolean after (Object when) +Description: The method Returns true if the time represented by this Calendar is after the time represented by when Object. + +Method: public boolean before(Object when) +Description: The method Returns true if the time represented by this Calendar is before the time represented by when Object. + +Method: public final void clear(int field) +Description: Set the given calendar field value and the time value of this Calendar undefined. + +Method: public Object clone() +Description: Clone method provides the copy of the current object. + +Method: public int compareTo(Calendar anotherCalendar) +Description: The compareTo() method of Calendar class compares the time values (millisecond offsets) between two calendar object. + +Method: protected void complete() +Description: It fills any unset fields in the calendar fields. + +Method: protected abstract void computeFields() +Description: It converts the current millisecond time value time to calendar field values in fields[]. + +Method: protected abstract void computeTime() +Description: It converts the current calendar field values in fields[] to the millisecond time value time. + +Method: public boolean equals(Object object) +Description: The equals() method compares two objects for equality and Returns true if they are equal. + +Method: +Description: + +Method: public int get(int field) +Description: In get() method fields of the calendar are passed as the parameter, and this method Returns the value of fields passed as the parameter. + +Method: public int getActualMaximum(int field) +Description: Returns the Maximum possible value of the calendar field passed as the parameter to getActualMaximum() method. + +Method: public int getActualMinimum(int field) +Description: Returns the Minimum possible value of the calendar field passed as parameter to getActualMinimum() methot. + +Method: public static Set getAvailableCalendarTypes() +Description: Returns a set which contains string set of all available calendar type supported by Java Runtime Environment. + +Method: public static Locale[] getAvailableLocales() +Description: Returns an array of all locales available in java runtime environment. + +Method: public String getCalendarType() +Description: Returns in string all available calendar type supported by Java Runtime Environment. + +Method: public String getDisplayName(int field, int style, Locale locale) +Description: Returns the String representation of the calendar field value passed as the parameter in a given style and local. + +Method: public Map getDisplayNames(int field, int style, Locale locale) +Description: Returns Map representation of the calendar field value passed as the parameter in a given style and local. + +Method: public int getFirstDayOfWeek() +Description: Returns the first day of the week in integer form. + +Method: public abstract int getGreatestMinimum(int field) +Description: This method returns the highest minimum value of Calendar field passed as the parameter. + +Method: public static Calendar getInstance() +Description: This method is used with calendar object to get the instance of calendar according to current time zone set by java runtime environment + +Method: public abstract int getLeastMaximum(int field) +Description: Returns smallest value from all maximum value for the field specified as the parameter to the method. + +Method: public abstract int getMaximum(int field) +Description: This method is used with calendar object to get the maximum value of the specified calendar field as the parameter. + +Method: public int getMinimalDaysInFirstWeek() +Description: Returns required minimum days in integer form. + +Method: public abstract int getMinimum(int field) +Description: This method is used with calendar object to get the minimum value of specified calendar field as the parameter. + +Method: public final Date getTime() +Description: This method gets the time value of calendar object and Returns date. + +Method: public long getTimeInMillis() +Description: Returns the current time in millisecond. This method has long as return type. + +Method: public TimeZone getTimeZone() +Description: This method gets the TimeZone of calendar object and Returns a TimeZone object. + +Method: public int getWeeksInWeekYear() +Description: Return total weeks in week year. Weeks in week year is returned in integer form. + +Method: public int getWeekYear() +Description: This method gets the week year represented by current Calendar. + +Method: public int hashCode() +Description: All other classes in Java overload hasCode() method. This method Returns the hash code for calendar object. + +Method: protected final int internalGet(int field) +Description: This method returns the value of the calendar field passed as the parameter. + +Method: Public boolean isLenient() +Description: Return Boolean value. True if the interpretation mode of this calendar is lenient; false otherwise. + +Method: public final boolean isSet(int field) +Description: This method checks if specified field as the parameter has been set or not. If not set then it returns false otherwise true. + +Method: public boolean isWeekDateSupported() +Description: Checks if this calendar supports week date. The default value is false. + +Method: public abstract void roll(int field, boolean up) +Description: This method increase or decrease the specified calendar field by one unit without affecting the other field + +Method: public void set(int field, int value) +Description: Sets the specified calendar field by the specified value. + +Method: public void setFirstDayOfWeek(int value) +Description: Sets the first day of the week. The value which is to be set as the first day of the week is passed as parameter. + +Method: public void setMinimalDaysInFirstWeek(int value) +Description: Sets the minimal days required in the first week. The value which is to be set as minimal days in first week is passed as parameter. + +Method: public final void setTime(Date date) +Description: Sets the Time of current calendar object. A Date object id passed as the parameter. + +Method: public void setTimeInMillis(long millis) +Description: Sets the current time in millisecond. + +Method: public void setTimeZone(TimeZone value) +Description: Sets the TimeZone with passed TimeZone value (object) as the parameter. + +Method: public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) +Description: Sets the current date with specified integer value as the parameter. These values are weekYear, weekOfYear and dayOfWeek. + +Method: public final Instant toInstant() +Description: The toInstant() method convert the current object to an instant. + +Method: public String toString() +Description: Returns string representation of the current object. " +"Can you provide an example of Java Calendar Class? +","import java.util.Calendar; +public class CalendarExample1 { + public static void main(String[] args) { + Calendar calendar = Calendar.getInstance(); + System.out.println(""The current date is : "" + calendar.getTime()); + calendar.add(Calendar.DATE, -15); + System.out.println(""15 days ago: "" + calendar.getTime()); + calendar.add(Calendar.MONTH, 4); + System.out.println(""4 months later: "" + calendar.getTime()); + calendar.add(Calendar.YEAR, 2); + System.out.println(""2 years later: "" + calendar.getTime()); + } +} +Output: The current date is : Thu Jan 19 18:47:02 IST 2017 +15 days ago: Wed Jan 04 18:47:02 IST 2017 +4 months later: Thu May 04 18:47:02 IST 2017 +2 years later: Sat May 04 18:47:02 IST 2019" +"Can you provide an example of Java Calendar Class: get()? +","import java.util.*; +public class CalendarExample2{ + public static void main(String[] args) { + Calendar calendar = Calendar.getInstance(); + System.out.println(""At present Calendar's Year: "" + calendar.get(Calendar.YEAR)); + System.out.println(""At present Calendar's Day: "" + calendar.get(Calendar.DATE)); + } +} +Output: At present Calendar's Year: 2017 + At present Calendar's Day: 20" +"Can you provide an example of Java Calendar Class: getInstance()? +","import java.util.*; +public class CalendarExample3{ + public static void main(String[] args) { + Calendar calendar = Calendar.getInstance(); + System.out.print(""At present Date And Time Is: "" + calendar.getTime()); + } +} +Output: At present Date And Time Is: Fri Jan 20 14:26:19 IST 2017" +"Can you provide an example of Java Calendar Class: getMaximum()? +","import java.util.*; +public class CalendarExample4 { + public static void main(String[] args) { + Calendar calendar = Calendar.getInstance(); + int maximum = calendar.getMaximum(Calendar.DAY_OF_WEEK); + System.out.println(""Maximum number of days in week: "" + maximum); + maximum = calendar.getMaximum(Calendar.WEEK_OF_YEAR); + System.out.println(""Maximum number of weeks in year: "" + maximum); + } +} +Output: Maximum number of days in week: 7 + Maximum number of weeks in year: 53" +Can you provide an example of Java Calendar Class: getMinimum()?,"import java.util.*; +public class CalendarExample5 { + public static void main(String[] args) { + Calendar cal = Calendar.getInstance(); + int maximum = cal.getMinimum(Calendar.DAY_OF_WEEK); + System.out.println(""Minimum number of days in week: "" + maximum); + maximum = cal.getMinimum(Calendar.WEEK_OF_YEAR); + System.out.println(""Minimum number of weeks in year: "" + maximum); + } +} +Output: Minimum number of days in week: 1 + Minimum number of weeks in year: 1" +What is Java TimeZone Class?,"Java TimeZone class represents a time zone offset, and also figures out daylight savings. It inherits the Object class." +"What is the class declaration for Java TimeZone class? +","public abstract class TimeZone extends Object implements Serializable, Cloneable " +"What are the Methods of Java TimeZone? +","Method: static String[] getAvailableIDs() +Description: It is used to get all the available IDs supported. + +Method: static TimeZone getDefault() +Description: It is used to get the default TimeZone for this host. + +Method: String getDisplayName() +Description: It is used to return a name of this time zone suitable for presentation to the user in the default locale. + +Method: String getID() +Description: It is used to get the ID of this time zone + +Method: int getOffset(long date) +Description: It is used to return the offset of this time zone from UTC at the specified date. + +Method: void setID(String ID) +Description: It is used to set the time zone ID " +"Can you provide an example of Java TimeZone class: getAvailableIDs()? +","import java.util.*; +public class TimeZoneExample1 { + public static void main( String args[] ){ + String[] id = TimeZone.getAvailableIDs(); + System.out.println(""In TimeZone class available Ids are: ""); + for (int i=0; i c) +Description: It is used to insert the specified collection elements in the invoking collection. + +Method: public boolean remove(Object element) +Description: It is used to delete an element from the collection. + +Method: public boolean removeAll(Collection c) +Description: It is used to delete all the elements of the specified collection from the invoking collection. + +Method: default boolean removeIf(Predicate filter) +Description: It is used to delete all the elements of the collection that satisfy the specified predicate. + +Method: public boolean retainAll(Collection c) +Description: It is used to delete all the elements of invoking collection except the specified collection. + +Method: public int size() +Description: It returns the total number of elements in the collection. + +Method: public void clear() +Description: It removes the total number of elements from the collection. + +Method: public boolean contains(Object element) +Description: It is used to search an element. + +Method: public boolean containsAll(Collection c) +Description: It is used to search the specified collection in the collection. + +Method: public Iterator iterator() +Description: It returns an iterator. + +Method: public Object[] toArray() +Description: It converts collection into array. + +Method: public T[] toArray(T[] a) +Description: It converts collection into array. Here, the runtime type of the returned array is that of the specified array. + +Method: public boolean isEmpty() +Description: It checks if collection is empty. + +Method: default Stream parallelStream() +Description: It returns a possibly parallel Stream with the collection as its source. + +Method: default Stream stream() +Description: It returns a sequential Stream with the collection as its source. + +Method: default Spliterator spliterator() +Description: It generates a Spliterator over the specified elements in the collection. + +Method: public boolean equals(Object element) +Description: It matches two collections. + +Method: public int hashCode() +Description: It returns the hash code number of the collection. " +"What is Iterator interface? + +",Iterator interface provides the facility of iterating the elements in a forward direction only. +"What are the Methods of Iterator interface? +","Methods of Iterator interface +There are only three methods in the Iterator interface. They are: + +Method: public boolean hasNext() +Description:It returns true if the iterator has more elements otherwise it returns false. + +Method: public Object next() +Description:It returns the element and moves the cursor pointer to the next element. + +Method: public void remove() +Description:It removes the last elements returned by the iterator. It is less used." +"What is iterable Interface? +","he Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface. + +It contains only one abstract method. i.e., + +Iterator iterator() +It returns the iterator over the elements of type T." +"What is Collection Interface? +","The Collection interface is the interface which is implemented by all the classes in the collection framework. It declares the methods that every collection will have. In other words, we can say that the Collection interface builds the foundation on which the collection framework depends. + +Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection interface." +"What is Java ArrayList? +","Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++. + +The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally. + +It inherits the AbstractList class and implements List interface. + +The important points about the Java ArrayList class are: + +Java ArrayList class can contain duplicate elements. +Java ArrayList class maintains insertion order. +Java ArrayList class is non synchronized. +Java ArrayList allows random access because the array works on an index basis. +In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list. +We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class in such cases. For example: + +ArrayList al = ArrayList(); // does not work +ArrayList al = new ArrayList(); // works fine " +"What is the class declaration for ArrayList class? +","Let's see the declaration for java.util.ArrayList class. + +public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable " +"What are the Constructors of the ArrayList? +","Constructors of ArrayList + +Constructor: ArrayList() +Description: It is used to build an empty array list. + +Constructor: ArrayList(Collection c) +Description: It is used to build an array list that is initialized with the elements of the collection c. + +Constructor: ArrayList(int capacity) +Description: It is used to build an array list that has the specified initial capacity." +"What are the Methods of ArrayList? +","Methods of ArrayList + + + + +Method: void add(int index, E element) +Description: It is used to insert the specified element at the specified position in a list. + +Method: boolean add(E e) +Description: It is used to append the specified element at the end of a list. + +Method: boolean addAll(Collection c) +Description: It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. + +Method: boolean addAll(int index, Collection c) +Description: It is used to append all the elements in the specified collection, starting at the specified position of the list. + +Method: void clear() +Description: It is used to remove all of the elements from this list. + +Method: void ensureCapacity(int requiredCapacity) +Description: It is used to enhance the capacity of an ArrayList instance. + +Method: E get(int index) +Description: It is used to fetch the element from the particular position of the list. + +Method: boolean isEmpty() +Description: It returns true if the list is empty, otherwise false. + +Method: Iterator() listIterator() int lastIndexOf(Object o) +Description: It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. + +Method: Object[] toArray() +Description: It is used to return an array containing all of the elements in this list in the correct order. + +Method: T[] toArray(T[] a) +Description: It is used to return an array containing all of the elements in this list in the correct order. + +Method: Object clone() +Description: It is used to return a shallow copy of an ArrayList. + +Method: boolean contains(Object o) +Description: It returns true if the list contains the specified element. + +Method: int indexOf(Object o) +Description: It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. + +Method: E remove(int index) +Description: It is used to remove the element present at the specified position in the list. + +Method: boolean remove(Object o) +Description: It is used to remove the first occurrence of the specified element. + +Method: boolean removeAll(Collection c) +Description: It is used to remove all the elements from the list. + +Method: boolean removeIf(Predicate filter) +Description: It is used to remove all the elements from the list that satisfies the given predicate. + +Method: protected void removeRange(int fromIndex, int toIndex) +Description: It is used to remove all the elements lies within the given range. + +Method: void replaceAll(UnaryOperator operator) +Description: It is used to replace all the elements from the list with the specified element. + +Method: void retainAll(Collection c) +Description: It is used to retain all the elements in the list that are present in the specified collection. + +Method: E set(int index, E element) +Description: It is used to replace the specified element in the list, present at the specified position. + +Method: void sort(Comparator c) +Description: It is used to sort the elements of the list on the basis of the specified comparator. + +Method: Spliterator spliterator() +Description: It is used to create a spliterator over the elements in a list. + +Method: List subList(int fromIndex, int toIndex) +Description: It is used to fetch all the elements that lies within the given range. + +Method: int size() +Description: It is used to return the number of elements present in the list. + +Method: void trimToSize() +Description: It is used to trim the capacity of this ArrayList instance to be the list's current size." +"What are the differences between Java Non-generic and Generic Collection? +","Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic. + +Java new generic collection allows you to have only one type of object in a collection. Now it is type-safe, so typecasting is not required at runtime. + +Let's see the old non-generic example of creating a Java collection. + +ArrayList list=new ArrayList();//creating old non-generic arraylist + +Let's see the new generic example of creating java collection. + +ArrayList list=new ArrayList();//creating new generic arraylist +In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of object in it. If you try to add another type of object, it gives a compile-time error. + + +" +"Can you provide an example of Java ArrayList? +","FileName: ArrayListExample1.java + +import java.util.*; + public class ArrayListExample1{ + public static void main(String args[]){ + ArrayList list=new ArrayList();//Creating arraylist + list.add(""Mango"");//Adding object in arraylist + list.add(""Apple""); + list.add(""Banana""); + list.add(""Grapes""); + //Printing the arraylist object + System.out.println(list); + } +} + +Output: + +[Mango, Apple, Banana, Grapes] + + +" +"How to Sort ArrayList? +","The java.util package provides a utility class Collections, which has the static method sort(). Using the Collections.sort() method, we can easily sort the ArrayList. + +import java.util.*; +class SortArrayList{ + public static void main(String args[]){ + //Creating a list of fruits + List list1=new ArrayList(); + list1.add(""Mango""); + list1.add(""Apple""); + list1.add(""Banana""); + list1.add(""Grapes""); + //Sorting the list + Collections.sort(list1); + //Traversing list through the for-each loop + for(String fruit:list1) + System.out.println(fruit); + + System.out.println(""Sorting numbers...""); + //Creating a list of numbers + List list2=new ArrayList(); + list2.add(21); + list2.add(11); + list2.add(51); + list2.add(1); + //Sorting the list + Collections.sort(list2); + //Traversing list through the for-each loop + for(Integer number:list2) + System.out.println(number); + } + +} + +Output: +Apple +Banana +Grapes +Mango +Sorting numbers... +1 +11 +21 +51 + + + +" +"What are the ways to iterate the elements of the collection in Java? +","There are various ways to traverse the collection elements: + +1.By Iterator interface. +2.By for-each loop. +3.By ListIterator interface. +4.By for loop. +5.By forEach() method. +6.By forEachRemaining() method. + + +" +"Can you provide an example of traversing the ArrayList elements? +","Let's see an example to traverse the ArrayList elements through other ways + +FileName: ArrayList4.java + +import java.util.*; +class ArrayList4{ + public static void main(String args[]){ + ArrayList list=new ArrayList();//Creating arraylist + list.add(""Ravi"");//Adding object in arraylist + list.add(""Vijay""); + list.add(""Ravi""); + list.add(""Ajay""); + + System.out.println(""Traversing list through List Iterator:""); + //Here, element iterates in reverse order + ListIterator list1=list.listIterator(list.size()); + while(list1.hasPrevious()) + { + String str=list1.previous(); + System.out.println(str); + } + System.out.println(""Traversing list through for loop:""); + for(int i=0;i{ //Here, we are using lambda expression + System.out.println(a); + }); + + System.out.println(""Traversing list through forEachRemaining() method:""); + Iterator itr=list.iterator(); + itr.forEachRemaining(a-> //Here, we are using lambda expression + { + System.out.println(a); + }); + } +} + +Output: + +Traversing list through List Iterator: +Ajay +Ravi +Vijay +Ravi +Traversing list through for loop: +Ravi +Vijay +Ravi +Ajay +Traversing list through forEach() method: +Ravi +Vijay +Ravi +Ajay +Traversing list through forEachRemaining() method: +Ravi +Vijay +Ravi +Ajay + +" +Can you provide an example of User-defined class objects in Java ArrayList?,"Let's see an example where we are storing Student class object in an array list. + +FileName: ArrayList5.java +class Student{ + int rollno; + String name; + int age; + Student(int rollno,String name,int age){ + this.rollno=rollno; + this.name=name; + this.age=age; + } +} + +import java.util.*; + class ArrayList5{ + public static void main(String args[]){ + //Creating user-defined class objects + Student s1=new Student(101,""Sonoo"",23); + Student s2=new Student(102,""Ravi"",21); + Student s2=new Student(103,""Hanumat"",25); + //creating arraylist + ArrayList al=new ArrayList(); + al.add(s1);//adding Student class object + al.add(s2); + al.add(s3); + //Getting Iterator + Iterator itr=al.iterator(); + //traversing elements of ArrayList object + while(itr.hasNext()){ + Student st=(Student)itr.next(); + System.out.println(st.rollno+"" ""+st.name+"" ""+st.age); + } + } +} + +Output: + 101 Sonoo 23 + 102 Ravi 21 + 103 Hanumat 25 + + + +" +"Can you provide an example of Java ArrayList Serialization and Deserialization? +","Let's see an example to serialize an ArrayList object and then deserialize it. + +FileName: ArrayList6.java + +import java.io.*; +import java.util.*; + class ArrayList6 { + + public static void main(String [] args) + { + ArrayList al=new ArrayList(); + al.add(""Ravi""); + al.add(""Vijay""); + al.add(""Ajay""); + + try + { + //Serialization + FileOutputStream fos=new FileOutputStream(""file""); + ObjectOutputStream oos=new ObjectOutputStream(fos); + oos.writeObject(al); + fos.close(); + oos.close(); + //Deserialization + FileInputStream fis=new FileInputStream(""file""); + ObjectInputStream ois=new ObjectInputStream(fis); + ArrayList list=(ArrayList)ois.readObject(); + System.out.println(list); + }catch(Exception e) + { + System.out.println(e); + } + } + } + +Output: + [Ravi, Vijay, Ajay] + + + +" +"Can you provide an example of Java ArrayList to add elements? +","Here, we see different ways to add an element. + +FileName: ArrayList7.java + +import java.util.*; + class ArrayList7{ + public static void main(String args[]){ + ArrayList al=new ArrayList(); + System.out.println(""Initial list of elements: ""+al); + //Adding elements to the end of the list + al.add(""Ravi""); + al.add(""Vijay""); + al.add(""Ajay""); + System.out.println(""After invoking add(E e) method: ""+al); + //Adding an element at the specific position + al.add(1, ""Gaurav""); + System.out.println(""After invoking add(int index, E element) method: ""+al); + ArrayList al2=new ArrayList(); + al2.add(""Sonoo""); + al2.add(""Hanumat""); + //Adding second list elements to the first list + al.addAll(al2); + System.out.println(""After invoking addAll(Collection c) method: ""+al); + ArrayList al3=new ArrayList(); + al3.add(""John""); + al3.add(""Rahul""); + //Adding second list elements to the first list at specific position + al.addAll(1, al3); + System.out.println(""After invoking addAll(int index, Collection c) method: ""+al); + + } +} + +Output: + +Initial list of elements: [] +After invoking add(E e) method: [Ravi, Vijay, Ajay] +After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay] +After invoking addAll(Collection c) method: +[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat] +After invoking addAll(int index, Collection c) method: +[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat] + + + +" +"Can you provide an example of Java ArrayList to remove elements? +","Here, we see different ways to remove an element. + +FileName: ArrayList8.java + +import java.util.*; + class ArrayList8 { + + public static void main(String [] args) + { + ArrayList al=new ArrayList(); + al.add(""Ravi""); + al.add(""Vijay""); + al.add(""Ajay""); + al.add(""Anuj""); + al.add(""Gaurav""); + System.out.println(""An initial list of elements: ""+al); + //Removing specific element from arraylist + al.remove(""Vijay""); + System.out.println(""After invoking remove(object) method: ""+al); + //Removing element on the basis of specific position + al.remove(0); + System.out.println(""After invoking remove(index) method: ""+al); + + //Creating another arraylist + ArrayList al2=new ArrayList(); + al2.add(""Ravi""); + al2.add(""Hanumat""); + //Adding new elements to arraylist + al.addAll(al2); + System.out.println(""Updated list : ""+al); + //Removing all the new elements from arraylist + al.removeAll(al2); + System.out.println(""After invoking removeAll() method: ""+al); + //Removing elements on the basis of specified condition + al.removeIf(str -> str.contains(""Ajay"")); //Here, we are using Lambda expression + System.out.println(""After invoking removeIf() method: ""+al); + //Removing all the elements available in the list + al.clear(); + System.out.println(""After invoking clear() method: ""+al); + } + } + + +Output: + +An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav] +After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav] +After invoking remove(index) method: [Ajay, Anuj, Gaurav] +Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat] +After invoking removeAll() method: [Ajay, Anuj, Gaurav] +After invoking removeIf() method: [Anuj, Gaurav] +After invoking clear() method: [] + +" +"What are the important points in Java LinkedList class? +","Java 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. + +The important points about Java LinkedList are: + +-Java LinkedList class can contain duplicate elements. +-Java LinkedList class maintains insertion order. +-Java LinkedList class is non synchronized. +-In Java LinkedList class, manipulation is fast because no shifting needs to occur. +-Java LinkedList class can be used as a list, stack or queue. +Hierarchy of LinkedList class + +As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and implements List and Deque interfaces. +Doubly Linked List + +In the case of a doubly linked list, we can add or remove elements from both sides. + + +" +"What is the class declaration for LinkedList class? +","Let's see the declaration for java.util.LinkedList class. + +public class LinkedList extends AbstractSequentialList implements List, Deque, Cloneable, Serializable + + +" +"What are the Constructors of Java LinkedList? +","Constructor: LinkedList() +Description: It is used to construct an empty list. + +Constructor: LinkedList(Collection c) +Description: It is used to construct a list containing the elements of the specified collection, in the order, they are returned by the collection's iterator. + + + + + +" +"What are the Methods of Java LinkedList? +","Method: boolean add(E e) +Description: It is used to append the specified element to the end of a list. + +Method: void add(int index, E element) +Description: It is used to insert the specified element at the specified position index in a list. + +Method: boolean addAll(Collection c) +Description: It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. + +Method: boolean addAll(Collection c) +Description: It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. + +Method: boolean addAll(int index, Collection c) +Description: It is used to append all the elements in the specified collection, starting at the specified position of the list. + +Method: void addFirst(E e) +Description: It is used to insert the given element at the beginning of a list. + +Method: void addLast(E e) +Description: It is used to append the given element to the end of a list. + +Method: void clear() +Description: It is used to remove all the elements from a list. + +Method: Object clone() +Description: It is used to return a shallow copy of an ArrayList. + +Method: boolean contains(Object o) +Description: It is used to return true if a list contains a specified element. + +Method: Iterator descendingIterator() +Description: It is used to return an iterator over the elements in a deque in reverse sequential order. + +Method: E element() +Description: It is used to retrieve the first element of a list. + +Method: E get(int index) +Description: It is used to return the element at the specified position in a list. + +Method: E getFirst() +Description: It is used to return the first element in a list. + + +Method: E getLast() +Description: It is used to return the last element in a list. + +Method: int indexOf(Object o) +Description: It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element. + +Method: int lastIndexOf(Object o) +Description: It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element. + +Method: ListIterator listIterator(int index) +Description: It is used to return a list-iterator of the elements in proper sequence, starting at the specified position in the list. + +Method: boolean offer(E e) +Description: It adds the specified element as the last element of a list. + +Method: boolean offerFirst(E e) +Description: It inserts the specified element at the front of a list. + +Method: boolean offerLast(E e) +Description: It inserts the specified element at the end of a list. + +Method: E peek() +Description: It retrieves the first element of a list + +Method: E peekFirst() +Description: It retrieves the first element of a list or returns null if a list is empty. + +Method: E peekLast() +Description: It retrieves the last element of a list or returns null if a list is empty. + +Method: E poll() +Description: It retrieves and removes the first element of a list. + +Method: E pollFirst() +Description: It retrieves and removes the first element of a list, or returns null if a list is empty. + +Method: E pollLast() +Description: It retrieves and removes the last element of a list, or returns null if a list is empty. + +Method: E pop() +Description: It pops an element from the stack represented by a list. + +Method: void push(E e) +Description: It pushes an element onto the stack represented by a list. + +Method: E remove() +Description: It is used to retrieve and removes the first element of a list. + +Method: E remove(int index) +Description: It is used to remove the element at the specified position in a list. + +Method: boolean remove(Object o) +Description: It is used to remove the first occurrence of the specified element in a list. + +Method: E removeFirst() +Description: It removes and returns the first element from a list. + +Method: boolean removeFirstOccurrence(Object o) +Description: It is used to remove the first occurrence of the specified element in a list (when traversing the list from head to tail). + +Method: E removeLast() +Description: It removes and returns the last element from a list. + +Method: boolean removeLastOccurrence(Object o) +Description: It removes the last occurrence of the specified element in a list (when traversing the list from head to tail). + +Method: E set(int index, E element) +Description: It replaces the element at the specified position in a list with the specified element. + +Method: Object[] toArray() +Description: It is used to return an array containing all the elements in a list in proper sequence (from first to the last element). + +Method: T[] toArray(T[] a) +Description: It returns an array containing all the elements in the proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array. + +Method: int size() +Description: It is used to return the number of elements in a list. + + + + +" +"Can you provide an example of Java LinkedList? +","import java.util.*; +public class LinkedList1{ + public static void main(String args[]){ + + LinkedList al=new LinkedList(); + al.add(""Ravi""); + al.add(""Vijay""); + al.add(""Ravi""); + al.add(""Ajay""); + + Iterator itr=al.iterator(); + while(itr.hasNext()){ + System.out.println(itr.next()); + } + } +} + +Output: Ravi + Vijay + Ravi + Ajay + + +" +"What are the difference between ArrayList and LinkedList? +","ArrayList and LinkedList both implement the List interface and maintain insertion order. Both are non-synchronized classes. + +However, there are many differences between the ArrayList and LinkedList classes that are given below. + +1) ArrayList internally uses a dynamic array to store the elements while LinkedList internally uses a doubly linked list to store the elements. +2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the other elements are shifted in memory while Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. +3) An ArrayList class can act as a list only because it implements List only while LinkedList class can act as a list and queue both because it implements List and Deque interfaces. +4) ArrayList is better for storing and accessing data while LinkedList is better for manipulating data. +5) The memory location for the elements of an ArrayList is contiguous while The location for the elements of a linked list is not contagious. +6) Generally, when an ArrayList is initialized, a default capacity of 10 is assigned to the ArrayList while There is no case of default capacity in a LinkedList. In LinkedList, an empty list is created when a LinkedList is initialized. +7) To be precise, an ArrayList is a resizable array while LinkedList implements the doubly linked list of the list interface. + +" +"Can you provide an example of ArrayList and LinkedList in Java? +","Let's see a simple example where we are using ArrayList and LinkedList both. + +FileName: TestArrayLinked.java + +import java.util.*; +class TestArrayLinked{ + public static void main(String args[]){ + + List al=new ArrayList();//creating arraylist + al.add(""Ravi"");//adding object in arraylist + al.add(""Vijay""); + al.add(""Ravi""); + al.add(""Ajay""); + + List al2=new LinkedList();//creating linkedlist + al2.add(""James"");//adding object in linkedlist + al2.add(""Serena""); + al2.add(""Swati""); + al2.add(""Junaid""); + + System.out.println(""arraylist: ""+al); + System.out.println(""linkedlist: ""+al2); + } +} + +Output: +arraylist: [Ravi,Vijay,Ravi,Ajay] +linkedlist: [James,Serena,Swati,Junaid] + + + +" +"What is Java List? +","List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements in the list. + +The List interface is found in the java.util package and inherits the Collection interface. It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5. +List Interface declaration +public interface List extends Collection + + +" +"What are the methods of Java List? +","Method: void add(int index, E element) +Description: It is used to insert the specified element at the specified position in a list. + +Method: boolean add(E e) +Description: It is used to append the specified element at the end of a list. + +Method: boolean addAll(Collection c) +Description: It is used to append all of the elements in the specified collection to the end of a list. + +Method: boolean addAll(int index, Collection c) +Description: It is used to append all the elements in the specified collection, starting at the specified position of the list. + +Method: void clear() +Description: It is used to remove all of the elements from this list. + +Method: boolean equals(Object o) +Description: It is used to compare the specified object with the elements of a list. + +Method: int hashcode() +Description: It is used to return the hash code value for a list. + +Method: E get(int index) +Description: It is used to fetch the element from the particular position of the list. + +Method: boolean isEmpty() +Description: It returns true if the list is empty, otherwise false. + +Method: int lastIndexOf(Object o) +Description: It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. + +Method: Object[] toArray() +Description: It is used to return an array containing all of the elements in this list in the correct order. + +Method: T[] toArray(T[] a) +Description: It is used to return an array containing all of the elements in this list in the correct order. + +Method: boolean contains(Object o) +Description: It returns true if the list contains the specified element + +Method: boolean containsAll(Collection c) +Description: It returns true if the list contains all the specified element + +Method: int indexOf(Object o) +Description: It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. + +Method: E remove(int index) +Description: It is used to remove the element present at the specified position in the list. + +Method: boolean remove(Object o) +Description: It is used to remove the first occurrence of the specified element. + +Method: boolean removeAll(Collection c) +Description: It is used to remove all the elements from the list. + +Method: void replaceAll(UnaryOperator operator) +Description: It is used to replace all the elements from the list with the specified element. + +Method: void retainAll(Collection c) +Description: It is used to retain all the elements in the list that are present in the specified collection. + +Method: E set(int index, E element) +Description: It is used to replace the specified element in the list, present at the specified position. + +Method: void sort(Comparator c) +Description: It is used to sort the elements of the list on the basis of specified comparator. + +Method: Spliterator spliterator() +Description: It is used to create spliterator over the elements in a list. + +Method: List subList(int fromIndex, int toIndex) +Description: It is used to fetch all the elements lies within the given range. + +Method: int size() +Description: It is used to return the number of elements present in the list. +" +"What is Java List and ArrayList? +","List is an interface whereas ArrayList is the implementation class of List. +" +"How to create a List in Java? +","The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the examples to create the List: + +//Creating a List of type String using ArrayList +List list=new ArrayList(); +//Creating a List of type Integer using ArrayList +List list=new ArrayList(); +//Creating a List of type Book using ArrayList +List list=new ArrayList(); +//Creating a List of type String using LinkedList +List list=new LinkedList(); + +In short, you can create the List of any type. The ArrayList and LinkedList classes are used to specify the type. Here, T denotes the type. +" +"Can you provide an example of Java List? +","Let's see a simple example of List where we are using the ArrayList class as the implementation. + +import java.util.*; +public class ListExample1{ +public static void main(String args[]){ + //Creating a List + List list=new ArrayList(); + //Adding elements in the List + list.add(""Mango""); + list.add(""Apple""); + list.add(""Banana""); + list.add(""Grapes""); + //Iterating the List element using for-each loop + for(String fruit:list) + System.out.println(fruit); + +} +} + +Output: +Mango +Apple +Banana +Grapes +" +"How to convert Array to List? +","We can convert the Array to List by traversing the array and adding the element in list one by one using list.add() method. Let's see a simple example to convert array elements into List. + +import java.util.*; +public class ArrayToListExample{ +public static void main(String args[]){ +//Creating Array +String[] array={""Java"",""Python"",""PHP"",""C++""}; +System.out.println(""Printing Array: ""+Arrays.toString(array)); +//Converting Array to List +List list=new ArrayList(); +for(String lang:array){ +list.add(lang); +} +System.out.println(""Printing List: ""+list); + +} +} +Output: +Printing Array: [Java, Python, PHP, C++] +Printing List: [Java, Python, PHP, C++] +" +"How to convert List to Array? +","We can convert the List to Array by calling the list.toArray() method. Let's see a simple example to convert list elements into array. + +import java.util.*; +public class ListToArrayExample{ +public static void main(String args[]){ + List fruitList = new ArrayList<>(); + fruitList.add(""Mango""); + fruitList.add(""Banana""); + fruitList.add(""Apple""); + fruitList.add(""Strawberry""); + //Converting ArrayList to Array + String[] array = fruitList.toArray(new String[fruitList.size()]); + System.out.println(""Printing Array: ""+Arrays.toString(array)); + System.out.println(""Printing List: ""+fruitList); +} +} +Output: +Printing Array: [Mango, Banana, Apple, Strawberry] +Printing List: [Mango, Banana, Apple, Strawberry] +" +"What is Get and Set Element in List? +","The get() method returns the element at the given index, whereas the set() method changes or replaces the element. + +import java.util.*; +public class ListExample2{ + public static void main(String args[]){ + //Creating a List + List list=new ArrayList(); + //Adding elements in the List + list.add(""Mango""); + list.add(""Apple""); + list.add(""Banana""); + list.add(""Grapes""); + //accessing the element + System.out.println(""Returning element: ""+list.get(1));//it will return the 2nd element, because index starts from 0 + //changing the element + list.set(1,""Dates""); + //Iterating the List element using for-each loop + for(String fruit:list) + System.out.println(fruit); + + } +} + +Output: +Returning element: Apple +Mango +Dates +Banana +Grapes +" +"How to Sort List? +","There are various ways to sort the List, here we are going to use Collections.sort() method to sort the list element. The java.util package provides a utility class Collections which has the static method sort(). Using the Collections.sort() method, we can easily sort any List. + +import java.util.*; +class SortArrayList{ + public static void main(String args[]){ + //Creating a list of fruits + List list1=new ArrayList(); + list1.add(""Mango""); + list1.add(""Apple""); + list1.add(""Banana""); + list1.add(""Grapes""); + //Sorting the list + Collections.sort(list1); + //Traversing list through the for-each loop + for(String fruit:list1) + System.out.println(fruit); + + System.out.println(""Sorting numbers...""); + //Creating a list of numbers + List list2=new ArrayList(); + list2.add(21); + list2.add(11); + list2.add(51); + list2.add(1); + //Sorting the list + Collections.sort(list2); + //Traversing list through the for-each loop + for(Integer number:list2) + System.out.println(number); + } + +} + +Output: +Apple +Banana +Grapes +Mango +Sorting numbers... +1 +11 +21 +51 +" +"What is Java ListIterator Interface? +",ListIterator Interface is used to traverse the element in a backward and forward direction. +"What is the class declaration for Listlterator Interface? +",public interface ListIterator extends Iterator +"What are the Methods of Java ListIterator Interface? +","Method: void add(E e) +Description: This method inserts the specified element into the list. + +Method: boolean hasNext() +Description: This method returns true if the list iterator has more elements while traversing the list in the forward direction. + +Method: E next() +Description: This method returns the next element in the list and advances the cursor position. + +Method: int nextIndex() +Description: This method returns the index of the element that would be returned by a subsequent call to next() + +Method: boolean hasPrevious() +Description: This method returns true if this list iterator has more elements while traversing the list in the reverse direction. + +Method: E previous() +Description: This method returns the previous element in the list and moves the cursor position backward. + +Method: E previousIndex() +Description: This method returns the index of the element that would be returned by a subsequent call to previous(). + +Method: void remove() +Description: This method removes the last element from the list that was returned by next() or previous() methods + +Method: void set(E e) +Description: This method replaces the last element returned by next() or previous() methods with the specified element. +" +"Can you provide an example of ListIterator Interface? +","import java.util.*; +public class ListIteratorExample1{ +public static void main(String args[]){ +List al=new ArrayList(); + al.add(""Amit""); + al.add(""Vijay""); + al.add(""Kumar""); + al.add(1,""Sachin""); + ListIterator itr=al.listIterator(); + System.out.println(""Traversing elements in forward direction""); + while(itr.hasNext()){ + + System.out.println(""index:""+itr.nextIndex()+"" value:""+itr.next()); + } + System.out.println(""Traversing elements in backward direction""); + while(itr.hasPrevious()){ + + System.out.println(""index:""+itr.previousIndex()+"" value:""+itr.previous()); + } +} +} + +Output: +Traversing elements in forward direction +index:0 value:Amit +index:1 value:Sachin +index:2 value:Vijay +index:3 value:Kumar +Traversing elements in backward direction +index:3 value:Kumar +index:2 value:Vijay +index:1 value:Sachin +index:0 value:Amit +" +"Can you provide an example of List: Book? +","Let's see an example of List where we are adding the Books. + +import java.util.*; +class Book { +int id; +String name,author,publisher; +int quantity; +public Book(int id, String name, String author, String publisher, int quantity) { + this.id = id; + this.name = name; + this.author = author; + this.publisher = publisher; + this.quantity = quantity; +} +} +public class ListExample5 { +public static void main(String[] args) { + //Creating list of Books + List list=new ArrayList(); + //Creating Books + Book b1=new Book(101,""Let us C"",""Yashwant Kanetkar"",""BPB"",8); + Book b2=new Book(102,""Data Communications and Networking"",""Forouzan"",""Mc Graw Hill"",4); + Book b3=new Book(103,""Operating System"",""Galvin"",""Wiley"",6); + //Adding Books to list + list.add(b1); + list.add(b2); + list.add(b3); + //Traversing list + for(Book b:list){ + System.out.println(b.id+"" ""+b.name+"" ""+b.author+"" ""+b.publisher+"" ""+b.quantity); + } +} +} + +Output: +101 Let us C Yashwant Kanetkar BPB 8 +102 Data Communications and Networking Forouzan Mc Graw Hill 4 +103 Operating System Galvin Wiley 6 + +" +"What are the important points about Java HashSet? +","Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface. + +The important points about Java HashSet class are: + +-HashSet stores the elements by using a mechanism called hashing. +-HashSet contains unique elements only. +-HashSet allows null value. +-HashSet class is non synchronized. +-HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode. +-HashSet is the best approach for search operations. +-The initial default capacity of HashSet is 16, and the load factor is 0.75. + +" +"What is the Difference between List and Set? +","A list can contain duplicate elements whereas Set contains unique elements only. +" +"What are the Constructors of the Java HashSet class? +","Sn:1 +Constructor: HashSet() +Description: It is used to construct a default HashSet. + +Sn:2 +Constructor: HashSet(int capacity) +Description: It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet. + +Sn:3 +Constructor: HashSet(int capacity, float loadFactor) +Description: It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor. + +Sn:4 +Constructor: HashSet(Collection c) +Description: It is used to initialize the hash set by using the elements of the collection c. +" +"What are the Methods of Java HashSet class? +","Various methods of Java HashSet class are as follows: + +Sn:1 +Method and Type: boolean +Method: add(E e) +Description: It is used to add the specified element to this set if it is not already present. + +Sn:2 +Method and Type: void +Method: clear() +Description: It is used to remove all of the elements from the set. + +Sn:3 +Method and Type: object +Method: clone() +Description: It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned. + +Sn:4 +Method and Type: boolean +Method: contains(Object o) +Description: It is used to return true if this set contains the specified element. + +Sn:5 +Method and Type: boolean +Method: isEmpty() +Description: It is used to return true if this set contains no elements. + +Sn:6 +Method and Type: Iterator +Method: iterator() +Description: It is used to return an iterator over the elements in this set. + +Sn:7 +Method and Type: boolean +Method: remove(Object o) +Description: It is used to remove the specified element from this set if it is present. + +Sn:8 +Method and Type: int +Method: size() +Description: It is used to return the number of elements in the set. + +Sn:9 +Method and Type: Spliterator +Method: spliterator() +Description: It is used to create a late-binding and fail-fast Spliterator over the elements in the set. +" +"Can you provide an example of Java HashSet? +","Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection. + +import java.util.*; +class HashSet1{ + public static void main(String args[]){ + //Creating HashSet and adding elements + HashSet set=new HashSet(); + set.add(""One""); + set.add(""Two""); + set.add(""Three""); + set.add(""Four""); + set.add(""Five""); + Iterator i=set.iterator(); + while(i.hasNext()) + { + System.out.println(i.next()); + } + } +} + +Five +One +Four +Two +Three + + + + + + +" +"What is the important points about the Java LinkedHashSet Class? +","Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. + +It inherits the HashSet class and implements the Set interface. + +The important points about the Java LinkedHashSet class are: +-Java LinkedHashSet class contains unique elements only like HashSet. +-Java LinkedHashSet class provides all optional set operations and permits null elements. +-Java LinkedHashSet class is non-synchronized. +-Java LinkedHashSet class maintains insertion order. +" +"What is the class declaration for LinkedHashSet class? +","Let's see the declaration for java.util.LinkedHashSet class. + +public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable +" +"What are the Constructors of the Java LinkedHashSet class? +","Constructor: HashSet() +Description: It is used to construct a default HashSet. + +Constructor: HashSet(Collection c) +Description: It is used to initialize the hash set by using the elements of the collection c. + +Constructor: LinkedHashSet(int capacity) +Description: It is used to initialize the capacity of the linked hash set to the given integer value capacity. + +Constructor: LinkedHashSet(int capacity, float fillRatio) +Description: It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument. + + + + + + + + +" +"Can you provide an example of Java LinkedHashSet? +","Let's see a simple example of the Java LinkedHashSet class. Here you can notice that the elements iterate in insertion order. + +FileName: LinkedHashSet1.java + +import java.util.*; +class LinkedHashSet1{ + public static void main(String args[]){ + //Creating HashSet and adding elements + LinkedHashSet set=new LinkedHashSet(); + set.add(""One""); + set.add(""Two""); + set.add(""Three""); + set.add(""Four""); + set.add(""Five""); + Iterator i=set.iterator(); + while(i.hasNext()) + { + System.out.println(i.next()); + } + } +} + +Output: +One +Two +Three +Four +Five + + +" +"What are the important points about the Java TreeSet class? +","Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order. + +The important points about the Java TreeSet class are: + +-Java TreeSet class contains unique elements only like HashSet. +-Java TreeSet class access and retrieval times are quiet fast. +-Java TreeSet class doesn't allow null element. +-Java TreeSet class is non synchronized. +-Java TreeSet class maintains ascending order. +-Java TreeSet class contains unique elements only like HashSet. +-Java TreeSet class access and retrieval times are quite fast. +-Java TreeSet class doesn't allow null elements. +-Java TreeSet class is non-synchronized. +-Java TreeSet class maintains ascending order. +-The TreeSet can only allow those generic types that are comparable. For example The Comparable interface is being implemented by the StringBuffer class. + + +" +"What is Internal Working of The TreeSet Class? +","TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-Black Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time. The reason behind this is there in the self-balancing tree. It is there to ensure that the tree height never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient data structures in order to keep the large data that is sorted and also to do operations on it. + +" +"What is Synchronization of The TreeSet Class? +","As already mentioned above, the TreeSet class is not synchronized. It means if more than one thread concurrently accesses a tree set, and one of the accessing threads modify it, then the synchronization must be done manually. It is usually done by doing some object synchronization that encapsulates the set. However, in the case where no such object is found, then the set must be wrapped with the help of the Collections.synchronizedSet() method. It is advised to use the method during creation time in order to avoid the unsynchronized access of the set. The following code snippet shows the same. + +TreeSet treeSet = new TreeSet(); +Set syncrSet = Collections.synchronziedSet(treeSet); + + +" +"What is the class declaration for TreeSet Class? +","Let's see the declaration for java.util.TreeSet class. + +public class TreeSet extends AbstractSet implements NavigableSet, Cloneable, Serializable + + +" +"What are the Constructors of the Java TreeSet Class? +","Constructor: TreeSet() +Description: It is used to construct an empty tree set that will be sorted in ascending order according to the natural order of the tree set. + +Constructor: TreeSet(Collection c) +Description: It is used to build a new tree set that contains the elements of the collection c. + +Constructor: TreeSet(Comparator comparator) +Description: It is used to construct an empty tree set that will be sorted according to given comparator. + +Constructor: TreeSet(SortedSet s) +Description: It is used to build a TreeSet that contains the elements of the given SortedSe +" +"What are the Methods of Java TreeSet Class? +","Method: boolean add(E e) +Description: It is used to add the specified element to this set if it is not already present. + +Method: boolean addAll(Collection c) +Description: It is used to add all of the elements in the specified collection to this set. + +Method: E ceiling(E e) +Description: It returns the equal or closest greatest element of the specified element from the set, or null there is no such element. + +Method: Comparator comparator() +Description: It returns a comparator that arranges elements in order. + +Method: Iterator descendingIterator() +Description: It is used to iterate the elements in descending order. + +Method: NavigableSet descendingSet() +Description: It returns the elements in reverse order. + +Method: E floor(E e) +Description: It returns the equal or closest least element of the specified element from the set, or null there is no such element. + +Method: SortedSet headSet(E toElement) +Description: It returns the group of elements that are less than the specified element. + +Method: NavigableSet headSet(E toElement, boolean inclusive) +Description: It returns the group of elements that are less than or equal to(if, inclusive is true) the specified element. + +Method: E higher(E e) +Description: It returns the closest greatest element of the specified element from the set, or null there is no such element. + +Method: Iterator iterator() +Description: It is used to iterate the elements in ascending order. + +Method: E lower(E e) +Description: It returns the closest least element of the specified element from the set, or null there is no such element. + +Method: E pollFirst() +Description: It is used to retrieve and remove the lowest(first) element. + +Method: E pollLast() +Description: It is used to retrieve and remove the highest(last) element. + +Method: Spliterator spliterator() +Description: It is used to create a late-binding and fail-fast spliterator over the elements. + +Method: NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) +Description: It returns a set of elements that lie between the given range. + +Method: SortedSet subSet(E fromElement, E toElement)) +Description: It returns a set of elements that lie between the given range which includes fromElement and excludes toElement. + +Method: SortedSet tailSet(E fromElement) +Description: It returns a set of elements that are greater than or equal to the specified element. + +Method: NavigableSet tailSet(E fromElement, boolean inclusive) +Description: It returns a set of elements that are greater than or equal to (if, inclusive is true) the specified element. + +Method: boolean contains(Object o) +Description: It returns true if this set contains the specified element. + +Method: boolean isEmpty() +Description: It returns true if this set contains no elements. + +Method: boolean remove(Object o) +Description: It is used to remove the specified element from this set if it is present. + +Method: void clear() +Description: It is used to remove all of the elements from this set. + +Method: Object clone() +Description: It returns a shallow copy of this TreeSet instance. + +Method: E first() +Description: It returns the first (lowest) element currently in this sorted set. + +Method: E last() +Description: It returns the last (highest) element currently in this sorted set. + +Method: int size() +Description: It returns the number of elements in this set. " +"Can you provide an example of Java TreeSet? +","Let's see a simple example of Java TreeSet. + +FileName: TreeSet1.java + +import java.util.*; +class TreeSet1{ + public static void main(String args[]){ + //Creating and adding elements + TreeSet al=new TreeSet(); + al.add(""Ravi""); + al.add(""Vijay""); + al.add(""Ravi""); + al.add(""Ajay""); + //Traversing elements + Iterator itr=al.iterator(); + while(itr.hasNext()){ + System.out.println(itr.next()); + } + } +} +Output: +Ajay +Ravi +Vijay +" +"What is Java Queue Interface? +","The interface Queue is available in the java.util package and does extend the Collection interface. It is used to keep the elements that are processed in the First In First Out (FIFO) manner. It is an ordered list of objects, where insertion of elements occurs at the end of the list, and removal of elements occur at the beginning of the list. + +Being an interface, the queue requires, for the declaration, a concrete class, and the most common classes are the LinkedList and PriorityQueue in Java. Implementations done by these classes are not thread safe. If it is required to have a thread safe implementation, PriorityBlockingQueue is an available option. +" +What is the class declaration for Queue Interface?,public interface Queue extends Collection +"What are the Methods of Java Queue Interface? +","Method: boolean add(object) +Description: It is used to insert the specified element into this queue and return true upon success. + +Method: boolean offer(object) +Description: It is used to insert the specified element into this queue. + +Method: Object remove() +Description: It is used to retrieves and removes the head of this queue. + +Method: Object poll() +Description: It is used to retrieves and removes the head of this queue, or returns null if this queue is empty. + +Method: Object element() +Description: It is used to retrieves, but does not remove, the head of this queue. + +Method: Object peek() +Description: It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. +" +"What are the following important features of a Queue? +","The following are some important features of a queue. + +-As discussed earlier, FIFO concept is used for insertion and deletion of elements from a queue. +-The Java Queue provides support for all of the methods of the Collection interface including deletion, insertion, etc. +-PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that are used most frequently. +-The NullPointerException is raised, if any null operation is done on the BlockingQueues. +-Those Queues that are present in the util package are known as Unbounded Queues. +-Those Queues that are present in the util.concurrent package are known as bounded Queues. +-All Queues barring the Deques facilitates removal and insertion at the head and tail of the queue; respectively. In fact, deques support element insertion and removal at both ends. +" +"What is the class declaration for PriorityQueue? +","Let's see the declaration for java.util.PriorityQueue class. +public class PriorityQueue extends AbstractQueue implements Serializable +" +"Can you provide an example of Java PriorityQueue? +","FileName: TestCollection12.java + +import java.util.*; +class TestCollection12{ +public static void main(String args[]){ +PriorityQueue queue=new PriorityQueue(); +queue.add(""Amit""); +queue.add(""Vijay""); +queue.add(""Karan""); +queue.add(""Jai""); +queue.add(""Rahul""); +System.out.println(""head:""+queue.element()); +System.out.println(""head:""+queue.peek()); +System.out.println(""iterating the queue elements:""); +Iterator itr=queue.iterator(); +while(itr.hasNext()){ +System.out.println(itr.next()); +} +queue.remove(); +queue.poll(); +System.out.println(""after removing two elements:""); +Iterator itr2=queue.iterator(); +while(itr2.hasNext()){ +System.out.println(itr2.next()); +} +} +} + +Output: +head:Amit + head:Amit + iterating the queue elements: + Amit + Jai + Karan + Vijay + Rahul + after removing two elements: + Karan + Rahul + Vijay +" +"What is Java Deque Interface? +","The interface called Deque is present in java.util package. It is the subtype of the interface queue. The Deque supports the addition as well as the removal of elements from both ends of the data structure. Therefore, a deque can be used as a stack or a queue. We know that the stack supports the Last In First Out (LIFO) operation, and the operation First In First Out is supported by a queue. As a deque supports both, either of the mentioned operations can be performed on it. Deque is an acronym for ""double ended queue""." +"What is the class declaration for Deque Interface? + +",public interface Deque extends Queue +"What are the Methods of Java Deque Interface? +","Method: boolean add(object) +Description: It is used to insert the specified element into this deque and return true upon success. + +Method: boolean offer(object) +Description: It is used to insert the specified element into this deque. + +Method: Object remove() +Description: It is used to retrieve and removes the head of this deque. + +Method: Object poll() +Description: It is used to retrieve and removes the head of this deque, or returns null if this deque is empty. + +Method: Object element() +Description: It is used to retrieve, but does not remove, the head of this deque. + +Method: Object peek() +Description: It is used to retrieve, but does not remove, the head of this deque, or returns null if this deque is empty. + +Method: Object peekFirst() +Description: The method returns the head element of the deque. The method does not remove any element from the deque. Null is returned by this method, when the deque is empty. + +Method: Object peekLast() +Description: The method returns the last element of the deque. The method does not remove any element from the deque. Null is returned by this method, when the deque is empty. + +Method: Boolean offerFirst(e) +Description: Inserts the element e at the front of the queue. If the insertion is successful, true is returned; otherwise, false. + +Method: Object offerLast(e) +Description: Inserts the element e at the tail of the queue. If the insertion is successful, true is returned; otherwise, false. +" +"What are the important points about ArrayDeque class? +","We know that it is not possible to create an object of an interface in Java. Therefore, for instantiation, we need a class that implements the Deque interface, and that class is ArrayDeque. It grows and shrinks as per usage. It also inherits the AbstractCollection class. + +The important points about ArrayDeque class are: + +-Unlike Queue, we can add or remove elements from both sides. +-Null elements are not allowed in the ArrayDeque. +-ArrayDeque is not thread safe, in the absence of external synchronization. +-ArrayDeque has no capacity restrictions. +-ArrayDeque is faster than LinkedList and Stack." +"What is ArrayDeque Hierarchy? +",The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the page. +"What is the class declaration for ArrayDeque class? +","Let's see the declaration for java.util.ArrayDeque class. + +public class ArrayDeque extends AbstractCollection implements Deque, Cloneable, Serializable " +"Can you provide an example Java ArrayDeque? +","FileName: ArrayDequeExample.java + +import java.util.*; +public class ArrayDequeExample { + public static void main(String[] args) { + //Creating Deque and adding elements + Deque deque = new ArrayDeque(); + deque.add(""Ravi""); + deque.add(""Vijay""); + deque.add(""Ajay""); + //Traversing elements + for (String str : deque) { + System.out.println(str); + } + } +} +Output: + +Ravi +Vijay +Ajay" +"What is Java Map Interface? +","A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys. + +A Map is useful if you have to search, update or delete elements on the basis of a key. +" +"What are the Useful methods of Map interface? +","Method: V put(Object key, Object value) +Description: It is used to insert an entry in the map. + +Method: void putAll(Map map) +Description: It is used to insert the specified map in the map. + +Method: V putIfAbsent(K key, V value) +Description: It inserts the specified value with the specified key in the map only if it is not already specified. + +Method: V remove(Object key) +Description: It is used to delete an entry for the specified key. + +Method: boolean remove(Object key, Object value) +Description: It removes the specified values with the associated specified keys from the map. + +Method: Set keySet() +Description: It returns the Set view containing all the keys + +Method: Set> entrySet() +Description: It returns the Set view containing all the keys and values. + +Method: void clear() +Description: It is used to reset the map. + +Method: V compute(K key, BiFunction remappingFunction) +Description: It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). + + +Method: V computeIfAbsent(K key, Function mappingFunction) +Description: It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. + +Method: V computeIfPresent(K key, BiFunction remappingFunction) +Description: It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. + +Method: boolean containsValue(Object value) +Description: This method returns true if some value equal to the value exists within the map, else return false. + +Method: boolean containsKey(Object key) +Description: This method returns true if some key equal to the key exists within the map, else return false. + +Method: boolean equals(Object o) +Description: It is used to compare the specified Object with the Map. + +Method: void forEach(BiConsumer action) +Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. + +Method: V get(Object key) +Description: This method returns the object that contains the value associated with the key. + +Method: V getOrDefault(Object key, V defaultValue) +Description: It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. + +Method: int hashCode() +Description: It returns the hash code value for the Map + +Method: boolean isEmpty() +Description: This method returns true if the map is empty; returns false if it contains at least one key. + +Method: V merge(K key, V value, BiFunction remappingFunction) +Description: If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. + +Method: V replace(K key, V value) +Description: It replaces the specified value for a specified key. + +Method: boolean replace(K key, V oldValue, V newValue) +Description: It replaces the old value with the new value for a specified key. + +Method: void replaceAll(BiFunction function) +Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. + +Method: Collection values() +Description: It returns a collection view of the values contained in the map. + +Method: int size() +Description: This method returns the number of entries in the map. +" +"What is Map.Entry Interface? +","Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It returns a collection-view of the map, whose elements are of this class. It provides methods to get key and value. +" +"What are the Methods of Map.Entry interface? +","Method: K getKey() +Description: It is used to obtain a key. + +Method: V getValue() +Description: It is used to obtain value. + +Method: int hashCode() +Description: It is used to obtain hashCode. + +Method: V setValue(V value) +Description: It is used to replace the value corresponding to this entry with the specified value. + +Method: boolean equals(Object o) +Description: It is used to compare the specified object with the other existing objects. + +Method: static ,V> Comparator> comparingByKey() +Description: It returns a comparator that compare the objects in natural order on key. + +Method: static Comparator> comparingByKey(Comparator cmp) +Description: It returns a comparator that compare the objects by key using the given Comparator. + +Method: static > Comparator> comparingByValue() +Description: It returns a comparator that compare the objects in natural order on value. + +Method: static Comparator> comparingByValue(Comparator cmp) +Description: It returns a comparator that compare the objects by value using the given Comparator. +" +"Can you provide an example of Java Map: Non-Generic (Old Style)? +"," +//Non-generic +import java.util.*; +public class MapExample1 { +public static void main(String[] args) { + Map map=new HashMap(); + //Adding elements to map + map.put(1,""Amit""); + map.put(5,""Rahul""); + map.put(2,""Jai""); + map.put(6,""Amit""); + //Traversing Map + Set set=map.entrySet();//Converting to Set so that we can traverse + Iterator itr=set.iterator(); + while(itr.hasNext()){ + //Converting to Map.Entry so that we can get key and value separately + Map.Entry entry=(Map.Entry)itr.next(); + System.out.println(entry.getKey()+"" ""+entry.getValue()); + } +} +} + +Output: +1 Amit +2 Jai +5 Rahul +6 Amit +" +"Can you provide an example of Java Map: Generic (New Style)? +"," +import java.util.*; +class MapExample2{ + public static void main(String args[]){ + Map map=new HashMap(); + map.put(100,""Amit""); + map.put(101,""Vijay""); + map.put(102,""Rahul""); + //Elements can traverse in any order + for(Map.Entry m:map.entrySet()){ + System.out.println(m.getKey()+"" ""+m.getValue()); + } + } +} + +Output: +102 Rahul +100 Amit +101 Vijay +" +"What is Java HashMap? +","Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updation, deletion, etc. HashMap class is found in the java.util package. + +HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the null elements as well, but there should be only one null key. Since Java 5, it is denoted as HashMap, where K stands for key and V for value. It inherits the AbstractMap class and implements the Map interface. +Points to remember +-Java HashMap contains values based on the key. +-Java HashMap contains only unique keys. +-Java HashMap may have one null key and multiple null values. +-Java HashMap is non synchronized. +-Java HashMap maintains no order. +-The initial default capacity of Java HashMap class is 16 with a load factor of 0.75. +" +"What is the class declaration for HashMap class? +","Let's see the declaration for java.util.HashMap class. + +public class HashMap extends AbstractMap implements Map, Cloneable, Serializable +" +"What is HashMap class Parameters? +","Let's see the Parameters for java.util.HashMap class. + +-K: It is the type of keys maintained by this map. +-V: It is the type of mapped values. +" +"What are the Constructors of the Java HashMap? +","Constructor: HashMap() +Description: It is used to construct a default HashMap. + +Constructor: HashMap(Map m) +Description: It is used to initialize the hash map by using the elements of the given Map object m. + +Constructor: HashMap(int capacity) +Description: It is used to initializes the capacity of the hash map to the given integer value, capacity. + +Constructor: HashMap(int capacity, float loadFactor) +Description: It is used to initialize both the capacity and load factor of the hash map by using its arguments. +" +"What are the Methods of Java HashMap class? +","Method: void clear() +Description: It is used to remove all of the mappings from this map. + +Method: boolean isEmpty() +Description: It is used to return true if this map contains no key-value mappings. + +Method: Object clone() +Description: It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned. + +Method: Set entrySet() +Description: It is used to return a collection view of the mappings contained in this map. + +Method: Set keySet() +Description: It is used to return a set view of the keys contained in this map. + +Method:V put(Object key, Object value) +Description: It is used to insert an entry in the map. + +Method: void putAll(Map map) +Description: It is used to insert the specified map in the map. + +Method: V putIfAbsent(K key, V value) +Description: It inserts the specified value with the specified key in the map only if it is not already specified. + +Method: V remove(Object key) +Description:It is used to delete an entry for the specified key. + +Method: boolean remove(Object key, Object value) +Description: It removes the specified values with the associated specified keys from the map. + +Method: V compute(K key, BiFunction remappingFunction) +Description: It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). + +Method:V computeIfAbsent(K key, Function mappingFunction) +Description:It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. + + +Method: V computeIfPresent(K key, BiFunction remappingFunction) +Description: It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. + +Method: boolean containsValue(Object value) +Description: This method returns true if some value equal to the value exists within the map, else return false. + +Method: boolean containsKey(Object key) +Description: This method returns true if some key equal to the key exists within the map, else return false. + +Method: boolean equals(Object o) +Description: It is used to compare the specified Object with the Map. + +Method: void forEach(BiConsumer action) +Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. + +Method: V get(Object key) +Description: This method returns the object that contains the value associated with the key. + +Method: V getOrDefault(Object key, V defaultValue) +Description: It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. + +Method: boolean isEmpty() +Description: This method returns true if the map is empty; returns false if it contains at least one key. + +Method: V merge(K key, V value, BiFunction remappingFunction) +Description:If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. + +Method: V replace(K key, V value) +Description: It replaces the specified value for a specified key. + +Method: boolean replace(K key, V oldValue, V newValue) +Description: It replaces the old value with the new value for a specified key. + +Method: void replaceAll(BiFunction function) +Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. + + +Method: Collection values() +Description: It returns a collection view of the values contained in the map. + +Method: int size() +Description: This method returns the number of entries in the map. +" +"Can you provide an example of Java HashMap? +","Let's see a simple example of HashMap to store key and value pair. + +import java.util.*; +public class HashMapExample1{ + public static void main(String args[]){ + HashMap map=new HashMap();//Creating HashMap + map.put(1,""Mango""); //Put elements in Map + map.put(2,""Apple""); + map.put(3,""Banana""); + map.put(4,""Grapes""); + + System.out.println(""Iterating Hashmap...""); + for(Map.Entry m : map.entrySet()){ + System.out.println(m.getKey()+"" ""+m.getValue()); + } +} +} +Iterating Hashmap... +1 Mango +2 Apple +3 Banana +4 Grapes + +In this example, we are storing Integer as the key and String as the value, so we are using HashMap as the type. The put() method inserts the elements in the map. + +To get the key and value elements, we should call the getKey() and getValue() methods. The Map.Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.Entry +" +"What is HashMap? +","HashMap is a part of the Java collection framework. It uses a technique called Hashing. It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value. There are four fields in HashMap. +" +"What is Java LinkedHashMap class? +","Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface. +Points to remember +-Java LinkedHashMap contains values based on the key. +–Java LinkedHashMap contains unique elements. +Java LinkedHashMap may have one null key and multiple null values. +-Java LinkedHashMap is non synchronized. +-Java LinkedHashMap maintains insertion order. +-The initial default capacity of Java HashMap class is 16 with a load factor of 0.75. + + +" +"What is the class declaration for LinkedHashMap? +","Let's see the declaration for java.util.LinkedHashMap class. + +public class LinkedHashMap extends HashMap implements Map + +" +"What is LinkedHashMap class Parameters? +","Let's see the Parameters for java.util.LinkedHashMap class. +-K: It is the type of keys maintained by this map. +-V: It is the type of mapped values. +" +"What are the Constructors of the Java LinkedHashMap class? +","Constructor: LinkedHashMap() +Description:It is used to construct a default LinkedHashMap. + +Constructor:LinkedHashMap(int capacity) +Description:It is used to initialize a LinkedHashMap with the given capacity. + +Constructor:LinkedHashMap(int capacity, float loadFactor) +Description:It is used to initialize both the capacity and the load factor. + +Constructor:LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) +Description:It is used to initialize both the capacity and the load factor with specified ordering mode. + +Constructor:LinkedHashMap(Map m) +Description:It is used to initialize the LinkedHashMap with the elements from the given Map class m. +" +"What are the Methods of Java LinkedHashMap class? +","Method: V get(Object key) +Description: It returns the value to which the specified key is mapped. + +Method: void clear() +Description: It removes all the key-value pairs from a map. + +Method: boolean containsValue(Object value) +Description: It returns true if the map maps one or more keys to the specified value. + +Method: Set> entrySet() +Description: It returns a Set view of the mappings contained in the map. + +Method: void forEach(BiConsumer action) +Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. + +Method: V getOrDefault(Object key, V defaultValue) +Description: It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key. + +Method: Set keySet() +Description: It returns a Set view of the keys contained in the map + +Method: protected boolean removeEldestEntry(Map.Entry eldest) +Description: It returns true on removing its eldest entry. + +Method: void replaceAll(BiFunction function) +Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. + +Method: Collection values() +Description: It returns a Collection view of the values contained in this map. +" +"Can you provide an example of Java LinkedHashMap? +","import java.util.*; +class LinkedHashMap1{ + public static void main(String args[]){ + + LinkedHashMap hm=new LinkedHashMap(); + + hm.put(100,""Amit""); + hm.put(101,""Vijay""); + hm.put(102,""Rahul""); + +for(Map.Entry m:hm.entrySet()){ + System.out.println(m.getKey()+"" ""+m.getValue()); + } + } +} + +Output:100 Amit + 101 Vijay + 102 Rahul +" +"What is Java TreeMap class? +","Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order. + +The important points about Java TreeMap class are: + +-Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. +-Java TreeMap contains only unique elements. +-Java TreeMap cannot have a null key but can have multiple null values. +-Java TreeMap is non synchronized. +-Java TreeMap maintains ascending order. + + +" +"What is the class declaration for TreeMap class? +","Let's see the declaration for java.util.TreeMap class. + +public class TreeMap extends AbstractMap implements NavigableMap, Cloneable, Serializable +" +"What is TreeMap class Parameters? +","Let's see the Parameters for java.util.TreeMap class. +-K: It is the type of keys maintained by this map. +-V: It is the type of mapped values. +" +"What are the Constructors of the Java TreeMap class? +","Constructor:TreeMap() +Description:It is used to construct an empty tree map that will be sorted using the natural order of its key. + +Constructor:TreeMap(Comparator comparator) +Description:It is used to construct an empty tree-based map that will be sorted using the comparator comp. + +Constructor:TreeMap(Map m) +Description:It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys. + +Constructor:TreeMap(SortedMap m) +Description:It is used to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm. +" +"What are the Methods of Java TreeMap class? +","Method: Map.Entry ceilingEntry(K key) +Description: It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key. + +Method: K ceilingKey(K key) +Description: It returns the least key, greater than the specified key or null if there is no such key. + +Method: void clear() +Description: It removes all the key-value pairs from a map. + +Method: Object clone() +Description: It returns a shallow copy of TreeMap instance. + +Method: Comparator comparator() +Description: It returns the comparator that arranges the key in order, or null if the map uses the natural ordering. + +Method: NavigableSet descendingKeySet() +Description: It returns a reverse order NavigableSet view of the keys contained in the map. + +Method: NavigableMap descendingMap() +Description: It returns the specified key-value pairs in descending order. + +Method: Map.Entry firstEntry() +Description: It returns the key-value pair having the least key. + +Method:Map.Entry floorEntry(K key) +Description: It returns the greatest key, less than or equal to the specified key, or null if there is no such key. + +Method: void forEach(BiConsumer action) +Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. + +Method: SortedMap headMap(K toKey) +Description: It returns the key-value pairs whose keys are strictly less than toKey. + +Method:NavigableMap headMap(K toKey, boolean inclusive) +Description: It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey. + +Method: Map.Entry higherEntry(K key) +Description: It returns the least key strictly greater than the given key, or null if there is no such key. + +Method: K higherKey(K key) +Description: It is used to return true if this map contains a mapping for the specified key + +Method: Set keySet() +Description: It returns the collection of keys exist in the map. + +Method: Map.Entry lastEntry() +Description: It returns the key-value pair having the greatest key, or null if there is no such key. + +Method: Map.Entry lowerEntry(K key) +Description: It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key. + +Method: K lowerKey(K key) +Description: It returns the greatest key strictly less than the given key, or null if there is no such key. + +Method: NavigableSet navigableKeySet() +Description: It returns a NavigableSet view of the keys contained in this map. + +Method: Map.Entry pollFirstEntry() +Description: It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. + +Method: Map.Entry pollLastEntry() +Description: It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. + +Method: V put(K key, V value) +Description: It inserts the specified value with the specified key in the map. + +Method: void putAll(Map map) +Description: It is used to copy all the key-value pair from one map to another map. + +Method: V replace(K key, V value) +Description: It replaces the specified value for a specified key. + +Method: boolean replace(K key, V oldValue, V newValue) +Description: It replaces the old value with the new value for a specified key. + +Method: void replaceAll(BiFunction function) +Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. + +Method: NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) +Description: It returns key-value pairs whose keys range from fromKey to toKey. + +Method: SortedMap subMap(K fromKey, K toKey) +Description: It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive. + +Method: SortedMap tailMap(K fromKey) +Description: It returns key-value pairs whose keys are greater than or equal to fromKey. + +Method: NavigableMap tailMap(K fromKey, boolean inclusive) +Description: It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey. + +Method: boolean containsKey(Object key) +Description: It returns true if the map contains a mapping for the specified key. + +Method: boolean containsValue(Object value) +Description:It returns true if the map maps one or more keys to the specified value. + +Method: K firstKey() +Description: It is used to return the first (lowest) key currently in this sorted map. + +Method: V get(Object key) +Description: It is used to return the value to which the map maps the specified key. + +Method: K lastKey() +Description: It is used to return the last (highest) key currently in the sorted map. + +Method: V remove(Object key) +Description: It removes the key-value pair of the specified key from the map. + +Method: Set> entrySet() +Description: It returns a set view of the mappings contained in the map. + +Method: int size() +Description: It returns the number of key-value pairs exists in the hashtable. + +Method: Collection values() +Description: It returns a collection view of the values contained in the map. +" +"Can you provide an example of Java TreeMap? +","import java.util.*; +class TreeMap1{ + public static void main(String args[]){ + TreeMap map=new TreeMap(); + map.put(100,""Amit""); + map.put(102,""Ravi""); + map.put(101,""Vijay""); + map.put(103,""Rahul""); + + for(Map.Entry m:map.entrySet()){ + System.out.println(m.getKey()+"" ""+m.getValue()); + } + } +} +Output:100 Amit + 101 Vijay + 102 Ravi + 103 Rahul + +" +"What is Java Hashtable class? +","Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and implements the Map interface. +Points to remember +-A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. +-Java Hashtable class contains unique elements. +-Java Hashtable class doesn't allow null key or value. +-Java Hashtable class is synchronized. +-The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75. +" +"What is the class declaration for Hashtable class? +","Let's see the declaration for java.util.Hashtable class. + +public class Hashtable extends Dictionary implements Map, Cloneable, Serializable +" +"What is Hashtable class Parameters? +","Let's see the Parameters for java.util.Hashtable class. + +-K: It is the type of keys maintained by this map. +-V: It is the type of mapped values. +" +"What are the Constructors of the Java Hashtable class? +","Constructor:Hashtable() +Description:It creates an empty hashtable having the initial default capacity and load factor. + +Constructor:Hashtable(int capacity) +Description:It accepts an integer parameter and creates a hash table that contains a specified initial capacity. + +Constructor:Hashtable(int capacity, float loadFactor) +Description:It is used to create a hash table having the specified initial capacity and loadFactor. + +Constructor:Hashtable(Map t) +Description:It creates a new hash table with the same mappings as the given Map. " +"What are the Methods of Java Hashtable class? +","Method: void clear() +Description: It is used to reset the hash table. + +Method: Object clone() +Description: It returns a shallow copy of the Hashtable. + +Method: V compute(K key, BiFunction remappingFunction) +Description: It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). + +Method: V computeIfAbsent(K key, Function mappingFunction) +Description: It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. + +Method: V computeIfPresent(K key, BiFunction remappingFunction) +Description: It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. + +Method: Enumeration elements() +Description: It returns an enumeration of the values in the hash table. + +Method: Set> entrySet() +Description: It returns a set view of the mappings contained in the map. + +Method: boolean equals(Object o) +Description: It is used to compare the specified Object with the Map. + +Method: void forEach(BiConsumer action) +Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. + +Method: V getOrDefault(Object key, V defaultValue) +Description: It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. + +Method: int hashCode() +Description: It returns the hash code value for the Map + +Method: Enumeration keys() +Description: It returns an enumeration of the keys in the hashtable. + +Method: Set keySet() +Description: It returns a Set view of the keys contained in the map. + +Method: V merge(K key, V value, BiFunction remappingFunction) +Description: If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. + +Method: V put(K key, V value) +Description: It inserts the specified value with the specified key in the hash table. + +Method: void putAll(Map t)) +Description: It is used to copy all the key-value pair from map to hashtable. + +Method: V putIfAbsent(K key, V value) +Description: If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value. + +Method: boolean remove(Object key, Object value) +Description: It removes the specified values with the associated specified keys from the hashtable. + +Method: V replace(K key, V value) +Description: It replaces the specified value for a specified key. + +Method: boolean replace(K key, V oldValue, V newValue) +Description: It replaces the old value with the new value for a specified key. + +Method: void replaceAll(BiFunction function) +Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. + +Method: String toString() +Description: It returns a string representation of the Hashtable object. + +Method: Collection values() +Description: It returns a collection view of the values contained in the map. + +Method: boolean contains(Object value) +Description: This method returns true if some value equal to the value exists within the hash table, else return false. + +Method: boolean containsValue(Object value) +Description: This method returns true if some value equal to the value exists within the hash table, else return false. + +Method: boolean containsKey(Object key) +Description: This method return true if some key equal to the key exists within the hash table, else return false. + +Method: boolean isEmpty() +Description: This method returns true if the hash table is empty; returns false if it contains at least one key. + +Method: protected void rehash() +Description: It is used to increase the size of the hash table and rehashes all of its keys. + +Method: V get(Object key) +Description: This method returns the object that contains the value associated with the key. + +Method: V remove(Object key) +Description: It is used to remove the key and its value. This method returns the value associated with the key. + +Method: int size() +Description: This method returns the number of entries in the hash table. " +"Can you provide an example of Java Hashtable? +","import java.util.*; +class Hashtable1{ + public static void main(String args[]){ + Hashtable hm=new Hashtable(); + + hm.put(100,""Amit""); + hm.put(102,""Ravi""); + hm.put(101,""Vijay""); + hm.put(103,""Rahul""); + + for(Map.Entry m:hm.entrySet()){ + System.out.println(m.getKey()+"" ""+m.getValue()); + } + } +} + +Output: +103 Rahul +102 Ravi +101 Vijay +100 Amit +" +"What are the Difference between HashMap and Hashtable? +","HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. + +But there are many differences between HashMap and Hashtable classes that are given below. +1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code while Hashtable is synchronized. It is thread-safe and can be shared with many threads. +2) HashMap allows one null key and multiple null values while Hashtable doesn't allow any null key or value. +3) HashMap is a new class introduced in JDK 1.2 while Hashtable is a legacy class. +4) HashMap is fast while Hashtable is slow. +5) We can make the HashMap as synchronized by calling this code +Map m = Collections.synchronizedMap(hashMap); while Hashtable is internally synchronized and can't be unsynchronized. +6) HashMap is traversed by Iterator while Hashtable is traversed by Enumerator and Iterator. +7) Iterator in HashMap is fail-fast while Enumerator in Hashtable is not fail-fast. +8) HashMap inherits AbstractMap class while Hashtable inherits Dictionary class. + +" +"What is Java EnumSet class? +","Java EnumSet class is the specialized Set implementation for use with enum types. It inherits AbstractSet class and implements the Set interface. +" +"What is the class declaration for EnumSet class? +","Let's see the declaration for java.util.EnumSet class. + +public abstract class EnumSet> extends AbstractSet implements Cloneable, Serializable +" +"What are the Methods of Java EnumSet class? +","Method: static > EnumSet allOf(Class elementType) +Description: It is used to create an enum set containing all of the elements in the specified element type. + +Method: static > EnumSet copyOf(Collection c) +Description: It is used to create an enum set initialized from the specified collection. + +Method: static > EnumSet noneOf(Class elementType) +Description: It is used to create an empty enum set with the specified element type. + +Method: static > EnumSet of(E e) +Description: It is used to create an enum set initially containing the specified element. + +Method: static > EnumSet range(E from, E to) +Description: It is used to create an enum set initially containing the specified elements. + +Method: EnumSet clone() +Description: It is used to return a copy of this set. + + +" +"Can you provide an example of Java EnumSet? +","import java.util.*; +enum days { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY +} +public class EnumSetExample { + public static void main(String[] args) { + Set set = EnumSet.of(days.TUESDAY, days.WEDNESDAY); + // Traversing elements + Iterator iter = set.iterator(); + while (iter.hasNext()) + System.out.println(iter.next()); + } +} + +Output: +TUESDAY +WEDNESDAY +" +"What is Java EnumMap class? +",Java EnumMap class is the specialized Map implementation for enum keys. It inherits Enum and AbstractMap classes. +"What is the class declaration for EnumMap class? +","Let's see the declaration for java.util.EnumMap class. + +public class EnumMap,V> extends AbstractMap implements Serializable, Cloneable " +"What is EnumMap class Parameters? +","Let's see the Parameters for java.util.EnumMap class. + +-K: It is the type of keys maintained by this map. +-V: It is the type of mapped values. +" +"What are the Constructors of the Java EnumMap class? +","Constructor: EnumMap(Class keyType) +Description: It is used to create an empty enum map with the specified key type. + +Constructor: EnumMap(EnumMap m) +Description: It is used to create an enum map with the same key type as the specified enum map. + +Constructor: EnumMap(Map m) +Description:It is used to create an enum map initialized from the specified map. +" +"What are the Methods of Java EnumMap class? +"," +Sn:1 +Method: clear() +Description: It is used to clear all the mapping from the map. + +Sn:2 +Method:clone() +Description: It is used to copy the mapped value of one map to another map. + +Sn:3 +Method:containsKey() +Description:It is used to check whether a specified key is present in this map or not. + +Sn:4 +Method:containsValue() +Description: It is used to check whether one or more key is associated with a given value or not. + +Sn:5 +Method:entrySet() +Description:It is used to create a set of elements contained in the EnumMap. + +Sn:6 +Method:equals() +Description: It is used to compare two maps for equality. + +Sn:7 +Method: get() +Description: It is used to get the mapped value of the specified key. + +Sn:8 +Method: hashCode() +Description: It is used to get the hashcode value of the EnumMap. + +Sn:9 +Method:keySet() +Description: It is used to get the set view of the keys contained in the map. + +Sn:10 +Method: size() +Description: It is used to get the size of the EnumMap. + +Sn:11 +Method:Values() +Description: It is used to create a collection view of the values contained in this map. + +Sn:12 +Method: put() +Description: It is used to associate the given value with the given key in this EnumMap + +Sn:13 +Method: putAll() +Description: It is used to copy all the mappings from one EnumMap to a new EnumMap. + +Sn:14 +Method: remove() +Description: It is used to remove the mapping for the given key from EnumMap if the given key is present. +" +"Can you provide an example of Java EnumMap? +"," +import java.util.*; +public class EnumMapExample { + // create an enum + public enum Days { + Monday, Tuesday, Wednesday, Thursday + }; + public static void main(String[] args) { + //create and populate enum map + EnumMap map = new EnumMap(Days.class); + map.put(Days.Monday, ""1""); + map.put(Days.Tuesday, ""2""); + map.put(Days.Wednesday, ""3""); + map.put(Days.Thursday, ""4""); + // print the map + for(Map.Entry m:map.entrySet()){ + System.out.println(m.getKey()+"" ""+m.getValue()); + } + } +} + +Output: +Monday 1 +Tuesday 2 +Wednesday 3 +Thursday 4 +" +"What is Java Collections class? +","Java collection class is used exclusively with static methods that operate on or return collections. It inherits Object class. + +The important points about Java Collections class are: + +-Java Collection class supports the polymorphic algorithms that operate on collections. +-Java Collection class throws a NullPointerException if the collections or class objects provided to them are null. " +"What is the class declaration for Collections class? +","Let's see the declaration for java.util.Collections class. + +public class Collections extends Object +" +Can you provide an example of Java Collections?,"import java.util.*; +public class CollectionsExample { + public static void main(String a[]){ + List list = new ArrayList(); + list.add(""C""); + list.add(""Core Java""); + list.add(""Advance Java""); + System.out.println(""Initial collection value:""+list); + Collections.addAll(list, ""Servlet"",""JSP""); + System.out.println(""After adding elements collection value:""+list); + String[] strArr = {""C#"", "".Net""}; + Collections.addAll(list, strArr); + System.out.println(""After adding array collection value:""+list); + } +} + +Output: +Initial collection value:[C, Core Java, Advance Java] +After adding elements collection value:[C, Core Java, Advance Java, Servlet, JSP] +After adding array collection value:[C, Core Java, Advance Java, Servlet, JSP, C#, .Net] +" +"What is Sorting in Collection? +","We can sort the elements of: +-String objects +-Wrapper class objects +-User-defined class objects +Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements. + +" +What is the Method of Collections class for sorting List elements?,public void sort(List list): is used to sort the elements of List. List elements must be of the Comparable type. +"Can you provide an example to sort string objects? +","import java.util.*; +class TestSort1{ +public static void main(String args[]){ + +ArrayList al=new ArrayList(); +al.add(""Viru""); +al.add(""Saurav""); +al.add(""Mukesh""); +al.add(""Tahir""); + +Collections.sort(al); +Iterator itr=al.iterator(); +while(itr.hasNext()){ +System.out.println(itr.next()); + } +} +} + +Mukesh +Saurav +Tahir +Viru +" +"What is Java Comparable interface? +","Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else." +"What is compareTo(Object obj) method? +","public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns + +-positive integer, if the current object is greater than the specified object. +-negative integer, if the current object is less than the specified object. +-zero, if the current object is equal to the specified object. +" +"What is Java Comparator interface? +","Java Comparator interface is used to order the objects of a user-defined class. + +This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element). + +It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age or anything else. +" +"What are the Methods of Java Comparator Interface? +","Method: public int compare(Object obj1, Object obj2) +Description: It compares the first object with the second object. + +Method: public boolean equals(Object obj) +Description: It is used to compare the current object with the specified object. + +Method: public boolean equals(Object obj) +Description: It is used to compare the current object with the specified object. +" +"Can you provide an example of Java Comparator (Non-generic Old Style)? +","Let's see the example of sorting the elements of List on the basis of age and name. In this example, we have created 4 java classes: + +1.Student.java +2..AgeComparator.java +3.NameComparator.java +4.Simple.java + +Student.java +This class contains three fields rollno, name and age and a parameterized constructor. + +class Student{ +int rollno; +String name; +int age; +Student(int rollno,String name,int age){ +this.rollno=rollno; +this.name=name; +this.age=age; +} +} + +AgeComparator.java +This class defines comparison logic based on the age. If the age of the first object is greater than the second, we are returning a positive value. It can be anyone such as 1, 2, 10. If the age of the first object is less than the second object, we are returning a negative value, it can be any negative value, and if the age of both objects is equal, we are returning 0. + +import java.util.*; +class AgeComparator implements Comparator{ +public int compare(Object o1,Object o2){ +Student s1=(Student)o1; +Student s2=(Student)o2; + +if(s1.age==s2.age) +return 0; +else if(s1.age>s2.age) +return 1; +else +return -1; +} +} + +NameComparator.java +This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic. + +import java.util.*; +class NameComparator implements Comparator{ +public int compare(Object o1,Object o2){ +Student s1=(Student)o1; +Student s2=(Student)o2; + +return s1.name.compareTo(s2.name); +} +} + +Simple.java +In this class, we are printing the values of the object by sorting on the basis of name and age. +import java.util.*; +import java.io.*; + +class Simple{ +public static void main(String args[]){ + +ArrayList al=new ArrayList(); +al.add(new Student(101,""Vijay"",23)); +al.add(new Student(106,""Ajay"",27)); +al.add(new Student(105,""Jai"",21)); + +System.out.println(""Sorting by Name""); + +Collections.sort(al,new NameComparator()); +Iterator itr=al.iterator(); +while(itr.hasNext()){ +Student st=(Student)itr.next(); +System.out.println(st.rollno+"" ""+st.name+"" ""+st.age); +} + +System.out.println(""Sorting by age""); + +Collections.sort(al,new AgeComparator()); +Iterator itr2=al.iterator(); +while(itr2.hasNext()){ +Student st=(Student)itr2.next(); +System.out.println(st.rollno+"" ""+st.name+"" ""+st.age); +} + + +} +} + + Sorting by Name + 106 Ajay 27 + 105 Jai 21 + 101 Vijay 23 + + Sorting by age + 105 Jai 21 + 101 Vijay 23 + 106 Ajay 27 +" +"Can you provide an example of Java Comparator (Generic)? +"," + +Student.java + +class Student{ +int rollno; +String name; +int age; +Student(int rollno,String name,int age){ +this.rollno=rollno; +this.name=name; +this.age=age; +} +} + +AgeComparator.java + +import java.util.*; +class AgeComparator implements Comparator{ +public int compare(Student s1,Student s2){ +if(s1.age==s2.age) +return 0; +else if(s1.age>s2.age) +return 1; +else +return -1; +} +} + + +NameComparator.java + +This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic. + +import java.util.*; +class NameComparator implements Comparator{ +public int compare(Student s1,Student s2){ +return s1.name.compareTo(s2.name); +} +} + +Simple.java +In this class, we are printing the values of the object by sorting on the basis of name and age. + +import java.util.*; +import java.io.*; +class Simple{ +public static void main(String args[]){ + +ArrayList al=new ArrayList(); +al.add(new Student(101,""Vijay"",23)); +al.add(new Student(106,""Ajay"",27)); +al.add(new Student(105,""Jai"",21)); + +System.out.println(""Sorting by Name""); + +Collections.sort(al,new NameComparator()); +for(Student st: al){ +System.out.println(st.rollno+"" ""+st.name+"" ""+st.age); +} + +System.out.println(""Sorting by age""); + +Collections.sort(al,new AgeComparator()); +for(Student st: al){ +System.out.println(st.rollno+"" ""+st.name+"" ""+st.age); +} +} +} + Sorting by Name + 106 Ajay 27 + 105 Jai 21 + 101 Vijay 23 + + Sorting by age + 105 Jai 21 + 101 Vijay 23 + 106 Ajay 27 + +" +What is Properties class in Java?,"The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable. + +It can be used to get property value based on the property key. The Properties class provides methods to get data from the properties file and store data into the properties file. Moreover, it can be used to get the properties of a system +" +"What is the Advantage of the properties file? +","Recompilation is not required if the information is changed from a properties file: If any information is changed from the properties file, you don't need to recompile the java class. It is used to store information which is to be changed frequently." +"What are the Constructors of the Properties class? +","Constructor:Properties() +Description: It creates an empty property list with no default values. + +Constructor:Properties(Properties defaults) +Description:It creates an empty property list with the specified defaults. " +"What are the Methods of Properties class? +","Method: public void load(Reader r) +Description: It loads data from the Reader object. + +Method: public void load(InputStream is) +Description: It loads data from the InputStream object + +Method: public void loadFromXML(InputStream in) +Description: It is used to load all of the properties represented by the XML document on the specified input stream into this properties table. + +Method: public String getProperty(String key) +Description: It returns value based on the key. + +Method:public String getProperty(String key, String defaultValue) +Description: It searches for the property with the specified key. + +Method:public void setProperty(String key, String value) +Description: It calls the put method of Hashtable. + +Method: public void list(PrintStream out) +Description: It is used to print the property list out to the specified output stream. + +Method: public void list(PrintWriter out)) +Description: It is used to print the property list out to the specified output stream. + +Method: public Enumeration propertyNames()) +Description: It returns an enumeration of all the keys from the property list. + +Method: public Set stringPropertyNames() +Description: It returns a set of keys in from property list where the key and its corresponding value are strings. + +Method:public void store(Writer w, String comment) +Description: It writes the properties in the writer object. + +Method: public void store(OutputStream os, String comment) +Description: It writes the properties in the OutputStream object. + +Method: public void storeToXML(OutputStream os, String comment) +Description: It writes the properties in the writer object for generating XML document. + +Method: public void storeToXML(Writer w, String comment, String encoding) +Description: It writes the properties in the writer object for generating XML document with the specified encoding. +" +"Can you provide an example of Properties class to get information from the properties file? +","To get information from the properties file, create the properties file first. + +db.properties +user=system +password=oracle + +Now, let's create the java class to read the data from the properties file. + +Test.java + +import java.util.*; +import java.io.*; +public class Test { +public static void main(String[] args)throws Exception{ + FileReader reader=new FileReader(""db.properties""); + + Properties p=new Properties(); + p.load(reader); + + System.out.println(p.getProperty(""user"")); + System.out.println(p.getProperty(""password"")); +} +} + +Output:system + oracle + + +Now if you change the value of the properties file, you don't need to recompile the java class. That means no maintenance problem. +" +"What are the Difference between ArrayList and Vector? +","ArrayList and Vector both implements List interface and maintains insertion order. + +However, there are many differences between ArrayList and Vector classes that are given below. +1) ArrayList is not synchronized while Vector is synchronized. +2) ArrayList increments 50% of current array size if the number of elements exceeds from its capacity while Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity. +3) ArrayList is not a legacy class. It is introduced in JDK 1.2 while Vector is a legacy class. +4) ArrayList is fast because it is non-synchronized while Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object. +5) ArrayList uses the Iterator interface to traverse the elements while A Vector can use the Iterator interface or Enumeration interface to traverse the elements. +" +"What is Java Vector? +","Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here. + +It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in such case. + +The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and throws the ConcurrentModificationException. + +It is similar to the ArrayList, but with two differences- +-Vector is synchronized. +-Java Vector contains many legacy methods that are not the part of a collections framework. +" +"What is the class declaration for Java Vector class? +","public class Vector +extends Object +implements List, Cloneable, Serializable +" +"What are the Constructors of the Java Vector? +","SN:1 +Constructor: vector() +Description: It constructs an empty vector with the default size as 10. + +SN:2 +Constructor: vector(int initialCapacity) +Description: It constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. + +SN:3 +Constructor: vector(int initialCapacity, int capacityIncrement) +Description: It constructs an empty vector with the specified initial capacity and capacity increment. + +SN:4 +Constructor: Vector( Collection c) +Description: It constructs a vector that contains the elements of a collection c. " +"Can you provide an example of Java Vector? +"," + +import java.util.*; +public class VectorExample { + public static void main(String args[]) { + //Create a vector + Vector vec = new Vector(); + //Adding elements using add() method of List + vec.add(""Tiger""); + vec.add(""Lion""); + vec.add(""Dog""); + vec.add(""Elephant""); + //Adding elements using addElement() method of Vector + vec.addElement(""Rat""); + vec.addElement(""Cat""); + vec.addElement(""Deer""); + + System.out.println(""Elements are: ""+vec); + } +} + + +Output: +Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer] +" +"What are the methods of Java Stack? +","SN:1 +Method: add() +Description: It is used to append the specified element in the given vector. + +SN:2 +Method: addAll() +Description:It is used to append all of the elements in the specified collection to the end of this Vector. + +SN:3 +Method:addElement() +Description:It is used to append the specified component to the end of this vector. It increases the vector size by one. + +SN:4 +Method: capacity() +Description:It is used to get the current capacity of this vector. + +SN:5 +Method: clear() +Description:It is used to delete all of the elements from this vector. + +SN:6 +Method: clone() +Description:It returns a clone of this vector. + +SN:7 +Method: contains() +Description:It returns true if the vector contains the specified element. + +SN:8 +Method: containsAll() +Description:It returns true if the vector contains all of the elements in the specified collection. + +SN:9 +Method: copyInto() +Description:It is used to copy the components of the vector into the specified array. + +SN:10 +Method: elementAt() +Description:It is used to get the component at the specified index. + +SN:11 +Method: elements() +Description: It returns an enumeration of the components of a vector. + +SN:12 +Method: ensureCapacity() +Description:It is used to increase the capacity of the vector which is in use, if necessary. It ensures that the vector can hold at least the number of components specified by the minimum capacity argument. + +SN:13 +Method: equals() +Description:It is used to compare the specified object with the vector for equality. + +SN:14 +Method: firstElement() +Description:It is used to get the first component of the vector. + +SN:15 +Method: forEach() +Description:It is used to perform the given action for each element of the Iterable until all elements have been processed or the action throws an exception. + +SN:16 +Method: get() +Description:It is used to get an element at the specified position in the vector. + +SN:17 +Method: hashCode() +Description:It is used to get the hash code value of a vector + +SN:18 +Method: indexOf() +Description:It is used to get the index of the first occurrence of the specified element in the vector. It returns -1 if the vector does not contain the element. + +SN:19 +Method: insertElementAt() +Description:It is used to insert the specified object as a component in the given vector at the specified index. + +SN:20 +Method: isEmpty() +Description:It is used to check if this vector has no components. + +SN:21 +Method: iterator() +Description: It is used to get an iterator over the elements in the list in proper sequence. + +SN:22 +Method:lastElement() +Description:It is used to get the last component of the vector. + +SN:23 +Method: lastIndexOf() +Description: It is used to get the index of the last occurrence of the specified element in the vector. It returns -1 if the vector does not contain the element. + +SN:24 +Method: listIterator() +Description:It is used to get a list iterator over the elements in the list in proper sequence. + +SN:25 +Method: remove() +Description:It is used to remove the specified element from the vector. If the vector does not contain the element, it is unchanged. + +SN:26 +Method: removeAll() +Description: It is used to delete all the elements from the vector that are present in the specified collection. + +SN:27 +Method: removeAllElements() +Description:It is used to remove all elements from the vector and set the size of the vector to zero. + +SN:28 +Method: removeElement() +Description:It is used to remove the first (lowest-indexed) occurrence of the argument from the vector. + +SN:29 +Method: removeElementAt() +Description:It is used to delete the component at the specified index. + +SN:30 +Method: removeIf() +Description:It is used to remove all of the elements of the collection that satisfy the given predicate. + +SN:31 +Method: removeRange() +Description:It is used to delete all of the elements from the vector whose index is between fromIndex, inclusive and toIndex, exclusive. + + +SN:32 +Method: replaceAll() +Description:It is used to replace each element of the list with the result of applying the operator to that element. + +SN:33 +Method: retainAll() +Description:It is used to retain only that element in the vector which is contained in the specified collection. + +SN:34 +Method: set() +Description:It is used to replace the element at the specified position in the vector with the specified element. + +SN:35 +Method: setElementAt() +Description:It is used to set the component at the specified index of the vector to the specified object. + +SN:36 +Method: setSize() +Description:It is used to set the size of the given vector. + + +SN:37 +Method: size() +Description:It is used to get the number of components in the given vector. + +SN:38 +Method: sort() +Description:It is used to sort the list according to the order induced by the specified Comparator. + +SN:39 +Method: spliterator() +Description:It is used to create a late-binding and fail-fast Spliterator over the elements in the list. + +SN:40 +Method: subList() +Description:It is used to get a view of the portion of the list between fromIndex, inclusive, and toIndex, exclusive. + +SN:41 +Method: toArray() +Description:It is used to get an array containing all of the elements in this vector in correct order. + +SN:42 +Method: toString() +Description:It is used to get a string representation of the vector. + +SN:43 +Method: trimToSize() +Description:It is used to trim the capacity of the vector to the vector's current size. +" +"What is Java Stack Class? +","In Java, Stack is a class that falls under the Collection framework that extends the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. It represents the LIFO stack of objects. Before using the Stack class, we must import the java.util package. The stack class arranged in the Collections framework hierarchy. + +" +"What are the Constructors of the Stack Class? +","The Stack class contains only the default constructor that creates an empty stack. + +public Stack() " +"How to Creat a Stack? +","If we want to create a stack, first, import the java.util package and create an object of the Stack class. + +Stack stk = new Stack(); +Or +Stack stk = new Stack<>(); +" +"What are the Methods of the Stack Class? +"," +We can perform push, pop, peek and search operation on the stack. The Java Stack class provides mainly five methods to perform these operations. Along with this, it also provides all the methods of the Java Vector class. + +Method: empty() +Modifier and Type: boolean +Description: The method checks the stack is empty or not. + +Method: push(E item) +Modifier and Type: E +Description: The method pushes (insert) an element onto the top of the stack. + +Method: pop() +Modifier and Type: : E +Description: The method removes an element from the top of the stack and returns the same element as the value of that function. + +Method: peek() +Modifier and Type: : E +Description: The method looks at the top element of the stack without removing it. + +Method: search(Object o) +Modifier and Type: int +Description: The method searches the specified object and returns the position of the object. +" +"What is Java Collection Interface? +","Collection is a group of objects, which are known as elements. It is the root interface in the collection hierarchy. This interface is basically used to pass around the collections and manipulate them where the maximum generality is desired. +" +"What is Iterator in Java? +","In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is practiced in order to iterate over a collection of Java object components entirety one by one. It is free to use in the Java programming language since the Java 1.2 Collection framework. It belongs to java.util package. + +Though Java Iterator was introduced in Java 1.2, however, it is still not the oldest tool available to traverse through the elements of the Collection object. The oldest Iterator in the Java programming language is the Enumerator predated Iterator. Java Iterator interface succeeds the enumerator iterator that was practiced in the beginning to traverse over some accessible collections like the ArrayLists. + +The Java Iterator is also known as the universal cursor of Java as it is appropriate for all the classes of the Collection framework. The Java Iterator also helps in the operations like READ and REMOVE. When we compare the Java Iterator interface with the enumeration iterator interface, we can say that the names of the methods available in Java Iterator are more precise and straightforward to use. +" +"What are the Advantages of Java Iterator? +"," +Iterator in Java became very prevalent due to its numerous advantages. The advantages of Java Iterator are given as follows : +-The user can apply these iterators to any of the classes of the Collection framework. +-In Java Iterator, we can use both of the read and remove operations. +-If a user is working with a for loop, they cannot modernize(add/remove) the Collection, whereas, if they use the Java Iterator, they can simply update the Collection. +-The Java Iterator is considered the Universal Cursor for the Collection API. +-The method names in the Java Iterator are very easy and are very simple to use. +" +What are the Disadvantages of Java Iterator?,"Despite the numerous advantages, the Java Iterator has various disadvantages also. The disadvantages of the Java Iterator are given below : + +-The Java Iterator only preserves the iteration in the forward direction. In simple words, the Java Iterator is a uni-directional Iterator. +-The replacement and extension of a new component are not approved by the Java Iterator. +-In CRUD Operations, the Java Iterator does not hold the various operations like CREATE and UPDATE. +-In comparison with the Spliterator, Java Iterator does not support traversing elements in the parallel pattern which implies that Java Iterator supports only Sequential iteration. +-In comparison with the Spliterator, Java Iterator does not support more reliable execution to traverse the bulk volume of data. +" +"How to use Java Iterator? +","When a user needs to use the Java Iterator, then it's compulsory for them to make an instance of the Iterator interface from the collection of objects they desire to traverse over. After that, the received Iterator maintains the trail of the components in the underlying collection to make sure that the user will traverse over each of the elements of the collection of objects. + +If the user modifies the underlying collection while traversing over an Iterator leading to that collection, then the Iterator will typically acknowledge it and will throw an exception in the next time when the user will attempt to get the next component from the Iterator. +" +"What are the methods of Java Iterator? +","The following figure perfectly displays the class diagram of the Java Iterator interface. It contains a total of four methods that are: + +-hasNext() +-next() +-remove() +-forEachRemaining() + +The forEachRemaining() method was added in the Java 8. Let's discuss each method in detail. + +-boolean hasNext(): The method does not accept any parameter. It returns true if there are more elements left in the iteration. If there are no more elements left, then it will return false. +If there are no more elements left in the iteration, then there is no need to call the next() method. In simple words, we can say that the method is used to determine whether the next() method is to be called or not. + +-E next(): It is similar to hasNext() method. It also does not accept any parameter. It returns E, i.e., the next element in the traversal. If the iteration or collection of objects has no more elements left to iterate, then it throws the NoSuchElementException. + +-default void remove(): This method also does not require any parameters. There is no return type of this method. The main function of this method is to remove the last element returned by the iterator traversing through the underlying collection. The remove () method can be requested hardly once per the next () method call. If the iterator does not support the remove operation, then it throws the UnSupportedOperationException. It also throws the IllegalStateException if the next method is not yet called. + +-default void forEachRemaining(Consumer action): It is the only method of Java Iterator that takes a parameter. It accepts action as a parameter. Action is nothing but that is to be performed. There is no return type of the method. This method performs the particularized operation on all of the left components of the collection until all the components are consumed or the action throws an exception. Exceptions thrown by action are delivered to the caller. If the action is null, then it throws a NullPointerException. +" +"Can you provide an example of Java Iterator? +","Now it's time to execute a Java program to illustrate the advantage of the Java Iterator interface. The below code produces an ArrayList of city names. Then we initialize an iterator applying the iterator () method of the ArrayList. After that, the list is traversed to represent each element. + +JavaIteratorExample.java + +import java.io.*; +import java.util.*; + +public class JavaIteratorExample { + public static void main(String[] args) + { + ArrayList cityNames = new ArrayList(); + + cityNames.add(""Delhi""); + cityNames.add(""Mumbai""); + cityNames.add(""Kolkata""); + cityNames.add(""Chandigarh""); + cityNames.add(""Noida""); + + // Iterator to iterate the cityNames + Iterator iterator = cityNames.iterator(); + + System.out.println(""CityNames elements : ""); + + while (iterator.hasNext()) + System.out.print(iterator.next() + "" ""); + + System.out.println(); + } +} + +Output: +CityNames elements: +Delhi Mumbai Kolkata Chandigarh Noida +" +"What is Java Deque? +","A deque is a linear collection that supports insertion and deletion of elements from both the ends. The name 'deque' is an abbreviation for double-ended queue. + +There are no fixed limits on the deque for the number of elements they may contain. However, this interface supports capacity restricted deques as well as the deques with no fixed size limits. There are various methods which are provided to insert, remove and examine the elements. + +These methods typically exist in two forms: the one that throws an exception when the particular operation fails and the other returns a special value which can be either null or false depending upon the operations. +" +What are the methods of Java Deque?,"Method: add(E e) +Description: This method is used to insert a specified element into the queue represented by the deque + +Method: addAll(Collectionc) +Description: Adds all the elements in the specified collection at the end of the deque. + +Method: addFirst(E e) +Description: Inserts the specified element at the front of the deque. + +Method: addLast(E e) +Description: Inserts the specified element at the end of the deque. + +Method: contains(object o) +Description: Returns true if the deque contains the specified element. + +Method: descendingIterator() +Description: Returns an iterator over the elements in reverse sequential order. + +Method: element() +Description: Retrieves the head of the queue represented by the deque. + +Method: getFirst() +Description: Retrieves but does not remove the first element of the deque + +Method: getLast() +Description: Retrieves but does not remove the last element of the deque. + +Method:iterator() +Description: Returns an iterator over the element in the deque in a proper sequence. + +Method: offer(E e) +Description: Inserts the specified element into the deque, returning true upon success and false if no space is available. + +Method:offerFirst() +Description: Inserts the specified element at the front of the deque unless it violates the capacity restriction. + +Method: offerLast() +Description: Inserts the specified element at the end of the deque unless it violates the capacity restriction. + +Method: peek() +Description: Retrieves but does not move the head of the queue represented by the deque or may return null if the deque is empty. + +Method: peekFirst() +Description: Retrieves but does not move the first element of the deque or may return null if the deque is empty. + +Method: peekLast() +Description: Retrieves but does not move the last element of the deque or may return null if the deque is empty. + +Method: poll() +Description: Retrieves and remove the head of the queue represented by the deque or may return null if the deque is empty. + +Method: pollFirst() +Description: Retrieves and remove the first element of the deque or may return null if the deque is empty. + +Method: pollLast() +Description: Retrieves and remove the last element of the deque or may return null if the deque is empty. + +Method: pop() +Description: Pops an element from the stack represented by the deque. + +Method: push() +Description: Pushes an element onto the stack represented by the deque. + +Method: remove() +Description: Retrieves and remove the head of the queue represented by the deque. + +Method: remove(Object o) +Description: Removes the first occurrence of the specified element from the deque. + +Method: removeFirst() +Description: Retrieves and remove the first element from the deque. + +Method: removeFirstOccurrence(Object o) +Description: Remove the first occurrence of the element from the deque. + +Method: removeLast() +Description: Retrieve and remove the last element from the deque. + +Method: removeLastOccurrence(Object o) +Description: Remove the last occurrence of the element from the deque. + +Method: size() +Description: Returns the total number of elements in the deque. +" +What is Java ConcurrentHashMap class?,"A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.. + " +"What is the class declaration for Java ConcurrentHashMap class? +","public class ConcurrentHashMap +extends AbstractMap +implements ConcurrentMap, Serializable +" +"Can you provide an example of Java ConcurrentHashMap class: computeIfAbsent()? +","//import statement + +import java.util.concurrent.*; + + import java.util.*; + +public class ConcurrentHashMapcomputeIfAbsentExample1_1 { + + public static void main(String[] args) + { + // crete a HashMap and add some values + HashMap mapcon + = new HashMap<>(); + mapcon.put(""k1"", 100); + mapcon.put(""k2"", 200); + mapcon.put(""k3"", 300); + mapcon.put(""k4"", 400); + System.out.println(""HashMap values :\n "" + mapcon.toString()); + mapcon.computeIfAbsent(""k5"", k -> 200 + 300); + mapcon.computeIfAbsent(""k6"", k -> 60 * 10); + System.out.println(""New HashMap after computeIfAbsent :\n ""+ mapcon); + } +} +Output: +HashMap values : + {k1=100, k2=200, k3=300, k4=400} +New HashMap after computeIfAbsent : + {k1=100, k2=200, k3=300, k4=400, k5=500, k6=600} +" +"What is Java ConcurrentLinkedQueue Class? +",ConcurrentLinkedQueue is an unbounded thread-safe queue which arranges the element in FIFO. New elements are added at the tail of this queue and the elements are added from the head of this queue. +What are the class methods of Java ConcurrentLinkedQueue?," +Method: add() +Description: Inserts the specified element at the tail of this queue + +Method: addAll() +Description: Inserts all the elements which are present in the specified collection to the tail of this queue + +Method: contains() +Description: Returns true if this queue contains the specified element + +Method: forEach() +Description: Performs the given action for each element until all elements have been processed. + +Method: isEmpty() +Description: Returns true if this queue contains no elements. + +Method: iterator() +Description: Returns an iterator over the elements in this queue + +Method: offer() +Description: Inserts the specified element at the tail of this queue + +Method: remove() +Description: Removes the specified element from this queue, if this element is present in the queue + +Method: removeAll() +Description: Removes all the elements of this in queue which are present in the specified collection. + +Method: removeIf() +Description: Removes all the elements in this queue that satisfy the given predicate filter. + +Method: retainAll() +Description: Retain only those elements in this queue that are present in the specified collection. + +Method: size() +Description: Returns the number of the elements in this queue. + +Method: spliterator() +Description: Returns a spliterator over the elements in this queue. + +Method: toArray() +Description: Returns an array containing all the elements of this queue which are in proper sequence. " \ No newline at end of file