Keywords cannot be used as identifiers (names) for classes, methods, variables or anything else in your code. All keywords start with a lower case.
Access Modifiers |
|
private | Makes a method or a variable accessible only from within its own class |
protected | Makes a method or a variable accessible only to classes in the same package or subclass of the class |
public | Makes a class, method or variable accessible from any other class |
Class, Method and Variable Modifiers |
|
abstract | Used to declare a class that cannot be instantiated or a method that must be implemented by a nonabstract subclass |
class | Used to specify a class |
extends | Used to indicate the superclass that a subclass is extending |
final | Makes it impossible to extend a class, override a method or reinitialize a variable |
implements | Used to indicate the interfaces that a class will implement |
interface | Used to specify a interface |
native | Indicates a method is written in a platform-dependent language such as C |
new | Used to instantiate an object by invoking the constructor |
static | Makes a method or a variable belong to a class as opposed to an instance |
strictfp | Used in front of a method or class to indicate that floating-point numbers will follow FP-strict rules in all expressions |
synchronized | Indicates that a method can be accessed by only one thread at a time |
transient | Prevents fields from ever being serialized. Transient fields are always skipped when objects are serialized |
volatile | Indicates a variable may change out of sync because it is used in threads |
Flow Control |
|
break | Exits from the block of code in which it resides |
case | Executes a block of code, dependent on what the switch tests for |
continue | Stops the rest of the code within the block from executing in a loop and then begins the next iteration of the loop |
default | Executes this block of code if none of the switch-case statement match |
do | Executes a block of code one time, then, in conjunction with the while statement, it performs a test to determine whether the block should be executed again |
else | Executes an alternate block of code if an if test is false |
for | Used to perform a conditional loop for a block of code |
if | Used to perform a logical test for true or false |
instanceof | Determines whether an object is an instance of a class, superclass or interface |
return | Returns from a method without executing any code that follows the statement (can optionally return a variable) |
switch | Indicates the variable to be compared with the case statement |
while | Executes a block of code repeatedly while a certain condition is true |
Error Handling |
|
catch | Declares the block of code used to handle an exception |
finally | Block of code usually following a try-catch statement, which is executed no matter what program flow occurs when dealing with an execption |
throw | Used to pass an exception up to the method that called this method |
throws | Indicates the method will pass an exception to the method that called it |
try | Block of code that will be tried, but which may cause an exception |
assert | Evaluates a conditional expression to verify the programmers assumption |
Package Control |
|
import | Statement to import packages or classes into code |
package | Specifies to which package all classes in a source file belong |
Variable Keywords |
|
super | Reference variable referring to the immediate superclass |
this | Reference variable referring to the current instance of an object |
Void Return Type |
|
void | Indicates no return type for a method |
Unused Reserved Words |
|
const | Do not use to declare a constant; use public static final |
goto | Not implemented in the Java language, its bad. |
Java has a number of primitive data types, these are portable across all computer platforms that support Java. Primitive data types are special data types built into the Java language, they are not objects created from a class. Object type String is often thought as a primitive data type but it is an Object.
Java defines eight primitive data types, these are commonly knows as the simple types, they are put into four groups
All Java's six number types are signed which means they can be positive or negative. Always append a f when you want a floating-point number otherwise it will be a double.
Data Type | Value |
boolean | A value indicating true or false |
byte | An 8-bit integer (signed) |
char | A single unicode character (16-bit unsigned) |
double | A 64-bit floating-point number (signed) |
float | A 32-bit floating-point number (signed) |
int | A 32-bit integer (signed) |
long | A 64-bit integer (signed) |
short | A 16-bit integer (signed) |
Each data type uses memory and has a defined minimum and maximum range, it also have a default value when initialized, which is described in the table below:
Type | Size in Bits |
Size in Bytes |
Default value |
Minimum Range |
Maximum Range |
boolean | 8 |
1 |
false |
n/a |
n/a |
char | 16 |
2 |
'\u0000' |
0 |
65,536 |
byte | 8 |
1 |
0 |
-128 |
127 |
short | 16 |
2 |
0 |
-32,768 |
32,767 |
int | 32 |
4 |
0 |
-2,147,483,648 |
2,147,483,647 |
long | 64 |
8 |
0L |
-9,223,372,036,854,775,808 |
9,223,372,036,854,775,807 |
float | 32 |
4 |
0.0f |
1.4e-045 |
3.4e+38 |
double | 64 |
8 |
0.0d |
4.9e-324 |
1.8e+308 |
You can also use binary, octal and Hexadecimal values, you can also convert a string into a binary, octal or hexadecimal values, which you can add, together, etc.
Binary/Hexadecimal/Octal Example | public class exercise19 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter number one: "); Integer number1 = in.nextInt(); System.out.println("Binary equivalent: " + Integer.toBinaryString(number1)); System.out.println("Hexadecimal equivalent: " + Integer.toHexString(number1)); System.out.println("Octal equivalent: " + Integer.toOctalString(number1)); } } |
Binary example | public class exercise17 { // private static final int bin1 = 0b10; // private static final int bin2 = 0b11; public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter first binary number: "); int bin1 = Integer.valueOf(in.nextLine(), 2); System.out.println("Enter second binary number: "); int bin2 = Integer.valueOf(in.nextLine(), 2); System.out.println("Sum: " + Integer.toBinaryString(bin1 + bin2)); } } |
Hexadecimal example | public class exercise17a { // private static final int hex1 = 0x0A; // private static final int hex2 = 0X01; public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter first binary number: "); int hex1 = Integer.valueOf(in.nextLine(), 16); System.out.println("Enter second binary number: "); int hex2 = Integer.valueOf(in.nextLine(), 16); System.out.println("Sum: " + Integer.toHexString(hex1 + hex2)); } } |
When you declare a variable you must use the data type and the name (which must be a valid identifier), you can declare multiple variables on a single line if they are the same data type. Java is a strongly typed programming language which means that every variable must be known at compile time, this identifies any errors in the code when compiling, there are two types of variables primitive or reference (pointer to an object).
A variable is just a storage location and has the following naming constraints
There are two types of variable in Java
Instance Variable | Declared within the class but outside any method, constructor or any other initializer block |
Local Variable | Declared within a method (or argument list of a method) |
Instance/Local | Variable Type | Action |
Instance | Primitive | Will be initialized with its default value (see Java Primitive Data types above for default values) |
Instance | Object | Will be initialized with null |
Instance | Array | Not Initialized - will have value null If Initialized - will be given default values |
Local | Primitive | All primitive must be initialized otherwise you will get a compiler error |
Local | Object | All object type be initialized otherwise you will get a compiler error, you can initialize a object with null to stop the compiler complaining String name = null; |
Local | Array | Not Initialized - will have value null If Initialized - will be given default values |
A quick example to explain the table above
Example | public class varTest { class test { Note: when you try to compile this, the compiler will error stating that method_count might not have been initialized, remember that you should initialize memember variables |
Here are some quick examples of using variables and primitive data types
boolean example | boolean t = true; boolean p = false; boolean q = 0; // Compiler error |
char example | char a = 'a'; |
byte example | byte b = 0x41; // display 65 byte c = 4; // display 4 |
short example | short a = 10; short b = 107; |
int example | int a = 1; int b = 10; int c = 10,000; // ERROR: because of the comma |
long example | long l1 = 110599L; long l2 = 0xFFFFl; // Note the lower case l |
float example | float f1 = 23.467890; // ERROR: Compiler error loss of precision float f1 = 23.467890F; // Note the suffix F at the end |
double example | double d1 = 987.987D; double d1 = 987.987; // OK, because the literal is a double |
Bad Examples | byte b8 = 0b_00000001; // Cannot have underscore directly after 0b |
String to ASCII example | public class exercise41 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a letter: "); char letter = in.next().charAt(0); System.out.println("Ascii number: " + (int) letter); System.out.println("Enter a String: "); char[] ca = in.next().toCharArray(); System.out.println("String converted into Ascii"); for (char c : ca) { System.out.print( (int) c + " "); } System.out.println(); String input = "Hello World"; byte[] bytes = input.getBytes(StandardCharsets.US_ASCII); System.out.println("Another way: "); for (byte b : bytes) { System.out.print((int) b + " "); } } } |
Java will allow you to narrow or widen variables in specific circumstances, also be careful of using signed and unsigned variables
Narrowing - Compiler errors due to not fitting thus data lost | byte b1 = 128; |
Widening - all ok due to fitting into the wider variable | int i1 = 10; |
Casting allows you to tell the compiler that you know what you are doing in regard to narrowing or widening, generally it's more commonly used when narrowing as data loss may occur for example casting a float variable to a int will cause a loss of data (decimal part). Normally try not to use a cast because you are implying that you know of risks.
Also note that if you cast it can cause a overflow or a underflow
Casting Examples | int a = 100; float a = 100.001f; Note: with explicit casting you let the compiler know that you know that you may loose info |
When casting primitive data types you can use the below:
Wrapper classes serve two primary purposes
There is a wrapper class for every primitive, the one for int is Integer, for float is Float and so on. below is a table detailing the wrapper classes and their constructor arguments
Primitive | Wrapper Class | Constructor Arguments |
boolean | Boolean | boolean or String |
byte | Byte | byte or String |
char | Character | char |
double | Double | double or String |
float | Float | float, double or String |
int | Integer | int or String |
long | Long | long or String |
short | Short | short or String |
A note before I show some examples is that wrapper classes are immutable, thus they cannot be changed, also a Boolean object can't be used like a boolean primitive.
Creating | Integer i1 = new Integer(42); Integer i2 = new Integer("42"); Character c1 = new Character('c'); |
Creating using valueOf() method | Integer i3 = Integer.valueOf("101011", 2); // converts 101011 to 43 Float f2 = Float.valueOf("3.14f"); // assign 3.14 to Float object f2 |
Creating using parseXXX() method | String s1 = "42"; int i1 = Integer.parseInt(s1); // converts the String to a int primitive |
Using Wrappers | String num1 = "42"; System.out.println("Total: " + (num1 + num2)); // results in 4258 not what we was hoping for Integer i1 = new Integer(num1); // convert the String value into a primitive value System.out.println("Total: " + (i1 + i2)); // results in 100 what we wanted System.out.println("Total: " + (Integer.parseInt(num1) + Integer.parseInt(num2))); // another way |
Using toString() | String num1 = "42"; Integer i1 = new Integer(num1); System.out.println("toString reports: " + i1.toString()); // now print out a String |
Each class has many methods for data integrity, for example the Character class has the following methods: isDefined, isDigit, isLowerCase, isUpperCase and so on.
Lastly regarding wrappers is to mention boxing and unboxing. Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
There are a few rules rearding boxing, the Java compiler applies autoboxing when a primitive value is:
and unboxing rules, the Java compiler applies unboxing when an object of a wrapper class is
Boxing and Unboxing example | public class Test { static int a = 5; static Integer A = 10; public static void main(String[] args) { boxing(a); // passing a int which will boxed into a Integer unboxing(A); // passing a Integer which will be unboxed into a int } static void boxing(Integer a) { System.out.println("Boxing: " + a); } static void unboxing(int a) { System.out.println("Unboxing: " + a); } } |
Identify the scope of variable
Scope is the region of a program a variable is visable and thus be used, there are several scopes
Scope | Qualifier |
Class | {DefinedClassType} |
Instance | this |
Method | none |
Loop Block | none |
Block including exception block | none |
Scope | Qualifier |
Some scope examples
Basic scope | public class Person { static String name = "UNKNOWN"; // Class Variable String instanceName = "UNKNOWN"; // Instance Variable; String age = "25"; // Instance Variable initialized; // Single Parameter Constructor. public Person(String age) { // Constructors are perfect examples of how a method parameter // name can have same name as class or instance variable name. // In this constructor, the Person instance age does not get // set at all, because age not qualified by 'this'. // This is a common mistake and may be tested on exam age = age; } // Two Args Constructor public Person(String name, String age) { // constructor parameters are named and typed the same as the // class variable 'name' and the instance variable 'age' // Correctly setting object's age using 'this' qualifier this.age = age; // instanceName is an instance variable and has different // name from the parameter which will be assigned to it, so // this not required, but good practice to use it // Also setting static variable name in same assignment // statement this.instanceName = Person.name = name; } // Simple setter for age public void setAge(String age) { // method sets instance variable age to the parameter passed. this.age = age; } // Simple setter for instanceName public void setInstanceName(String instanceName) { this.instanceName = instanceName; } // Simple get decade to explain loop scope public String getDecade(int age) { // a method local variable String decadeString = ""; // A method local variable int decadeNumver = age/10; // A method local variable int j = 0; for (int i = j = 0; i < (decadeNumber + 1); i++, j++) { // local loop block variable named decade, scope is loop String decade = "Decade " + (age / 10); // i variable is local to the loop if (i == (decadeNumber)) { decadeString = decade; } } int modyear = age % 10; decadeString += ", Year " + modyear; return decadeString; } } |
Nested Classes and scope | public class NestedScope { public static void main(String[] args) { // local variable i declared and initialized int i = 10; class locallyDefinedClass { { // i from method scope still visible in nested local class System.out.println("value of i BEFORE LOOP " + i); System.out.println("---------------"); // Because this for loop is within a local class,this is valid for (int i = 0; i< 5; i++) { System.out.println("value of i during FIRST loop " + i); } System.out.println("---------------"); // the local variable i from previous loop has gone out of scope // so it is ok to create another local variable in the second loop // declaration of the same name. for (int i = 5; i > 0; i--) { System.out.println("value of i during SECOND loop " + i); } System.out.println("---------------"); // assign local loop variable j to local variable i from the // surrounding method of the nested class, for (int j = i; j < 15; j++) { System.out.println("value of i,j during THIRD loop " + i + "," + j); } System.out.println("value of i AFTER LOOP " + i); } } System.out.println("value of i before local class instantiated " + i); new locallyDefinedClass(); System.out.println("value of i after local class instantiated " + i); } } |
Use local variable type inference
There is a new feature called Local Variable Type Inference (LVTI) from Java 10 onwards that allows you to reduce the verbosity of the code, you can only use it for local variables inside a method body, note that var is not a data type. Note that var itself is not a keyword and can be used for class names and var names.
You cannot use LVTI for the following:
When and when not to use vars | public class VarTest { public static void main(String[] args) { var p1 = new Person(); p1.setName("Paul"); System.out.println(p1); // Adding some other var declarations: // i is inferred to be an int, since it's assigned a literal int var i = 1; // An array can be assigned to an LVTI variable var aVarArray = new int[3]; // Valid to assign a method return value to an LVTI variable var methodVal = p1.getName(); // OK to assign a null object to LVTI variable but not literal null // Note that i am using var as a variable name which is valid Object nullObject = null; var var = nullObject; // Invalid var declarations: // // cannot use var declaration in a compound statement // var j = 0, k = 0; // // // again, cannot use var declaration in a compound statement // var m, n = 0; // // // Cannot declare a var variable without also initializing it // var someObject; // // // Cannot assign null to var variable, type cannot be inferred // var newvar = null; // // // Cannot use array initializer in var declaration/initialization // var myArray = {"A", "B"}; // // // Cannot have an array of var // var[]newarray = new int[2]; } } |
Array Declaration, Construction and Initialization
Arrays are objects in Java that store multiple variables of the same data type. Arrays can hold either primitive data types or object references, but the array itself will always be an object type. Multidimensional arrays are just arrays of arrays, the dimensions in a multidimensional array can have different lengths. An array of primitives can accept any value that can be promoted implicity to the declared type of the array (byte can go into a int array). An array of objects can hold any object that passes the IS-A (instanceof) test for the declared type.
Declaring an Array | Arrays are declared by stating the type of element the array will hold, which can be a primitive or an object. The array will not be determined at this point and the compiler will throw an error if you do. |
Constructing an Array | Constructing an array means creating the array object on the heap - in other words, doing a new on the array type, at this point you determine the size of the array so that the space can be allocated on the heap. Primitive arrays are given default values when created unless otherwise specified (see above for default values). |
Initializing an Array | Initializing an means putting things into it. if you have an array of objects, the array does not hold the object but holds a reference to the objects. The default value of an element of an array which has a type of object is null, so becareful if you try to use this element otherwise you get a nullpointerexception error. To access an element within the array you start from 0, if you get an ArrayIndexOutOfBoundsException it means that you are trying to access an element that does not exist (not within range). |
The position number in square brackets is more formally called a subscript (index), a subscript must be an integer or an integer expression. You cannot change the size of an array once constructed, however there are other list types that can be grown or shrunk see Collections for more details.
Array Examples |
|
Declaring an Array Example | int[] array1; // Square brackets before variable name (recommended) String [][][] occupantName; // 3 dimensional array int[5] array1; // ERROR: You cannot include the size of an array, the compiler will complain |
Constructing an Array Example | int[] array1; // Declare the array of ints Note: the array will now be on the heap with each element set to 0 (default) # Declare an array in one statement # Will not compile # Multidimension arrays |
Initializing an Array Example | # Setting values for sepcific elements within the array # Initializing a multidimensional array |
Declaring, Constructing and Initializing on one line | # 4 element array of type int # Multidimensional array # Object array |
Anonymous Array | # A second short cut is called an anonymous array, below creates a 3 element array of type int. |
Simple arrays | public class Array1 { Note: arrays have a length variable that contains the number of elements. |
multi-dimensional array examples | class arrayTest { public static void main(String[] args) { int array1[][] = { {1,2,3}, {4,5,6} }; int array2[][] = { {1,2}, {3}, {4,5,6} }; buildOutput(array1); System.out.println(); buildOutput(array2); } public static void buildOutput ( int a[][] ) { for ( int i = 0; i < a.length; i++ ) { for ( int j = 0; j < a[i].length; j++) System.out.print(a[i][j] + " "); System.out.println(); } } } |
Passing arrays to methods | class arrayTest { public static void main(String[] args) { int a[] = { 1, 2, 3, 4, 5, 6 }; System.out.print("Orginal array values: "); for (int i = 0; i < a.length; i++) System.out.print( a[i] + " "); System.out.println(); // array is passed to by-reference modifyArray(a); System.out.print("Now changed to: "); for (int i = 0; i < a.length; i++) System.out.print( a[i] + " "); System.out.println("\n\nElement a[3] is now: " + a[3]); // array elements are passed by-value; modifyElement (a[3]); System.out.println("Element a[3] has been changed to: " + a[3]); } // whole array are passed by-reference public static void modifyArray (int b[]) { for (int j = 0; j < b.length; j++) b[j] *= 2; } // array elements are passed by-value public static void modifyElement (int e) { e *=2; } } |
Combining arrays | int[] array1 = {1, 2, 3, 4}; int[] array2 = {2, 5, 7, 8}; int aLen = array1.length; int bLen = array2.length; int[] result = new int[aLen + bLen]; System.arraycopy(array1, 0, result, 0, aLen); System.arraycopy(array2, 0, result, aLen, bLen); Arrays.stream(result).sorted().forEach(p -> System.out.print(p + " ")); |
To manipulate Arrays in Java we can use the utility class java.util.Arrays (sorting, searching, etc), ArrayList's are alternate methods for manipulating collections of data.
Type of Functionality | Arrays Class methods | List Interface methods |
Comparison | compare (Java 9) compareUnsigned (Java 9) deepEquals equals |
equals isEmpty |
Searches | binarySearch misMatch (Java 9) |
contains containsAll indexOf lastIndexOf |
Data Manipulation | deepHashCode deepToString fill hashCode parallelPrefix (Java 8) parallelSort (Java 8) parallelSetAll (Java 8) setAll (Java 8) sort toString |
add addAll clear get hashCode remove removeAll replaceAll retainAll set size sort |
Data Transformation | asList copyOf copyOfRange spliterator (java 8) stream (Java 8) |
copyOf (Java 10) iterator listIterator of (Java 9) spliterator (Java 9) subList toArray |
Some examples of the above are below, use the Java documentation or have a play around to get more familiar with these methods
Comparison Examples | String[] names1 = {"Will", "Graham", "Moore", "Arthur", "Norman"}; String[] names2 = {"Will", "Graham", "Moore", "Arthur", "Norman"}; String[] names3 = {"Will", "Graham", "Moore", "Arthur"}; String[] names4 = names1; String[] names5 = {}; // Equals checks if the arrays are the same (same reference) System.out.println(names1.equals(names2)); // contents are the same but they are different arrays System.out.println(names1.equals(names3)); // both contents and arrays are different System.out.println(names1.equals(names4)); // Arrays.compare checks the contents of the arrays, it does not care if they are not the same array (same reference) System.out.println(Arrays.compare(names1, names2)); // only checks that the contents are the same System.out.println(Arrays.compare(names1, names3)); // contents are not the same System.out.println(Arrays.compare(names1, names4)); // contents are the same // We have to convert to a list before we can use the List.isEmpty method System.out.println(Arrays.asList(names1).isEmpty()); System.out.println(Arrays.asList(names5).isEmpty()); // the array has to be empty not NULL |
Searching Examples | int[] numbers1 = {0, 1, 2, 3, 4, 5, 6}; // sorted array int[] numbers2 = {6, 3, 2, 1, 5, 0, 4}; // unsorted array String[] names1 = {"Will", "Graham", "Moore", "Arthur", "Norman"}; String[] names2 = {"Will", "Graham", "Moore", "Arthur", "Norman"}; System.out.println(Arrays.binarySearch(numbers1, 3)); // display the index where the pattern matched System.out.println(Arrays.binarySearch(numbers2, 3)); // arrays must be sorted for the binarySearch to work, this display -7 Arrays.sort(names1); System.out.println(Arrays.toString(names1)); // list is now in sorted order System.out.println(Arrays.binarySearch(names1, "Arthur")); // the array MUST be sorted System.out.println(Arrays.asList(names2).contains("Moore")); // a LIST is a ordered collection (ordering is as they were entered) of objects that contain duplicates System.out.println(Arrays.asList(names2).indexOf("Norman")); System.out.println(Arrays.toString(names2)); |
Data Manipulation Examples | int[] numbers1 = {0, 1, 2, 3, 4, 5, 6}; // sorted array String[] names1 = {"Will", "Graham", "Moore", "Arthur", "Norman"}; Arrays.fill(numbers1, 0); System.out.println(Arrays.toString(numbers1)); Arrays.setAll(numbers1, p -> p = 1); // you could have complex lambda (operator) here System.out.println(Arrays.toString(numbers1)); // You can use some of the List methods as well System.out.println(Arrays.asList(names1).size()); System.out.println(Arrays.asList(names1).get(1)); Arrays.asList(names1).replaceAll(p -> p = "Paul"); // this updates the array using the List interface System.out.println(Arrays.toString(names1)); |
Data Transformation Examples | int[] numbers1 = {0, 1, 2, 3, 4, 5, 6}; // sorted array String[] names1 = {"Will", "Graham", "Moore", "Arthur", "Norman"}; int[] numbers2 = Arrays.copyOf(numbers1, numbers1.length); // returns the copied number of elements System.out.println(Arrays.toString(numbers2)); int[] numbers3 = Arrays.copyOf(numbers1, 3); // you can just copy a subset of the array System.out.println(Arrays.toString(numbers3)); System.out.println(Arrays.asList(names1).subList(1, 3).toString()); // this returns a List, from index, to index (excluding), notice we did not pickup Arthur at index 3 |
Here are some examples of converting different types of arrays (int, String), I have provided examples on using Streams and Collections as well.
Converting int arrays (and double) | public class converting_int_array_to_list { public static void main(String[] args) { int[] intArray = {0, 1, 2, 3, 4, 5, 6}; System.out.println("Converting int array to List"); System.out.println("================================================================"); // convert int array to List using for loop List<Integer> list1 = new ArrayList<>(intArray.length); for(int i : intArray) { list1.add(i); } System.out.println("List1 (for loop): " + list1); // convert int array to List (Streams) List<Integer> list2 = Arrays.stream(intArray).boxed().collect(Collectors.toList()); System.out.println("List2 (Streams): " + list2); // convert int array to List (Collections) List<Integer> list3 = new ArrayList<>(); Collections.addAll(list3, Arrays.stream(intArray).boxed().toArray(Integer[]::new)); System.out.println("List3 (Collections): " + list3); // convert int array to List (IntStream) List<Integer> list4 = IntStream.of(intArray).boxed().collect(Collectors.toList()); System.out.println("List4 (IntStream): " + list4); // yo can use the same for double, float, etc double[] doubleArray = {0.1, 0.2, 0.3, 0.4, 0.5}; List<Double> list5 = Arrays.stream(doubleArray).boxed().collect(Collectors.toList()); System.out.println("List5 (convert double): " + list5); } } |
Converting String arrays | public class converting_string_array_list { public static void main(String[] args) { String[] stringArray = {"Paul", "Will", "Moore", "Graham", "Arthur"}; // convert String array to List using for loop List<String> list1 = new ArrayList<>(stringArray.length); for(String s : stringArray) { list1.add(s); } System.out.println("List1 (for loop): " + list1); // convert String array to List using Arrays.asList List<String> list2 = Arrays.asList(stringArray); System.out.println("List2 (asList) : " + list2); // convert String array to List (Streams) List<String> list3 = Arrays.stream(stringArray).collect(Collectors.toList()); System.out.println("List3 (Streams): " + list3); // convert String array to List (Collections) List<String> list4 = new ArrayList<>(); Collections.addAll(list4, stringArray); System.out.println("List4 (Collections): " + list4); // convert String array to List (new ArrayList) List<String> list5 = new ArrayList<>(Arrays.asList(stringArray)); System.out.println("List5 (new array): " + list5); } } |