All the answers to your questions on Java can be found right here!

We not only render solutions in Java programming, our experts provide answers on using Java like a professional as well. Browse through the frequently asked questions on Java and find the answers you are looking for.

JAVA FAQs – PART I

How to initialise an array in Java?

In Java, in order to initialise an array, you must use the correct syntax, which is given below:

ArrayInitializer:

   { [VariableInitializerList] [,]    }

VariableInitializerList:

   VariableInitializer {, VariableInitializer}

The ‘ArrayInitializer’ is written as a comma-separated list of expressions and enclosed in curly braces {}. Also, each ‘VariableInitializer’ must be assignment-compatible with the array’s component type, otherwise, you may run into an error during compilation.

Example: Declaring and Initialising Array In A Single Statement

import java.util.Array;

public class InitializeArrayDemo

{

   public static void main(Strinng[] args)

 {

      int[] a = {1, 3, 5, 7, 9};

System.out.println(Arrays.toString(a));

  }

}

How to uninstall Java?

You can uninstall or remove Java, including the JDK and JRE from your desktop or laptop. Based on the operating system which you use, the steps may differ. See the steps given below in order to remove or uninstall Java from your current operating system:

Windows XP

  1. Click Start menu→ Go to Control Panel → Click Add/Remove Programs.
  2. Select Java from the list.
  3. Click the Remove/Uninstall button and follow the onscreen instructions.

Windows Vista and 7

  1. Click Start button → Go to Control Panel → Click Programs → Click Programs and Features.
  2. Select Java from the list.
  3. Click the Uninstall button and follow the onscreen instructions.

Windows 8 and 8.1 Pro

  1. Go to Start screen → Click Control Panel → Go to Uninstall a Program.
  2. Select Java from the list.
  3. Click the Uninstall button and follow the onscreen instructions.

Windows 10

  1. Click Start → Click Settings → Go to System → Click Apps & Features.
  2. Select Java from the list.
  3. Click the Uninstall button and follow the onscreen instructions.

Mac OS X

  1. Go to Finder → Click Applications.
  2. Type or paste JavaAppletPlugin.plugin in the search box and press the Enter key.
  3. Right-click on the file and select Move to Trash.

Unix/Linux

  1. Open Software Centre.
  2. Type Java in the search box. You can also go to the Installed section and look for Java.
  3. Select Java (including plugin, JDK, JRE, if any) and click the Remove button.

If you are an advanced computer user, such as a system administrator, then you can manually remove or uninstall Java via the terminal or command line.

How to call a method in Java?

A Java method is a collection of statements which are grouped together in order to perform a particular task or operation. There are two ways in which you can call a method:

  1. Method that returns a value
  2. Method that does not return a value

The process of calling a method in a Java program is carried out when the return statement is executed and it it reaches the method ending with closed brackets ‘()’.

For example:

System.out.println(“This is a demo on calling a method.”);

How to create an array in Java?

You can create an array in a Java program.

Syntax:

Type[] <variable name> = new Type[value];

Example:

class ArrayDemo

{

public static void main(String[] args)

{

int[] myArray; //declares an array of integers

myArray = new int[3]; //allocates memory for 3 integers

myArray[0] = 2015; //initialises first element

myArray[1] = 2016;

myArray[2] = 2017;

myArray[3] = 2018;

System.out.println(“The year is: “ + myArray[0]);

System.out.println(“The year is: “ + myArray[1]);

System.out.println(“The year is: “ + myArray[2]);

System.out.println(“The year is: “ + myArray[3]);

}

}

How to reverse a string in Java?

Use the following Java code to reverse a string in the given output:

class InvertString

{

public static void main(String args[])

{

StringBuffer a = new StringBuffer(“Hello World!”);

System.out.println(a.reverse());

}

}

Note: The StringBuffer class is a fine option as it contains a method ‘reverse()’ which can be used to reverse or invert a given object of its class.

How to sort an array in Java?

To sort arrays in Java programs, you will need to use the “Arrays.sort(yourArray);” method from the java.utils. Arrays library.

How to convert int to string in Java?

When converting from an integer (int) to a string in java, it is best that you use the String.valueof() method:

int I = 2;

String strI = String.valueof(i);

How to compile java

Compiling Java programs can be performed in two ways: use the command prompt (for Windows) or Terminal (for Mac OS or Unix/Linux), or you can use a java compiling software application such as Eclipse, GNU Compiler for Java (GCJ), etc.

You can compile your Java program via command line by using the javac command. The syntax is javac filename.java (with extension).

How to read from a file in Java?

You can read from a file in Java with the help of BufferedReader and StringBuilder. See the example given below:

BufferedReader br = new BufferedReader(new FileReader(“file.txt”));

try

{

StringBuilder sb = new StringBuilder();

String line = br.readLine();

while (line != null)

{

sb.append(line);

sb.append(System.lineSeparator());

line = br.readLine();

}

String everything = sb.toString();

}

finally {

br.close();

}

How to declare an array in Java?

The most useful way of declaring an array in Java programs is by using the syntax:

Type[] <variable name> = new Type[value];

This syntax is applied for declaring a one-dimensional array. Here, If you want to declare multi-dimensional arrays, the use the following syntax:

Type[] []… <variable name> = new Type[value1] [value2]…;

For example,

int[] a = new a[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

The example given above is used for declaring a single dimensional array in a Java program.

How to read a file in Java?

There are several ways you can read as well as write a file in Java. Some of the popular classes that allow you to read Java files (and ordinary text files) are JDK, BufferedReader, FileReader, Scanner, IOUtils, FileInputStream, FileUtils and much more. In addition, it is possible to read a Java file from JAR and via URL on your web browser. You can easily find them online to use on your computer system in order to view your Java files.

How to print an array in Java?

In order to print an array (with elements) in Java, you can use the following methods:

  1. Arrays.toString(). This method will print one-dimensional array in rows and columns.
  2. Arrays.asList(). This method will print one-dimensional array as a list.
  3. Arrays.deepToString(). This method will print two-dimensional array in a line.

How to compare strings in Java?

You can compare strings in Java using different methods. See the methods given below:

  1. Creating two string objects:

String string1 = “Hello”;

String string2 = “Greetings”;

  1. Using the startsWith() method for returning boolean values (True or False):

System.out.println(string1.startsWith(“He”)); //returns True

System.out.println(string1.startsWith(“el”)); //returns False

  1. Using the endsWith() method for returning boolean values (True or False)

System.out.println(string1.endsWith(“lo”)); //returns True

System.out.println(string2.endsWith(“Gr”)); //returns False

How to check Java version?

The simplest way to check the version of Java that is installed in your computer or operating system is by launching the command prompt (Windows) or Terminal (Mac OS and Unix/Linux) and type java -version. That’s it! The current version of Java will displayed on the screen.

How to use scanner in Java?

The Scanner class is contained in the java.util.Scanner library that will allow you to read and input values of various types in Java programming. Scanner breaks its input into tokens by using a delimiter pattern, which by default, matches whitespace (used as Character.isWhitespace). The following is an example of using Scanner in Java:

import java.util.Scanner;

public class Demo

{

public static void main(String[] args)

{

System.out.println(“Enter a number: ”);

Scanner scan = new Scanner(System.in);

int num1 = scan.nextIn();

System.out.println(“Enter another number: “);

int num2 = scan.nextIn();

int num3 = num1 + num2;

System.out.println(“This is what you get: “ + num3);

}

}

How to throw an exception in Java?

The throw statement lets you throw an exception in your Java programs. The throw statement requires a single argument, that is, a throwable object, which is an instance of any sub-class of the Throwable class (a class always starts with an upper-case letter). See the syntax with example of a throw statement given below:

Syntax;

throw new exception_class(“error message”);

Example:

throw new ArithmeticException(“The year 2018 is not of the 20th century.”);

How to write to a file in Java?

Refer to the following example in order to write to a file in Java.

PrintWriter writer = new PrintWriter(“your-file-name.txt”, “UTF-8”);

writer.println(“Input your first line.”);

writer.println(“Input your second line.”);

writer.close();

In the example given above, we have used PrintWriter. You can also use others like BufferedWriter, FileOutputStream, DataOutputStream, FileChannel, RandomAccessFile, Java 7 Files and much more.

JAVA FAQs – PART II

How to run Java program in terminal?

In order to run your Java program in the terminal (Mac OS and Unix/Linux) and command prompt (Windows), ensure that you have Java installed on your computer. Also, you are required to include the appropriate path to JDK in the System Environment (Windows). Open terminal and locate the directory where your Java file is stored. Once located, use the command java filename to execute the program. You may be required to compile the program first, using javac filename.java command.

How to convert string to int in Java?

To convert (also called parsing in Java programming) a string into an integer in Java, you will need to use the syntax given as follows:

String myString = “value”;

int foo = Integer.parseInt(myString);

Example:

String myString = “12345”;

int foo = Integer.parseInt(myString);

How to return an array in Java?

In Java programming, the expression to return an array is:

public static void main(String[] args) {

//enter value here

System.out.print(“input output message here”);

}

How to initialise an ArrayList in Java?

The simplest method to initialise an ArrayList in Java is by using the following syntax:

List<String> element = Arrays.asList(“A”, “B”, “C”, “D”, “E”…);

How to import a class in Java?

Every class in Java is associated with a special object of type java.lang.Class. If all of your classes are in the same package, then it is not necessary to import them. However, in order to import a class in Java, you must use the import keyword. For example:

import package.myclass;

How to get user input in Java?

There are a lot of ways you can get user input in your Java programs. However, you can use the simplest method with Scanner. See the syntax with example given below:

import java.util.Scanner;

Scanner reader = new Scanner(System.in);

System.out.println(“Enter a number: “);

int n = reader.nextInt();

reader.close();

How to call a method from another class in Java?

What you need to remember is when you call a method from another class, you will need to tell the compiler where to find that method. For instance, you can simply initialise an instance of the WordList class and then call the method.

WordList list = new WordList();

list.addWord(“someWord”);

How to round in Java?

Use setRoundingMode, set the RoundingMode explicitly to handle your issues with the half-even round, then use the format pattern for your required output.

How to implement comparable Java?

To implement comparable in Java, you simply have to define an object which can be compared to the particular category. For example:

public class Animal implements Comparable<Animal>

public int compareTo(Animal other)

{

return Integer.compare(this.year_discovered, other.year_discovered);

}

How to print in Java?

If you want to display the output of your program, or other information in Java, then you must use the print() or println() methods. The only difference between the two methods is that the print() statement will position the cursor on the same line, whereas, the println() statement will position the cursor on the next line after the output.

For example:

System.out.print(“Welcome to Java programming!”); //cursor stays on the same line

System.out.println(“Welcome to Java programming!”); //cursor is positioned on the next line

How to split a string in Java?

You can split several string values in Java with the help of the String.split() method. See the example below on how to use the method to split a string value.

String string = “Hello-World”;

String[] parts = string.split(“-”); //expression is passed to split two string values

String part1 = parts[0]; //this will separate Hello

String part2 = parts[1]; //this will separate World

How to generate a random number in Java?

In Java, generating numbers, or random numbers require arithmetic logic and operations. Also, you must use the Math.random() method to fulfil your purpose. The Random class must be included in the Java package library. See the syntax with example given below:

import java.util.Random;

int max = 100;

int min = 1;

Random rdm = new Random()

int value = rdm.nextInt((max – min) + 1) + min;

How to sort an ArrayList in Java?

To sort an ArrayList in Java, you are required to use the sort() method of the Collections class. The Collections class is a utility class that is contained in the java.util.collections package library. The syntax for using the sort() method is:

Collections.sort(arraylist);

How to read a text file in Java?

Java supports reading plain text files with the help of FileReader, BufferedReader, Scanner, StringBuilder and much more. These readers are easy to use and are particularly effective.

How to declare an ArrayList in Java?

You can create a new object using the constructor that accepts a Collection:

List<String> x = new ArrayList<value>(Arrays.asList(“abc”, “xyz”));

Here are the constructors of the ArrayList class:

ArrayList(): This constructs an empty list with an initial capacity of ten.

ArrayList(Collection<? Extends E> c) (*): This constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

ArrayList(int initialCapacity): This constructs an empty list with the specified initial capacity.

How to create an object in Java?

There are four ways you can create objects in Java:

  1. Using the new keyword: This is the most common way to create an object in Java. The syntax is given as follows:

MyObject object = new MyObject();

  1. Using the Class.forName() method: You can use this method to create an object in Java if you already know the name of the class and whether it has a public default constructor. See the syntax given below:

MyObject object = (MyObject) Class.forName(“subin.rnd.MyObject”).newInstance();

  1. Using clone() method: This method will allow you to create a copy of an existing object in Java. See the syntax given below:

MyObject hasObject = new MyObject();

MyObject object = (MyObject) hasObject.clone();

  1. Using object de-serialization: This method will allow you to create an object from its serialized form. See the syntax given below:

ObjectInputStream inStream = new ObjectInputStream(anInputStream);

MyObject object = (MyObject) inStream.readObject();

How to clear Java cache?

You can clear Java cache by deleting Temporary Files from the Java Control Panel in Windows XP, Vista, 7, 8 and 10 and on Mac OS X editions.

How to close a Scanner in Java?

In Java, Scanner should always be closed in the finally block. See the syntax given below:

Scanner scanner = null;

try {

scanner = new Scanner(System.in);

}

finally {

if(scanner!=null)

scanner.close();

}

JAVA FAQs – PART III

How to install Java 64-bit?

If you are not sure which operating system architecture you are using, the default web browser installed on your computer will be automatically presented with the 64-bit Java that you can download and install from the website.

How to parse a string in Java?

To parse a string in your Java program, you will need to use the String.split() method. Consider the syntax with example given below:

String str = “prefix-John-Maggie-Beach-Sea”;

String prefix = “prefix-”;

String noPrefixStr = str.substring(s.indexOf(prefix) + prefix.length());

String[] tokens = str.split(“-”);

for (String t : tokens)

System.out.println(t);

How to master Java?

Java is a high-level object oriented programming language which is used widely in the fields of computer programming, development of websites, software, applications for the mobile platform and much more. Therefore, in order to master your skills in Java, you must learn and constantly practice the programming language. There are also online tutorial websites for beginners that will help you learn Java.

Additionally, you can approach our experts at Codexoxo to guide you to learn, create, test and implement Java programs, whether it’s for your projects or simply for the passion of learning the programming language for general use. Call <enter-phone-number>.

How to read a file in Java using Scanner?

You can a Java file, even a plain text file in Java using the Scanner method. To do this, consider the syntax with example given below:

import java.io.File;

import java.util.Scanner;

public class Demo

{

public static void main(String[] args)

{

File file = new File(“yourfile.txt”);

Scanner sc = new Scanner(file);

while (sc.hasNextLine())

{

int i = sc.nextInt();

System.out.println(i);

}

sc.close();

}

}

Note: You must mention the filename with extension as given above in the statement. For improved results, you can make use of the try..catch block to handle exceptions.

How to use Eclipse Java?

Eclipse is a software application and an integrated development environment (IDE) for Java. You will need a Java Development Kit (JDK) installed in order to use Eclipse on your workstation. Download and install Eclipse that will allow you to create, compile and execute/run Java programs on a user-friendly interface.

To use Eclipse, follow the steps given below:

  1. Start Eclipse.
  2. Create a new Java project:

(a) File → New → Project.

(b) Select “Java” in the category list.

(c) Select “Java Project” in the project list and click the Next button.

(d) Enter a project name in the Project name field (e.g., Hello World Project).

(e) Click the Finish button and accept any message that may appear on the screen.

  1. Create a new Java class:

(a) Click the “Create a Java Class” button in the toolbar.

(b) Enter “Hello World” in the Name field.

(c) Click the checkbox indicating that you would like Eclipse to create a “public static void main(String[] args)” method.

(d) Click the Finish button.

  1. A Java editor for Hello World will open. Below the main method, enter the following line:

System.out.println(“Hello World”);

  1. Save your project using Ctrl+S keys and this will start the automated compilation of your program.
  2. Click the Run button in the toolbar. You will be prompted to create a Launch configuration. Select “Java Application” and then click “New”.

7. Click Run to run your “Hello World” program. The console will open and display the output “Hello World” on your screen.

How to run Java programs in Windows 10?

To run Java programs in Windows 10 machine, you can either use the command prompt, or simply download and install a client software such as NetBeans, Eclipse, etc. For using the command prompt, first make sure that you have installed a Java Runtime Environment (JRE) and that you have specified Java path in the Environment Variable settings, which can be accessed from the System Properties window.

After you have specified the Java path, you can run Java programs via command prompt – locating the directory where you have stored your Java files using cd and dir commands and then type the name of the Java file. For example, java.exe, myfile.exe, etc. To compile your Java program, use javac myfile.java command.

How to open a file in Java?

Here is a sample program to open a file in Java:

package com.journaldev.files;

import java.awt.Desktop;

import java.io.File;

import java.io.IOException;

public class JavaOpenFile

{

public static void main(String[] args)

{

File file = new File(“Users/Username/note.txt”);

if(!Desktop.isDesktopSupported())

{

System.out.println(“Desktop is not supported.”);

return;

}

Desktop desktop = Desktop.getDesktop();

if(file.exists()) desktop.open(file);

From the example given above, the text file will be opened in the default text editor application (Notepad in Windows). Similarly, if you try to open a PDF file using the program given above, it will be opened in Acrobat Reader or Adobe Reader, whichever is installed. An exception will be thrown if no dedicated application is found to open the required file.

How to return multiple values in Java?

In Java, when you want a function to return multiple values, you must

  1. Embed those values in an object you return, or
  2. Change an object that is passed to your function

Here is a syntax with example that shows returning multiple values in a Java program:

public class Demo

{

public String name;

public String location;

 

public String[] getDemo()

{

String ar[] = new String[2];

ar[0] = name;

ar[1] = location;

return ar; //will return two values simultaneously

}

}

How to square a number in Java?

You can square a number in Java in two different ways:

  1. Multiplying the number by itself

The syntax with example to use this method is:

int i = 2;

int square = i * i;

Here, the value 2 will be multiplied by itself. Hence, giving you the output 4.

  1. Calling the Math.pow function

The syntax with example to use this method is:

int i = 2;

int square = Math.pow(i, 2);

How to throw exception in Java?

In Java programming, exceptions can be thrown using the throw statement. Any code can throw an exception – your code, code from a package that is written by another programmer, or an exception that is thrown by the Java run-time environment. The syntax for using the throw statement is:

throw someThrowableObject;

Example:

public Object pop()

{

Object obj;

if (size == 0)

{

throw new EmptyStackException();

}

obj = objectAt(size – 1);

setobjectAt(size – 1, null);

size–;

return obj;

}

How to do or apply exponents in Java?

In normal arithmetic operations, you can use the Caret symbol ‘^’ to use as exponents. However, in Java, this is not the case. Instead, you will require the Math.pow() method which is contained in the import java.util.Math package library to help you perform arithmetic operations.

Thus, to apply exponent in your Java program, consider the syntax with example given below:

import java.util.Math;

public class Demo

{

public static void getPow()

{

Scanner sc = new Scanner(System.in);

System.out.println(“Enter first number: “);

int first = sc.nextInt();

System.out.println(“Enter second number: “);

int second = sc.nextInt();

System.out.println(first + “ to the power of “ + second + “is: “ + (int) Math.pow(first, second));

}

}

How to concatenate strings in Java?

In Java, you can concatenate or join two (or more) strings by using the ‘+’ operator. For example:

public class Demo

{

public static void main(String[] args)

{

int a = 1970;

System.out.println(“The vintage era started in: “ + a + “!”);

}

}

How to add an array in Java?

The size of an array cannot be modified. However, if you want to have a bigger array, then you will have to instantiate a new one. To do this, you must use the ArrayList.toArray(T[] a) method. For example:

String[] myArray = new String[where.size()];

where.toArray(myArray);

How to print array in Java?

The simplest way to print an array in Java is by using the syntax given below:

System.out.println(Arrays.toString(array));

If your array contains other arrays as elements, then use:

System.out.println(Arrays.deepToString(array));

Find More Solutions At Codexoxo – Contact

More solutions for Java can be easily found at Codexoxo. Our team of highly skilled experts can help you with the best answers which you are not able to find elsewhere. Also, our experts can guide you through Java programming – its usage and the preferred tools you will need. Contact us to avail assistance from our Java experts at Codexoxo. Our support centre can be reached by dialling the toll-free phone number <enter-phone-number> round the clock.

 

Speak with our team of Java professionals today and get help immediately. Our experts can assist and guide you with tasks such as Java programming, developing websites and applications for desktop as well as mobile platform and much more.

Call Now