package org.kodejava.util;
import java.util.Arrays;
import java.util.List;
public class ArrayToListExample {
public static void main(String[] args) {
// Creates an array of object, in this case we create an
// Integer array.
Integer[] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
// Convert the created array above to collection, in this
// example we convert it to a List.
List<Integer> list = Arrays.asList(numbers);
// We've got a list of our array here and iterate it.
for (Integer number : list) {
System.out.print(number + ", ");
}
}
}
Category Archives: Java
How do I convert collection to ArrayList?
package org.kodejava.util;
import java.util.ArrayList;
import java.util.LinkedList;
public class CollectionToArrayList {
public static void main(String[] args) {
// We create LinkedList collection type at put some values
// in it. Here we put A, B, C and D letter into it.
LinkedList<String> linkedList = new LinkedList<>();
linkedList.push("A");
linkedList.push("B");
linkedList.push("C");
linkedList.push("D");
// Let say you want to convert it to other type of collection,
// for instance here we convert it into ArrayList. To do it
// we can pass the collection created above as a parameter to
// ArrayList constructor.
ArrayList<String> arrayList = new ArrayList<>(linkedList);
// Now we have converted the collection into ArrayList and
// printed what is inside.
for (String s : arrayList) {
System.out.println("s = " + s);
}
}
}
How do I get number of days in a month?
Let say you want to know the number of days in a month, or we can say it as the last date of a month. The example below shows you how to obtain the number of days or the date.
package org.kodejava.util;
import java.util.Calendar;
public class MonthDaysExample {
public static void main(String[] args) {
// First get an instance of calendar object.
Calendar calendar = Calendar.getInstance();
// We'll set the date of the calendar to the following
// date. We can use constant variable in the calendar
// for months value (JANUARY - DECEMBER). Be informed that
// month in Java started from 0 instead of 1.
int year = 2021;
int month = Calendar.FEBRUARY;
int date = 1;
// We have a new date of 2021-02-01
calendar.set(year, month, date);
// Here we get the maximum days for the date specified
// in the calendar. In this case we want to get the number
// of days for february 2021
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Max Day: " + maxDay);
// Here we want to see what is the days for february on
// a leap year.
calendar.set(2020, Calendar.FEBRUARY, 1);
maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Max Day: " + maxDay);
}
}
The result of the code snippet above:
Max Day: 28
Max Day: 29
In JDK 8 you can use the new Date Time API to get the number of days in a month. Here an example that show you how to do it: How do I get the length of month represented by a date object?.
How do I create random number?
The java.lang.Math.random() method returns random number between 0.0 and 1.0 including 0.0 but not including 1.0. By multiplying Math.random() result with a number, for example 10 will give us a range of random number between 0.0 and 10.0.
To get a random number between two numbers (n and m) we can use the formula of: n + (Math.random() * (m - n)). Where n is the lowest number (inclusive) and m is the highest number (exclusive).
package org.kodejava.lang;
public class RandomNumberExample {
public static void main(String[] args) {
// The Math.random() returns a random number between 0.0 and 1.0
// including 0.0 but not including 1.0.
double number = Math.random();
System.out.println("Generated number: " + number);
// By multiplying Math.random() result with a number will give
// us a range of random number between, for instance 0.0 to 10.0 as
// shown in the example below.
number = Math.random() * 10;
System.out.println("Generated number: " + number);
// To get a random number between n and m we can use the formula:
// n + (Math.random() * (m - n)). The example below creates random
// number between 100.0 and 200.0.
int n = 100;
int m = 200;
number = n + (Math.random() * (m - n));
System.out.println("Generated number: " + number);
// Creates an integer random number
int random = 100 + (int) (Math.random() * 100);
System.out.println("Generated number: " + random);
}
}
Here is an example result of our program.
Generated number: 0.024974902600698234
Generated number: 2.271051510086771
Generated number: 147.542543014888
Generated number: 112
How do I query records from a table?
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcQueryExample {
// Database connection information
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
public static void main(String[] args) {
// Get a connection to database.
try (Connection connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
// Create a statement object.
Statement statement = connection.createStatement();
// Executes a query command to select isbn and the book title
// from books table. The execute query returns a ResultSet
// object which is the result of our query execution.
String query = "SELECT isbn, title, published_year FROM book";
ResultSet books = statement.executeQuery(query);
// To get the value returned by the statement.executeQuery we
// need to iterate the books object until the last items.
while (books.next()) {
// To get the value from the ResultSet object we can call
// a method that correspond to the data type of the column
// in database table. In the example below we call
// books.getString("isbn") to get the book's ISBN
// information.
System.out.println(books.getString("isbn") + ", " +
books.getString("title") + ", " +
books.getInt("published_year"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
How do I get my screen size?
package org.kodejava.awt;
import java.awt.*;
public class ScreenSizeExample {
public static void main(String[] args) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
System.out.println("Screen Width: " + screenSize.getWidth());
System.out.println("Screen Height: " + screenSize.getHeight());
}
}
The output of the code snippet above:
Screen Width: 2560.0
Screen Height: 1080.0
How do I determine if a pathname is a directory?
To determine if an abstract pathname is a directory we can use the File.isDirectory() method. Here is an example code.
package org.kodejava.io;
import java.io.File;
public class IsDirectoryExample {
public static void main(String[] args) {
// Creates a instance of File.
File file = new File("C:/Users/wsaryada");
// Check if the abstract pathname is a directory by calling
// isDirectory() method of the File class.
if (file.isDirectory()) {
System.out.println("This file is a directory.");
} else {
System.out.println("This is just an ordinary file.");
}
}
}
How do I get total space and free space of my disk?
package org.kodejava.io;
import java.io.File;
public class FreeSpaceExample {
public static void main(String[] args) {
// We create an instance of a File to represent a partition
// of our file system. For instance here we used a drive D:
// as in Windows operating system.
File file = new File("D:");
// Using the getTotalSpace() we can get an information of
// the actual size of the partition, and we convert it to
// mega bytes.
long totalSpace = file.getTotalSpace() / (1024 * 1024);
// Next we get the free disk space as the name of the
// method shown us, and also get the size in mega bytes.
long freeSpace = file.getFreeSpace() / (1024 * 1024);
// Just print out the values.
System.out.println("Total Space = " + totalSpace + " Mega Bytes");
System.out.println("Free Space = " + freeSpace + " Mega Bytes");
}
}
Here is the result of the program:
Total Space = 1907605 Mega Bytes
Free Space = 946213 Mega Bytes
How do I rename a file or directory?
package org.kodejava.io;
import java.io.File;
import java.io.IOException;
public class FileRenameExample {
public static void main(String[] args) throws IOException {
// Creates a new file called OldHouses.csv
File oldFile = new File("OldHouses.csv");
boolean created = oldFile.createNewFile();
System.out.println("File created? " + created);
// Creates the target file.
File newFile = new File("NewHouses.csv");
// The renameTo() method renames file or directory to a
// new name by passing the new destination file.
boolean renamed = oldFile.renameTo(newFile);
System.out.println("File renamed? " + renamed);
}
}
How do I check if a file is hidden?
The File.isHidded() method checks to see if the file represented by aFile object is a hidden file. The definition of hidden is varied between operating systems. On UNIX based systems, a file is considered to be hidden when their name begins with a period character ('.'). On Windows operating system, a file is considered to be hidden if it has been marked hidden in the filesystem.
This File.isHidden() method returns true if and only if the file denoted by this File object is hidden according to the conventions of the underlying platform.
package org.kodejava.io;
import java.io.File;
import java.io.IOException;
public class FileHiddenExample {
public static void main(String[] args) throws IOException {
File file = new File("Hidden.txt");
file.createNewFile();
// We are using the isHidden() method to check whether a file
// is hidden.
if (file.isHidden()) {
System.out.println("File is hidden!");
} else {
System.out.println("File is not hidden!");
}
}
}
If you want to set the file attribute to hidden in Windows operating system you can see it in the following example: How do I set the value of file attributes?
