JAVA Flashcards
What is the purpose of the main method in a Java program?
It is where the Java program starts, creating other objects and controlling the flow of the program.
How do you declare and initialize a String variable with the value “Hello World!”?
String str = “Hello World!”;
What symbol is used to concatenate two strings in Java?
The + symbol
How do you declare a constant in Java?
By using the final keyword.
final double STANDARD_GRAVITY = 9.81;
What is the result of the modulo operation 10 % 3?
1
What does the charAt method do in Java?
It returns the character at a specified index in a string.
String message = “Hello, World!”;
char firstChar = message.charAt(0);
//Retrieves character at index 0
char seventhChar = message.charAt(6);
//Retrieves character index 6
What is the difference between System.out.println and System.out.print?
System.out.println prints a string or number and then starts a new line, while System.out.print prints a string or number without starting a new line.
How do you extract a substring from index 1 to index 3 from the string “Birkbeck”?
String str1 = uni.substring(1, 3);
(This will store “ir”)
What is an example of declaring and assigning multiple variables in one line in Java?
int numberOfCars = 5, numberOfMotorbikes = 7;
What does the final keyword indicate when declaring a variable?
It indicates that the variable is a constant and its value cannot be changed.
How do you use the substring method to extract a part of a string in Java?
String sub = str.substring(startIndex, endIndex);
End index is excluded.
What data type would you use to store the value 9.81 in Java?
double
How do you declare a method in Java?
public void methodName() { /* code */ }
What does the + operator do when used with strings in Java?
It concatenates the strings.
What is the significance of using double quotes around a string in Java?
Double quotes are used to denote string literals in Java.
What is the effect of the statement x += 5; in Java?
It increments the variable x by 5.
What is the output of System.out.println(“Hello” + “ World!”);?
Hello World!
What is the role of the public keyword in Java?
It is an access modifier that makes the class, method, or variable accessible from any other class.
How do you declare an integer variable and assign it the value 10 in Java?
int x = 10;
What keyword is used to define a class in Java?
class
How do you create a new object of a class in Java?
ClassName obj = new ClassName();
What does the static keyword mean in Java?
It means the method or variable belongs to the class, rather than instances of the class.
How do you declare a method that returns an integer in Java?
public int methodName() { /* code */ }
What is the purpose of the void keyword in a method declaration?
It indicates that the method does not return any value.
How do you write a single-line comment in Java?
Using // followed by the comment text.
What is the default value of an uninitialized boolean variable in Java?
FALSE
How do you write a multi-line comment in Java?
Using /* comment text */
How do you import a package in Java?
Using the import statement, e.g., import java.util.Scanner;
How do you create a for loop that prints numbers 1 to 10 in Java?
for (int i = 1; i <= 10; i++)
{ System.out.println(i); }
How do you declare an array of integers with 5 elements in Java?
int[] arr = new int[5];
How do you access the third element of an array named arr in Java?
arr[2]
What does the length property of an array return in Java?
The number of elements in the array.
How do you handle exceptions in Java?
Using a try-catch block,
e.g.,
try { /* code / } catch (ExceptionType e) { / handler */ }
What is the purpose of the final block in exception handling?
It contains code that will run regardless of whether an exception was thrown or not.
How do you read a line of text from the Java console?
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
How do you create a new file using Java’s File class?
java File file = new File(“filename.txt”); file.createNewFile();
What does the == operator do with reference types in Java?
It checks if both references point to the same object.
How do you convert a string to an integer in Java?
int num = Integer.parseInt(“123”);
How do you compare the values of two strings in Java?
Using the .equals method, e.g., str1.equals(str2);
How do you convert an integer to a string in Java?
String str = String.valueOf(123);
String str = Integer.toString(123);
How do you create a Scanner object in Java to read user input from the keyboard?
Scanner scanner = new Scanner(System.in);
How do you import the Scanner class in Java?
import java.util.Scanner;
How do you read an integer value from the user using Scanner in Java?
int favouriteInteger = scanner.nextInt();
How do you read a double value from the user using Scanner in Java?
double favouriteDouble = scanner.nextDouble();
How do you read a string from the user using Scanner in Java?
String favouriteString = scanner.nextLine();
How do you solve the issue of reading a string after an integer input with Scanner?
Use an extra scanner.nextLine(); to consume the end-of-line character.
What is a common issue when using scanner.nextLine() after scanner.nextInt()?
The scanner does not consume the end-of-line character, so scanner.nextLine() may read it as input.
What is the syntax for an if-else if-else statement in Java?
if (condition1) { // statements }
else if (condition2) { // statements }
else { // statements }
How do you write a basic if statement in Java?
if (condition) { // statements }
How do you write a basic if-else statement in Java?
if (condition) { // statements } else { // statements }
What does the && operator mean in Java?
AND
What is the correct way to compare two strings for equality in Java?
str1.equals(str2);
What is the syntax for a while loop in Java?
while (condition) { // statements }
What is the syntax for a do-while loop in Java?
do { // statements } while (condition);
How do you write a basic for loop in Java?
for (int i = 0; i < 10; i++) { // statements }
What is the scope of a variable declared inside a loop in Java?
The variable is only defined within the loop.
How do you exit a loop prematurely in Java?
Use the break statement.
What is the purpose of continuing the statement in a loop?
It skips the current iteration and proceeds with the next iteration of the loop.
How do you create a nested loop in Java?
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
// statements
}
}
What is a common use of nested loops?
Generating a multiplication table.
How do you declare a boolean variable in Java?
boolean isJavaFun = true;
What is the syntax for an if statement that checks multiple conditions using &&?
if (condition1 && condition2) { // statements }
How do you check if a number is positive in Java?
if (number > 0) { // statements }
How do you declare and initialize an array of integers with 5 elements?
int[] numbers = {1, 2, 3, 4, 5};
How do you access the length of an array in Java?
array.length
How do you generate a random number between 0 (inclusive) and 1 (exclusive) in Java?
double r = Math.random();
What is the syntax for checking if a variable x is between 0 and 100 (inclusive)?
if (0 <= x && x <= 100) { // statements }
How do you convert a string to a double in Java?
double num = Double.parseDouble(“123.45”);
How do you print an array of integers in Java?
for (int i = 0; i < array.length; i++) { System.out.println(array[i]); }
What is the syntax for the ternary operator in Java and how is it used?
Syntax:
condition ? expressionIfTrue : expressionIfFalse;
String result = (age >= 18) ? “You can drive” : “You cannot drive”;
How do you declare an array of integers in Java?
int[] scoreBoard;
How do you construct a new array of integers with 5 elements in Java?
new int[5];
How do you declare and initialize an array with specific values in Java?
int[] scoreBoard = {10, 30, 42, 11, 45};
How do you initialize an array of 5 integers to zero in Java?
int[] scoreBoard = new int[5];
How do you declare and initialize a string array with specific values in Java?
String[] classmates = {“Maria”, “John”, “Irene”};
How do you access the 4th element of an array named scoreBoard in Java?
scoreBoard[3];
What happens if you try to access an index outside the bounds of an array in Java?
It causes a runtime exception: java.lang.ArrayIndexOutOfBoundsException.
How do you get the length of an array named scoreBoard in Java?
scoreBoard.length;
How do you iterate through all elements of an array using an enhanced for loop in Java?
for (int playerScore : scoreBoard) { System.out.print(playerScore + “ “); }
How do you fill an array with values provided by the user in Java?
for (int i = 0; i < scoreBoard.length; i++) { scoreBoard[i] = scanner.nextInt(); }
How do you copy the elements of one array to another in Java?
for (int i = 0; i < scoreBoard.length; i++) { pointBoard[i] = scoreBoard[i]; }
How do you parse a command-line argument to an integer in Java?
int num = Integer.parseInt(args[0]);
How do you insert an element at an arbitrary position in an array in Java?
Shift elements to the right and then insert the element.
How do you declare a partially filled array and keep track of the filled positions?
int[] array = new int[10]; int rightmost = 5;
How do you swap two elements in an array in Java?
int temp = scoreBoard[0]; scoreBoard[0] = scoreBoard[1]; scoreBoard[1] = temp;
What is the basic idea of the selection sort algorithm?
It divides the array into sorted and unsorted parts and iteratively selects the smallest element from the unsorted part to move to the sorted part.
How do you declare an ArrayList of strings in Java?
ArrayList<String> items = new ArrayList<String>();</String></String>
How do you add an element to an ArrayList in Java?
items.add(“Sword”);
How do you get the size of an ArrayList in Java?
items.size();
How do you check if an ArrayList is empty in Java?
items.isEmpty();
How do you remove an element at a specific position in an ArrayList in Java?
items.remove(index);
How do you set the value of an element at a specific position in an ArrayList in Java?
items.set(index, “Helm”);
How do you create a copy of an ArrayList in Java?
ArrayList<String> copy = new ArrayList<String>(items);</String></String>
How do you iterate through all elements of an ArrayList using an enhanced for loop?
for (String item : items)
{
System.out.println(item);
}
How do you declare a two-dimensional array in Java?
int[][] example = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 } };
How do you access an element in a two-dimensional array in Java?
example[row][column];
How do you populate a two-dimensional array using nested loops?
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
array[i][j] = (i + 1) * (j + 1);
}
}
How do you convert a string to a double in Java?
double num = Double.parseDouble(“123.45”);
How do you generate a random integer between 0 and 100 in Java?
int randomNum = (int)(Math.random() * 101);
How do you print all elements of an array in Java?
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
What is the main purpose of object-oriented programming (OOP)?
To organize software design around data, or objects, rather than functions and logic.
What is a class in object-oriented programming?
A blueprint for creating objects, providing initial values for state (attributes) and implementations of behaviour (methods). Example: class Animal { int age; String name; }
What does a constructor in Java do?
Initializes a new object and its properties when an instance is created. Example: public Animal() { age = 0; name = “”; }
What is an example of a simple Java constructor for a class Employee?
public Employee() { this.name = “”; this.email = “”; this.workedHours = 0; }
What are access modifiers in Java?
Keywords that set the accessibility of classes, methods, and other members. Common modifiers include public, private, and protected. Example: private int age;
What does the private access modifier do?
Restricts access to the member so that it can only be accessed within its own class. Example: private String password;
How can private variables in a class be accessed from outside the class?
Through public methods, typically getters and setters. Example: public String getName() { return name; }
How do you declare a class in Java?
Using the class keyword followed by the class name and a pair of curly braces. Example: class Employee { }
How is a new object instantiated in Java?
The new keyword is followed by the class name and parentheses. Example: Employee emp = new Employee();
What is the difference between public and private variables?
Public variables can be accessed from any other class; private variables can only be accessed within their own class. Example: public int id; private String name;
What is the default value of a string in Java if not explicitly initialized?
null
Example: String name;
How does a for loop differ from a while loop?
A for loop is used when the number of iterations is known before it runs; a while loop runs based on a condition being true. Example: for (int i = 0; i < 10; i++) {} vs while (condition) {}
Why are constructors important in Java?
They provide a way to initialize the state of new objects at the moment of creation. Example: public Employee(String name) { this.name = name; }
How do you create a method in Java that returns an integer?
public int getAge() { return age; }
What is method overloading?
When two or more methods in the same class have the same name but different parameters. Example: void display(String data) {} void display(int data) {}
What is a getter method in Java?
A method that reads and returns the value of a private variable. Example: public int getAge() { return this.age; }
Why should instance variables often be private?
To maintain encapsulation and prevent unauthorized parts of code from modifying internal state. Example: private int age;
What is a setter method in Java?
A method that updates the value of a private variable. Example: public void setAge(int age) { this.age = age; }
How do you handle data encapsulation in Java?
By keeping class fields private and providing public getters and setters to access and update the values. Example: public void setName(String name) { this.name = name; }
What does the this keyword represent in Java?
It refers to the current instance of the class. Example: this.name = name;
How do you add an element to an ArrayList in Java?
Using the .add() method. Example: list.add(“element”);
What is the purpose of the public keyword in a class definition?
To allow access to classes, methods, or variables from any other class. Example: public void display() {}
What is an instance variable?
A variable declared within a class for which each instantiated object of the class has its own copy. Example: private int id;
How do you check the size of an ArrayList?
Using the .size() method. Example: list.size();
What is method visibility and why is it important?
It dictates from where the method can be accessed within the application, crucial for encapsulation. Example: private void calculateSalary() {}
How does the default constructor behave if not explicitly defined?
It initializes object fields with default values, such as null for objects and zero for numeric types. Example: When no constructor is defined, Employee e = new Employee();
How do you declare a method that does not return a value?
With the void keyword. Example: public void printName() { System.out.println(this.name); }
What is the role of a constructor in an object’s lifecycle?
To initialize the object’s state when it is created. Example: public Person() { this.name = “Unknown”; this.age = 0; }
How are instance methods called in Java?
Using the dot notation with an instance of the class. Example: person.displayInfo();
What is the significance of the new keyword in Java?
It creates a new object instance of a class. Example: List<String> myList = new ArrayList<>();</String>