In this Post, You wil learn about Java Fundamentals Questions And Answer with Easy Understandable for Students. Java is a widely-used object-oriented programming language designed for cross-platform compatibility, stability, and security.

Questions Answer of Java Fundamentals

  • What is Java Language?

Ans:    Java is a very popular high level programming language and has been used widely to create various types of computer applications such as database applications, desktop applications, Web based applications, mobile applications, and games among others.

  • What is High level Programming Language

Ans:    High-level language is more readable than assembly. Some high-level languages are also scripting languages, meaning that the code is not compiled until runtime. Examples of high-level languages include: FORTRAN, C, C++, Java, JavaScript, Python.

  • Write an Five high level programming language.

Ans:    FORTRAN, C, C++, Java, JavaScript, Python

  • What is Machine Language?

Ans:-  Machine code, also known as machine language, is the elemental language of computers. It is read by the computer’s central processing unit (CPU), is composed of digital binary numbers

  • Explain the term of Compiler

Ans:    A Java compiler instead of translating Java code to machine language code, translates it into Java Bytecode (a highly optimized set of instructions).

  • Define the term Interpreter.

Ans:-  Interpreter in Java is a computer program that converts high-level program statement into Assembly Level Language.

  • What is Java Virtual Machine?

Ans:-  A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode.

  • Explain the term Java  IDE

Ans:    Java IDE (Integrated Development Environment) is a software application that enables users to write and debug Java programs more easily.

  • What is the shortcut key to Run New Project in Java NetBeans?

Ans:    F6

  • What is the shortcut key to execute or run a File in Java NetBeans?

Ans:- Shift+F6

  • What is Comments in Java and how many types of Comments.

Ans:-  The Java comments are the statements in a program that are not executed by the compiler and interpreter. There are 2 types of comments in Java.

Questions Answer of Java Fundamentals

  • Explain two ways of comments in java programming.

Ans:-  Beginning  a  comment  line  with  two  consecutive  forward  slashes  (//)

Writing  the  comment  between  the  symbols  /*  and  */

  • Why do we use comments in a code?

Ans:-

  • Comments are used to make the program more readable by adding the details of the code.
  • It makes easy to maintain the code and to find the errors easily.
  • What are Java package?

Ans:-  A  package  in  java  is  a  group  of related  classes. Package in java can be categorized in two form, built-in package and user-defined package.

  • What is class name and package name in Java?

Ans:-  In Java,   the  class  name should  be  the  same  as  the  source  file  name.  The  package  name  can  be  different  from either the class or the source file name.

  • What is Method in Java

Ans:-  A method is a group of statements written to perform specific  task. The method body is enclosed  with in  a pair of curly braces.

Note:-  Main  is  a  special method that every Java application must have.

  • Which function is used to take output in Java.

Ans:-  System.out.println()

  • What is the works of println function in Java.

Ans:-  A println() in Java is also utilised to display a text on the console, which is the parameter to this method in String.

  • What is data types? How many types of Data types in Java.

Ans:-  Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

  1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Data Type Type  of  values Size
ByteInteger8-Bit
ShortInteger16-bit
IntInteger32-bit
LongInteger64-Bit
FloatFloating Point32-bit
DoubleFloating Point64-bit
CharCharacter16-bit
BooleanTrue or False1-bit
  1. Non-primitive data types: The non-primitive data types include ClassesInterfaces, and Arrays.
  2. What are variables called in Java?

Ans:-  A  variable  is  a  placeholder  for  data  that can  change  its  value  during  program  execution.  A  variable  is  the  name  for  a storage  location  in  the  computer’s  internal  memory. All  data  variables  in  Java  have  to  be  declared  and  initialized  before  they  are  used. When declaring  variables,  we have  to  specify  the  data  type.

  • How many bytes of data does a long data-type store in java?

Ans:-  64-bit

  • Which of the following type of values store data type in java
Data TypeTypes of ValuesSize
ByteInteger8-bit
ShortInteger16-bit
IntInteger32-bit
LongInteger64-bit
FloatFloating point32-bit
DoubleFloating point64-bit
CharCharacter16-bit
BooleanTrue or false1-bit

Questions Answer of Java Fundamentals

  • What are the valid variable rules in Java?

Ans:-

  • Variable names can begin with either an alphabetic character , an underscore

(_),  or a dollar sign ($).  However,  convention is  to  begin a variable name with a

letter .  They  can  consist  of  only  alphabets,  digits,  and  underscore.

  • Variable names must be one word. Spaces are not allowed in  variable names.

Underscores  are  allowed.  “total_marks”  is  fine  but  “total  marks”  is  not.

  • There  are  some  reserved  words  in  Java  that  cannot  be  used  as  variable

names,  for  example  –  int.

  • Java  is  a  case-sensitive  language.  Variable  names  written  in  capital  letters

differ  from  variable  names  with  the  same  spelling  but  written  in  small  letters.  For

example,  the  variable  name  “percentage”  differs  from  the  variable  name

“PERCENTAGE”  or  “Percentage”.

  • It  is  good  practice  to  make  variable  names  meaningful.  The  name  should

indicate  the  use  of  that  variable.

  • Define the terms of String variables.

Ans:-  A variable of the primitive data type char can be used to store a single character . T o store more than  one character ,  we use the  String  class in  Java. T o assign a text value  to  a  String  variable  we  enclose  the  text  between  double  quotes.

  • What are operators in Java Language?

Ans:-  Operators  are  special  symbols  in  a  programming  language  and  perform  certain  specific operations. For example: +, -, *, / etc.

  • How many types of Operators?

Ans:-  There are many types of operators in Java which are given below:


  • Arithmetic Operator(+,-,*,/,%,++,–)
  • Relational Operator(==, !=, >, <, >=, <=)
  • Logical Operator (&&, ||, !)
  • Assignment Operator(=, +=, -=, *=, /=, %=)
  • What are control flow statements?

Ans:-  Java compiler executes the code from top to bottom.  Java provides statements that can be used to control the flow of Java code. Such statements are called control flow statements.

  • How many types of Control Flow statements provides by Java

Ans:-  Java provides three types of control flow statements.

  1. Decision Making statements
    • If-else statements
    • switch statement
  2. Loop statements
    • do while loop
    • while loop
    • for loop
    • for-each loop
  3. Jump statements
    • break statement
    • continue statement
  • Write the term If-Else statements.

Ans:-  The Java if statement is used to test the condition. It executes the if block if condition is true otherwise else block is executed.

  • Write the syntax of if-else statement with example.

Ans:-  The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.

Syntax:

if(condition){  

//code if condition is true  

}else{  

//code if condition is false  

}  

  • What is switch statement?

Ans:    The switch statement is used to execute a block of code matching one value out of many possible values.

  • What is the meaning of loop?

Ans:    Loops in Java is a feature used to execute a particular part of the program repeatedly if a given condition evaluates to be true.

  • What is the function of while statements in Java?

Ans:- The while statement evaluates the test before executing the body of a loop.

  • Write a square number of program using while loop.

Ans:-

public class WhileDemo {

public static void main (String[ ] args)

{

int number = 1;

while (number <= 5)

{

System.out.print (“Square of ” + number);

System.out.println (” = ” + number*number); ++number;

}

}

}

  • Write the steps to be performed to print the squares number from 1 to 5.

Ans:-

The following steps need to be performed.

1.  Initialize number = 1

2.  Test if the number <= 5

3.  If yes, print the square of the number; Increment number (number = number + 1) Go

back to step 2

4.  If no, exit the loop.

  • What is the use of ++ operator in loop

Ans:-  ++ operator is used to increment the value of number.

  • Is it same effect ++ number or number++ and number=number+1;

Ans:- Yes

  • What is function of Do while loop in Java?

Ans:- The do while statement evaluates the test after executing the body of a loop.

  • Write the steps to performed in do-while loop in Java.

Ans:- The following steps need to be performed.

1.  Initialize number = 1

2.  Print the square of the number

3.  Increment number (number = number + 1)

4.  Test if the number <= 5

5.  If yes, Go back to step 2 If no, Exit the loop

  • Difference between while loop and do while loop.

Ans:

A while loop is an entry controlled loop – it tests for a condition prior to running a block of codeA do-while loop is an exit control loop – it tests for a condition after running a block of code
A while loop runs zero or more times Body of loop may never be executedA do-while loop runs once or more times but at least once
The variables in the test condition must be initialized prior to entering the loop structure.Body of loop is executed at least once
while (condition) { statements }do { statements } while (condition);
  • Write a square number of program using do-while loop.

Ans:-

public class DoWhileDemo {

public static void main (String[ ] args)

{

int number = 1; do

{

System.out.print (“Square of ” + number);

System.out.println (” = ” + number*number); ++number;

}

while (number <= 5);

} }         

  • Write the common coding errors while using loop.

Ans:- Common Coding Errors –

  • Infinite Loops– This type of error occurs when the loop runs forever, the loop never exits. This happens when the test condition is always true.
  • Syntax Errors– Do not forget the semi colon at the end of the test condition in a do-while loop. Otherwise you will get a compiler error.
    • Do not place a semi colon at the end of the test condition in a while loop.
  • Find the Common Coding Errors in For Loop

Ans:-

Common Coding Errors: The for Loop

Initial  value  is  greater  than  the  limit  value  and  the  loop  increment  is  positive.

for  (  int  count  =  5;  count  <=  1;  count++)

In  this  case,  body  of  the  loop  will  never  be  executed

Initial  value  is  lesser  than  the  limit  value  and  the  loop  increment  is  negative.

In  this  case  also,  body  of  the  loop  will  never  be  executed.

Placing  a  semicolon  at  the  end  of  a  for  statement:

for  (  int  count  =  1;  count  <=  5;  count++);

{

//body  of  loop

}

This has the  effect  of defining the  body of the  loop  to  be empty .  The statements

within the  curly  braces  will be  executed  only  once  (after  the  for  loop  terminates)

and  not  as  many  times  as  expected.

Executing  the  loop  either  more  or  less  times  than  the  desired  number  of  times.

For example, the following loop  iterates  4 times and not the intended  5 times

because  it  exits  when  count  =  5.

for  (  int  count  =  1;  count  <  5;  count  ++)

The  correct  way  to  loop  five  times  would  be  to  test  for  count  <=  5.

Such  errors  are  known  as  off  by  one  errors.

Using  a  loop  index  (declared  within  the  loop)  outside  the  loop.

for  (  int  count  =  1;  count  <  5;  count  ++)

{

System.out.println(count);

}

System.out.println(count);  //error!!

The  scope  of  the  variable  count  is  only  within  the  body  of  the  loop.  It  is  not  visible

outside  the  loop.

  • What is use of for statements(loop) in Java?

Ans:- The for loop is the most widely used Java loop construct. For loop is used to repeat a specific block of code a known number of times.

  • Explain the three parts of the for loop.

Ans:-

  • The initial_value initializes the value of the loop counter.
  • The test_condition tests whether the loop should be executed again. The loop is exited when the test condition fails.
  • The step updates the counter in each loop iteration.
  • Write a square number of program using for loop.

Ans:-

for (int number = 1; number<= 5; ++number)

{

System.out.print(“Square of “+ number);

System.out.println(” = “+ number*number);

}

  • What is role of Arrays?

Ans:- Arrays are variables that can hold more than one value, they can hold a list of values of the same type.

Q48     Write the syntax of Arrays in Java.

Ans:- int[] marks = new int[]{value1, value2, …, valueN};

            dataType: This specifies the type of elements the array will hold, like int, double, or String.

arrayName: This is the name you choose for your array variable.

new dataType[]: This uses the new keyword to allocate memory for the array.

value1, value2, …, valueN: These are the actual values you want to store in the array, enclosed in curly braces {}.

Q:-       How to Declare and Initialize of an Array?

Ans:- 

  1. Declare the array:

Java

dataType[] arrayName;

This defines a variable arrayName of type array, but doesn’t allocate memory yet.

  • Initialize the array:

arrayName = new dataType[size];

Q49     Difference between variable and Arrays .

Ans:- Array holds multiple values, whereas an ordinary variable hold a single value. . A

variable is a field that stores data values during the execution of a Java program.

Ans:-

Common Coding Errors: Arrays

In  an  off  by  one  error,  the  loop  index  if  varied  from  0  to  n  instead  of  0  to  n-1. For example,  if  the  array  size  is  5,  then  loop  index  =  5  is  an  off  by  one  error  since  array index  can  go  only  from  0  to  4.

double  []  ]  marks  =  new  double  [5];

for  (int  i  =  0;  i  <=  5;  i++)  {

System.out.print(marks[i]);

}

In  this  case an Array index  out of bounds error occurs and the  program terminates unexpectedly  with  an  error  as  below.

Exception in thread “main”

java.lang.ArrayIndexOutOfBoundsException: 5

at  javaprograms.ArrayDemo.main(ArrayDemo.java:11)

Java  Result:  1

Q51      What is use of (\t) syntax?

Ans:- The use of \t to print a tab between the numbers in the print statement

Q52     What is Method in Java?

Ans:- A method is a block of code or collection of statements or a set of code grouped

together to perform a certain task or operation. A method has a name, a return type, an optional list of parameters, and a body. The structure of a Java method is as below:

static  double  rectangle_area  (double  length,  double  breadth)

{

return  (length  *  breadth);

}

Q:-      What is the use of Void ?

Ans:-  A  special  return  type  void  can  be  used  if  a  method  does  not  return  any  value.  For  example,  a method  that  just  prints  a  string  need  not  have  a  return  value  can  use  void  as  the  return  type.

void  print_message(String  message)  {

System.out.println(“The  message  is:  “+  message);

}

Q53     Explain the term of OOP (Object oriented Programming)

Ans:-  Java is an Object Oriented Programming (OOP) language. In an OOP language, a program is collection of objects that interact with other objects to solve a problem. Each object is an instance of a class.

Q54      What is Class and Objects?

Ans:- Objects:– An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. A program is collection of objects that interact with other  objects  to  solve  a  problem.  Each  object  is  an  instance  of  a  class.

Class :- A class is a group of objects which have common properties. . A class is a

physical or logical entity that has certain attributes. The title, author, publisher, genre and price are the data members of the class Book.

Q55     What is the role of data member and method member in Java?

Ans:- Variables declared with in a class preceded by a data type which define the state of an object are called data members.

Member method are declared where the class is defined. The methods are a member of the class within which they are written.

Public Class Book {

String Title;

String Author;       //data member of the book class

String Publisher;

double Price;

void Display()         //method member of the book class

{

System.out.println(“Title” “+Title);

System.out.println(“Author” “+Author);

System.out.println(“publisher” “+publisher);

System.out.println(“Price” “+Price);

}}

Q56      What are constructors?

Ans:- A  special method member called the  constructor  method is  used to  initialize  the  data members  of  the  class . The constructor has the  same name as the  class, has no return  type,  and may or may not  have  a  parameter  list.

class Book {

  // Member variables

  String title;

  String author;

  // Constructor (no arguments)

  Book() {

    title = “Unknown”;

    author = “Unknown”;

  }

  // Method to display book details

  public void displayDetails() {

    System.out.println(“Title: ” + title);

    System.out.println(“Author: ” + author);

  }

}

public class Main {

  public static void main(String[] args) {

    // Create a Book object using the constructor

    Book book1 = new Book();

    // Display book details

    book1.displayDetails();

  }

}

Explanation:

  1. We define a class Book with two member variables: title and author.
  2. The class has a constructor named Book. This constructor has no arguments (indicated by empty parentheses).
  3. Inside the constructor, we initialize the title and author variables with default values (“Unknown” in this case). This ensures the object has some initial state.
  4. We also define a method displayDetails to print the book’s title and author.
  5. In the Main class, we create a new Book object named book1 using the constructor. This calls the Book constructor and creates a new Book instance.
  6. Finally, we call the displayDetails method on book1 to print its details.

Q57      Define Access modifiers.

Ans:- Access modifiers are keywords that can be used to control the visibility of fields, methods, and constructors in a class. The four access modifiers in Java are public, protected, default, and private.

Note:- Data members of  a  class  can  be  accessed  from  outside  the  class  by  default. Private members of a class cannot be accessed outside the  class.

Q58     What is the use of User Data Input with example?

Ans:-  

            User Input in Java:

Scanner Class: If you want to get user input from the keyboard, the most common approach is to use the Scanner class from the java.util package.

Scanner Methods: The Scanner class provides various methods for reading different data types entered by the user. For example, nextInt() reads an integer, nextDouble() reads a double, and nextLine() reads a whole line of text (including spaces).

 import java.util.Scanner;

public class Main {

  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.print(“Enter your name: “);

    String name = scanner.nextLine();

    System.out.print(“Enter your age: “);

    int age = scanner.nextInt();

    System.out.println(“Hello, ” + name + “! You are ” + age + ” years old.”);

  }

}

Q59     Which packages are used for array manipulation?

Ans:- import Java.util.Arrays

Q60     Which of the method used for sorting a number using array?

Ans:- 

double[]  marks  =  {103,  144,  256.5,346,  387.5};

Arrays.sort(marks);

The marks array after sorting becomes = {103.0, 144.0, 256.5, 346.0, 387.5}. Sorting

makes it easier for us to find the lowest and highest marks obtained by a student. To print  the  lowest  marks,  we  can  now  write

System.out.println(marks[0]);

To  print  the  highest  marks, we  can  write

System.out.println(marks[marks.length-1]);

The  same  method  can  be  used  to  sort  an  array  of  Strings  in  alphabetic  order.

String[]  names  ={ ” M a y a n k ” , ” M u d i t ” , ” S h i v a ” , ” A n j u ” ,”Savita”};

Arrays.sort(names);

Q60     Which packages are used for String manipulation?

Ans:- package Java.lang

Q61      Write a table to show the common used String class methods.

Ans:-

MethodDescriptionApplication myString =“Hello World”Output
char charAt (int index)Return the character at the given indexmyString.charAt(6)W
String concat (String str)Concatenate the specified string at the end of this stringmyString.concat(”Today”)Hello World Today
boolean contains (String s)Returns true if this string contains the specified substringmyString.contains (”Hell”)True
boolean endsWith (String suffix)T est whether this string end with the given suffixmyString.endsWith (”old”)False
boolean equals (Object anObject)Compare this string with specified objectmyString.equals (”Goodbye World”)False
boolean equalsIgnoreCase (String another)Compare this string with specified string ignoring casemyString. equalsIgnoreCase (”hello world”)True
int indexOf (int c)Return the index of the first occurrence of given charactermyString. indexof (’W’)6
int indexOf (String str)Return the index of the first occurrence of given substringmyString. indexof (”rld”)8
boolean isEmpty()Returns true if the length of this string is 0myString. isEmpty()False
int length()Returns the length of the StringmyString. length ()11
String replace(char oldChar, char newChar)Returns a new string after replacing all occurrences of oldChar in this string with newCharmyString.replace (‘l’,’*’)He**o Wor*d
String replace(String oldStr, String newStr)Returns a new string after replacing all occurrences of oldStr in this string with newStrmyString.replace (”Hello”, “Yellow”)Yellow World
String toLowerCase()Converts all of the characters in this String to lower casemyString.toLower Case ( )hello world
String toUpperCase()Converts all of the characters in this String to upper casemyString.toLower Case ( )HELLO WORLD

Q:61     What is Getter and Setter methods in Java?

Ans:- Private data members of a class cannot be accessed outside the class, you can  give  controlled  access  to  data  members  outside  the  class  through  getter  and  setter methods.

                A getter method returns the value of a data member. For example we could

define  a  getter  method  in  the  Book class  for  the  price  data  member  as  given  below:

double  getPrice  (  )  {

return  price;

}

Similarly ,  we define  a  setter  method but  control  how  the  price  is  set.  We  do  not  allow a  book  price  to  become  lower  than  100.0

void  setPrice(double  newprice)  {

if  (newprice  <  100)

System.out.println(“Price  cannot  be  set  lower  than

100!”);

else

price  =  newprice;

}

Q62     Define the term Exception Handling.

Ans:- The Exception Handling in Java is one of the powerful mechanism to handle the

runtime errors so that the normal flow of the application can be maintained.

Q62  Which keyword used to handle an exception in Java?

Ans:- Java provides three keywords that are used to handle the exception.

  • Try
  • Catch
  • Finally

Q63  Explain Try and catch keyword.

Ans:-  try– A try block surrounds the part of the code that can generate exception

catch– The catch blocks follow a try block. A catch block contains the exception

handler – specific code that is executed when the exception occurs. Multiple catch

blocks following a try block can handle different types of exceptions.

Q64  Write the example of Java Exception Handling

Ans:-  Java Exception Handling Example

Let’s see an example of Java Exception Handling in which we are using a try-catch

statement to handle the exception.

JavaExceptionExample.java

public classJavaExceptionExample{

public static voidmain(String args[]){

try{

//code that may raise exception

intdata=100/0;

}catch(ArithmeticException e){System.out.println(e);}

//rest code of the program

System.out.println(“rest of the code…”);

}

}

Q65  Write the following terms –

a.  Assertions

b.  Threads

c.  Wrapper class

Ans:-

Assertions :-An assertion is a useful mechanism for effectively identifying/detecting and correcting logical errors in a program.

Threads :- A multithreaded program is one that can perform multiple tasks concurrently so that there is optimal utilization of the computer’s resources. A multithreaded program consists of two or more parts called threads each of which can execute a different task independently at the same time.

In Java, threads can be created in two ways

1. By extending the Thread class

2. By implementing the Runnable interface

Wrapper Class:- By default, the primitive datatypes (such as int, float, and so on) of Java are passed by value and not by reference. Sometimes, you may need to pass the primitive datatypes by reference. That is when you can use wrapper classes provided by Java. These classes wrap the primitive datatype into an object of that class.

public class Car {

  // Member variable using a primitive type (int)

  private int speed;

  // Constructor (no arguments)

  public Car() {

    speed = 0;

  }

  // Setter method using a wrapper class (Integer)

  public void setSpeed(Integer newSpeed) {

    // Validate speed (optional)

    if (newSpeed < 0) {

      System.out.println(“Error: Speed cannot be negative.”);

      return;

    }

    speed = newSpeed.intValue(); // Unboxing to access the primitive value

  }

  // Getter method using a wrapper class (Integer)

  public Integer getSpeed() {

    return Integer.valueOf(speed); // Boxing to create an Integer object

  }

  // Method to accelerate (demonstrates using the primitive value)

  public void accelerate() {

    speed += 10;

  }

}

public class Main {

  public static void main(String[] args) {

    Car car = new Car();

    // Set speed using setter (with validation)

    car.setSpeed(50);

    System.out.println(“Current speed: ” + car.getSpeed() + ” mph”); // Get speed using getter

    car.accelerate();

    System.out.println(“Speed after acceleration: ” + car.getSpeed() + ” mph”);

  }

}