Java – Data Types ”; Previous Next Data types define the type and value range of the data for the different types of variables, constants, method parameters, returns type, etc. The data type tells the compiler about the type of data to be stored and the required memory. To store and manipulate different types of data, all variables must have specified data types. Java data types are categorized into two parts − Primitive Data Types Reference/Object Data Types Java Primitive Data Types Primitive data types are predefined by the language and named by a keyword. There are eight primitive data types supported by Java. Below is the list of the primitive data types: byte short int long float double boolean Java byte Data Type Byte data type is an 8-bit signed two”s complement integer Minimum value is -128 (-2^7) Maximum value is 127 (inclusive)(2^7 -1) Default value is 0 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer. Example − byte a = 100, byte b = -50 Java short Data Type Short data type is a 16-bit signed two”s complement integer Minimum value is -32,768 (-2^15) Maximum value is 32,767 (inclusive) (2^15 -1) Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer Default value is 0. Example − short s = 10000, short r = -20000 Java int Data Type Int data type is a 32-bit signed two”s complement integer. Minimum value is – 2,147,483,648 (-2^31) Maximum value is 2,147,483,647(inclusive) (2^31 -1) Integer is generally used as the default data type for integral values unless there is a concern about memory. The default value is 0 Example − int a = 100000, int b = -200000 Java long Data Type Long data type is a 64-bit signed two”s complement integer Minimum value is -9,223,372,036,854,775,808(-2^63) Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1) This type is used when a wider range than int is needed Default value is 0L Example − long a = 100000L, long b = -200000L Java float Data Type Float data type is a single-precision 32-bit IEEE 754 floating point Float is mainly used to save memory in large arrays of floating point numbers Default value is 0.0f Float data type is never used for precise values such as currency Example − float f1 = 234.5f Java double Data Type double data type is a double-precision 64-bit IEEE 754 floating point This data type is generally used as the default data type for decimal values, generally the default choice Double data type should never be used for precise values such as currency Default value is 0.0d Example − double d1 = 123.4 Java boolean Data Type boolean data type represents one bit of information There are only two possible values: true and false This data type is used for simple flags that track true/false conditions Default value is false Example − boolean one = true Java char Data Type char data type is a single 16-bit Unicode character Minimum value is ”u0000” (or 0) Maximum value is ”uffff” (or 65,535 inclusive) Char data type is used to store any character Example − char letterA = ”A” Example: Demonstrating Different Primitive Data Types Following examples shows the usage of variour primitive data types we”ve discussed above. We”ve used add operations on numeric data types whereas boolean and char variables are printed as such. public class JavaTester { public static void main(String args[]) { byte byteValue1 = 2; byte byteValue2 = 4; byte byteResult = (byte)(byteValue1 + byteValue2); System.out.println(“Byte: ” + byteResult); short shortValue1 = 2; short shortValue2 = 4; short shortResult = (short)(shortValue1 + shortValue2); System.out.println(“Short: ” + shortResult); int intValue1 = 2; int intValue2 = 4; int intResult = intValue1 + intValue2; System.out.println(“Int: ” + intResult); long longValue1 = 2L; long longValue2 = 4L; long longResult = longValue1 + longValue2; System.out.println(“Long: ” + longResult); float floatValue1 = 2.0f; float floatValue2 = 4.0f; float floatResult = floatValue1 + floatValue2; System.out.println(“Float: ” + floatResult); double doubleValue1 = 2.0; double doubleValue2 = 4.0; double doubleResult = doubleValue1 + doubleValue2; System.out.println(“Double: ” + doubleResult); boolean booleanValue = true; System.out.println(“Boolean: ” + booleanValue); char charValue = ”A”; System.out.println(“Char: ” + charValue); } } Output Byte: 6 Short: 6 Int: 6 Long: 6 Float: 6.0 Double: 6.0 Boolean: true Char: A Java Reference/Object Data Type The reference data types are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc. Class objects and various types of array variables come under reference datatype. The default value of any reference variable is null. A reference variable can be used to refer to any object of the declared type or any compatible type. Example The following example demonstrates the reference (or, object) data types. // Creating an object of ”Animal” class Animal animal = new Animal(“giraffe”); // Creating an object of ”String” class String myString = new String(“Hello, World!”); Print Page Previous Next Advertisements ”;
Category: Java
Java 8 Questions and Answers ”; Previous Next Java 8 Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Java 8 Interview Questions This section provides a huge collection of Java 8 Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Java 8 Online Quiz This section provides a great collection of Java 8 Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Java 8 Online Test If you are preparing to appear for a Java and Java 8 related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Java 8 Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;
Java – Discussion
Discuss Java ”; Previous Next Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding of Java. This reference will take you through simple and practical approaches while learning Java Programming language. Print Page Previous Next Advertisements ”;
Java – Vector
Java Vector Class ”; Previous Next Introduction Vector implements a dynamic array. It is similar to ArrayList, but with two differences − Vector is synchronized. Vector contains many legacy methods that are not part of the collections framework. Vector proves to be very useful if you don”t know the size of the array in advance or you just need one that can change sizes over the lifetime of a program. The java.util.Vector class implements a growable array of objects. Similar to an Array, it contains components that can be accessed using an integer index. Following are the important points about Vector − The size of a Vector can grow or shrink as needed to accommodate adding and removing items. Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface. Unlike the new collection implementations, Vector is synchronized. This class is a member of the Java Collections Framework. Class declaration Following is the declaration for java.util.Vector class − public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable Here <E> represents an Element, which could be any class. For example, if you”re building an array list of Integers then you”d initialize it as follows − ArrayList<Integer> list = new ArrayList<Integer>(); Class constructors Sr.No. Constructor & Description 1 Vector() This constructor is used to create an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. 2 Vector(Collection<? extends E> c) This constructor is used to create a vector containing the elements of the specified collection, in the order they are returned by the collection”s iterator. 3 Vector(int initialCapacity) This constructor is used to create an empty vector with the specified initial capacity and with its capacity increment equal to zero. 4 Vector(int initialCapacity, int capacityIncrement) This constructor is used to create an empty vector with the specified initial capacity and capacity increment. Class methods Sr.No. Method & Description 1 boolean add(E e) This method appends the specified element to the end of this Vector. 2 boolean addAll(Collection<? extends E> c) This method appends all of the elements in the specified Collection to the end of this Vector. 3 void addElement(E obj) This method adds the specified component to the end of this vector, increasing its size by one. 4 int capacity() This method returns the current capacity of this vector. 5 void clear() This method removes all of the elements from this vector. 6 Vector clone() This method returns a clone of this vector. 7 boolean contains(Object o) This method returns true if this vector contains the specified element. 8 boolean containsAll(Collection<?> c) This method returns true if this Vector contains all of the elements in the specified Collection. 9 void copyInto(Object[ ] anArray) This method copies the components of this vector into the specified array. 10 E elementAt(int index) This method returns the component at the specified index. 11 Enumeration<E> elements() This method returns an enumeration of the components of this vector. 12 void ensureCapacity(int minCapacity) This method increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument. 13 boolean equals(Object o) This method compares the specified Object with this Vector for equality. 14 E firstElement() This method returns the first component (the item at index 0) of this vector. 15 void forEach(Consumer<? super E> action) This method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. 16 E get(int index) This method returns the element at the specified position in this Vector. 17 int hashCode() This method returns the hash code value for this Vector. 18 int indexOf(Object o) This method returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element. 19 void insertElementAt(E obj, int index) This method inserts the specified object as a component in this vector at the specified index. 20 boolean isEmpty() This method tests if this vector has no components. 21 Iterator<E> iterator() This method returns an iterator over the elements in this list in proper sequence. 22 E lastElement() This method returns the last component of the vector. 23 int lastIndexOf(Object o) This method returns the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element. 24 ListIterator<E> listIterator() This method returns a list iterator over the elements in this list (in proper sequence). 25 E remove(int index) This method removes the element at the specified position in this Vector. 26 boolean removeAll(Collection<?> c) This method removes from this Vector all of its elements that are contained in the specified Collection. 27 void removeAllElements() This method removes all components from this vector and sets its size to zero. 28 boolean removeElement(Object obj) This method removes the first occurrence of the argument from this vector. 29 void removeElementAt(int index) This method deletes the component at the specified index. 30 boolean removeIf(Predicate<? super E> filter) Removes all of the elements of this collection that satisfy the given predicate. 31 boolean retainAll(Collection<?> c) This method retains only the elements in this Vector that are contained in the specified Collection. 32 E set(int index, E element) This method replaces the element at the specified position in this Vector with the specified element. 33 void setElementAt(E obj, int index) This method sets the component at the specified index of this vector to be the specified object. 34 void setSize(int newSize) This method sets the size of this vector. 35 int size() This method returns the number of components in this vector. 36 Spliterator<E> spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this list. 37 List <E> subList(int fromIndex, int toIndex) This method returns a view of the portion
Java – Properties
Java Properties Class ”; Previous Next Introduction The Java Properties class is a class which represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Following are the important points about Properties − Each key and its corresponding value in the property list is a string. A property list can contain another property list as its ”defaults”, this second property list is searched if the property key is not found in the original property list. This class is thread-safe; multiple threads can share a single Properties object without the need for external synchronization. Class declaration Following is the declaration for java.util.Properties class − public class Properties extends Hashtable<Object,Object> Field Following are the fields for java.util.Properties class − protected Properties defaults − This is the property list that contains default values for any keys not found in this property list. Class constructors Sr.No. Constructor & Description 1 Properties() This constructs creates an empty property list with no default values. 2 Properties(int initialCapacity) This constructs creates an empty property list with no default values, and with an initial size accommodating the specified number of elements without the need to dynamically resize. 3 Properties(Properties defaults) This constructs creates an empty property list with the specified defaults. Class methods Sr.No. Method & Description 1 String getProperty(String key) This method searches for the property with the specified key in this property list. 2 void list(PrintStream out) This method prints this property list out to the specified output stream. 3 void load(InputStream inStream) This method reads a property list (key and element pairs) from the input byte stream. 4 void loadFromXML(InputStream in) This method loads all of the properties represented by the XML document on the specified input stream into this properties table. 5 Enumeration<?> propertyNames() This method returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list. 6 Object setProperty(String key, String value) This method calls the Hashtable method put. 7 void store(OutputStream out, String comments) The method writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method. 8 void storeToXML(OutputStream os, String comment) This method emits an XML document representing all of the properties contained in this table. 9 Set<String> stringPropertyNames() This method returns a set of keys in this property list where the key and its corresponding value are strings, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list. Methods inherited This class inherits methods from the following classes − java.util.Hashtable java.util.Object Getting an Enumeration of Properties Keys Example The following example shows the usage of java.util.Properties.propertyNames() method. package com.tutorialspoint; import java.util.Enumeration; import java.util.Properties; public class PropertiesDemo { public static void main(String[] args) { Properties prop = new Properties(); // add some properties prop.put(“Height”, “200”); prop.put(“Width”, “15”); // assign the property names in a enumaration Enumeration<?> enumeration = prop.propertyNames(); // print the enumaration elements while(enumeration.hasMoreElements()) { System.out.println(“” + enumeration.nextElement()); } } } Output Let us compile and run the above program, this will produce the following result − Width Height Print Page Previous Next Advertisements ”;
Java – LinkedHashSet
Java LinkedHashSet Class ”; Previous Next Introduction The Java LinkedHashSet class is a Hash table and Linked list implementation of the Set interface, with predictable iteration order.Following are the important points about LinkedHashSet − This class provides all of the optional Set operations, and permits null elements. Class declaration Following is the declaration for java.util.LinkedHashSet class − public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable Parameters Following is the parameter for java.util.LinkedHashSet class − E − This is the type of elements maintained by this set. Class constructors Sr.No. Constructor & Description 1 LinkedHashSet() This constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75). 2 LinkedHashSet(Collection<? extends E> c) This constructs a new linked hash set with the same elements as the specified collection. 3 LinkedHashSet(int initialCapacity) This constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75). 4 LinkedHashSet(int initialCapacity, float loadFactor) This constructs a new, empty linked hash set with the specified initial capacity and load factor. Class methods Sr.No. Method & Description 1 Spliterator<E> spliterator() This method returns a late-binding and fail-fast Spliterator over the elements in this set. This class inherits methods from the following classes − java.util.HashSet java.util.AbstractSet java.util.AbstractCollection java.util.Object java.util.Set Getting a Spliterator() to Iterate Entries of LinkedHashSet Example The following example shows the usage of Java LinkedHashSet spliterator() method to iterate entries of the LinkedHashSet. We”ve created a LinkedHashSet object of Integer. Then few entries are added using add() method and then an spliterator is retrieved using spliterator() method and each value is printed by iterating through the spliterator. package com.tutorialspoint; import java.util.LinkedHashSet; import java.util.Spliterator; public class LinkedHashSetDemo { public static void main(String args[]) { // create hash set LinkedHashSet <Integer> newset = new LinkedHashSet <>(); // populate hash set newset.add(1); newset.add(2); newset.add(3); // create an spliterator Spliterator<Integer> spliterator = newset.spliterator(); // check values spliterator.forEachRemaining(v -> System.out.println(v)); } } Let us compile and run the above program, this will produce the following result. 1 2 3 Print Page Previous Next Advertisements ”;
Servlets Tutorial
Servlets Tutorial PDF Version Quick Guide Resources Job Search Discussion Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. Why to Learn Servlet? Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI. Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. Applications of Servlet Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. Audience This tutorial is designed for Java programmers with a need to understand the Java Servlets framework and its APIs. After completing this tutorial you will find yourself at a moderate level of expertise in using Java Servlets from where you can take yourself to next levels. Prerequisites We assume you have good understanding of the Java programming language. It will be great if you have a basic understanding of web application and how internet works. Print Page Previous Next Advertisements ”;
Java 14 – New Features
Java 14 – New Features ”; Previous Next Java 14 is a major feature release and it has brought many JVM specific changes and language specific changes to JAVA. It followed the Java release cadence introduced Java 10 onwards and it was releasd on 17 Mar 2020, just six months after Java 13 release. Java 14 is a non-LTS release. New Features in Java 14 Following are the major new features which are introduced in Java 14. JEP 361 − Switch Expressions − Now a standard feature allowing switch to use return values via yield. JEP 368 − Text Blocks − A second preview feature to handle multiline strings like JSON, XML easily. JEP 305 − Pattern matching for instanceOf − instanceOf operator enhanced to carry a predicate. JEP 358 − NullPointerException message − NullPointerException now can send detailed message. JEP 359 − Records − A preview feature introducing a new type record. JEP 343 − Packaging Tool − New packager based on javapackager introduced. JEP 345 − NUMA aware G1 − G1 garbage collector is now NUMA aware. JEP 349 − JFR Event Streaming − The package jdk.jfr.consumer, in module jdk.jfr, is enhanced to subscribe to events asynchronously. JEP 352 − Non-Volatile Mapped Byte Buffers − New File mapping modes added to refer to Non-Volatile Memory, NVM. JEP 363 − CMS Garbage Collector Removed − Concurrent Mark Sweep (CMS) Garbage Collector deprecated in Java 9 is removed. JEP 347 − Pack200 Tools and API Removed − pack200 and unpack200 tools, and the Pack200 API from java.util.jar are removed. JEP 370 − Foreign-Memory Access API − A new API to access foreign memory outside of heap space. Deprecation & Removals The following are the list of Deprecation and Removals in Java 14 − Deprecations Solaris and SPARC Ports (JEP 362) − because this Unix operating system and RISC processor are not in active development since the past few years. ParallelScavenge + SerialOld GC Combination (JEP 366) − since this is a rarely used combination of GC algorithms, and requires significant maintenance effort Removals Concurrent Mark Sweep (CMS) Garbage Collector (JEP 363) − This GC was deprecated in Java 9 and is replaced with G1 as default GC. There are other high performant alternatives as well like ZDC, Shenandoah. This GC was kept for 2 years for interested users to maintain. As there is no active maintenance, this GC is now completed removed from Java 14. Pack200 Tools and API (JEP 367) − These compression libraries were introduced in Java 5 and were deprecated in Java 11. Now these libraries are completely removed from Java 14. Print Page Previous Next Advertisements ”;
Java – Useful Resources
Java – Useful Resources ”; Previous Next The following resources contain additional information on Java. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Java Programming Course For Beginners Best Seller 146 Lectures 16.5 hours Karthikeya T More Detail Advanced Java Using Eclipse IDE: Learn JavaFX & Databases Most Popular 34 Lectures 7.5 hours Syed Raza More Detail Java Made Easy for Beginners, Testers, Selenium and Appium 249 Lectures 62 hours Arun Motoori More Detail Java SE 11 Programming: For Beginners Most Popular 123 Lectures 8.5 hours Lemuel Ogbunude More Detail Core Java Bootcamp Program With Hands-On Practice Featured 99 Lectures 17 hours Selfcode Academy More Detail Learn Java Programming For Beginners Featured 24 Lectures 5.5 hours Quaatso Learning More Detail Print Page Previous Next Advertisements ”;
Java – HashSet
Java HashSet Class ”; Previous Next Introduction The Java HashSet class implements the Set interface, backed by a hash table.Following are the important points about HashSet − This class makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. Class declaration Following is the declaration for java.util.HashSet class − public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable Parameters Following is the parameter for java.util.HashSet class − E − This is the type of elements maintained by this set. Class constructors Sr.No. Constructor & Description 1 HashSet() This constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75). 2 HashSet(Collection<? extends E> c) This constructs a new set containing the elements in the specified collection. 3 HashSet(int initialCapacity) This constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75). 4 HashSet(int initialCapacity, float loadFactor) This constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor. Class methods Sr.No. Method & Description 1 boolean add(E e) This method adds the specified element to this set if it is not already present. 2 void clear() This method removes all of the elements from this set. 3 Object clone() This method returns a shallow copy of this HashSet instance, the elements themselves are not cloned. 4 boolean contains(Object o) This method returns true if this set contains the specified element. 5 boolean isEmpty() This method returns true if this set contains no elements. 6 Iterator<E> iterator() This method returns an iterator over the elements in this set. 7 boolean remove(Object o) This method removes the specified element from this set if it is present. 8 int size() This method returns returns the number of elements in this set(its cardinality). 9 Spliterator<E> spliterator() This method returns a late-binding and fail-fast Spliterator over the elements in this set. Methods inherited This class inherits methods from the following classes − java.util.AbstractSet java.util.AbstractCollection java.util.Object java.util.Set Adding element to a HashSet Example The following example shows the usage of Java HashSet add() method to add entries to the HashSet. We”ve created a HashSet object of Integer. Then few entries are added using add() method and then set is printed. package com.tutorialspoint; import java.util.HashSet; public class HashSetDemo { public static void main(String args[]) { // create hash set HashSet <Integer> newset = new HashSet <>(); // populate hash set newset.add(1); newset.add(2); newset.add(3); // checking elements in hash set System.out.println(“Hash set values: “+ newset); } } Output Let us compile and run the above program, this will produce the following result. Hash set values: [1, 2, 3] Print Page Previous Next Advertisements ”;