0% found this document useful (0 votes)
75 views49 pages

Java Programming Basics for Grade 12

The document provides an overview of Java, including its definition, history, and key features such as object-oriented programming and platform independence. It explains fundamental concepts like classes, objects, the Java Virtual Machine (JVM), and the structure of a Java program, along with syntax, data types, operators, and control statements. Additionally, it highlights Java's applications, advantages, and the importance of comments and variables in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views49 pages

Java Programming Basics for Grade 12

The document provides an overview of Java, including its definition, history, and key features such as object-oriented programming and platform independence. It explains fundamental concepts like classes, objects, the Java Virtual Machine (JVM), and the structure of a Java program, along with syntax, data types, operators, and control statements. Additionally, it highlights Java's applications, advantages, and the importance of comments and variables in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Important notes Grade -12 Subject- IT Code-802

Q1: What is Java?


A1: Java is a popular, high-level programming language. Think of it as a set of instructions you give to a computer to
make it do specific tasks, like creating apps, websites, or even games. It's designed to be "write once, run anywhere,"
meaning code written in Java can work on different types of devices without needing changes.
Q2: Who created Java?
A2: Java was created by James Gosling and his team at Sun Microsystems (now Oracle) and released in 1995.
Q3: What makes Java special or popular?
A3: Java is popular because it's:
 Object-Oriented:
It organizes code into "objects" that represent real-world things, making it easier to manage and reuse.
 Platform Independent:
You can write Java code on one computer and run it on another, even if they have different operating systems (like
Windows, macOS, or Linux).
 Simple and Secure:
It's designed to be relatively easy to learn and includes features that enhance security.
 Versatile:
It's used for many things, including mobile apps (Android), web applications, desktop software, and large business
systems.
Q4: What is a "class" in Java?
A4: Imagine a blueprint for building a house. A "class" in Java is like that blueprint. It describes the characteristics
(data) and actions (methods) that objects of that class will have.
Q5: What is an "object" in Java?
A5: Following the house blueprint example, an "object" is an actual house built from that blueprint. In Java, an object
is a specific instance of a class, meaning it's a real item created based on the class's definition.
Q6: What does "JVM" stand for and what does it do?
A6: JVM stands for Java Virtual Machine. It's like a special program that translates your Java code (which is
compiled into "bytecode") into instructions that your computer can understand and execute. This is what enables
Java's "write once, run anywhere" capability.
Q7: What is the "main method" in a Java program?
A7: The main method is the starting point of any Java program. When you run a Java application, the computer looks
for and begins executing code from this method. It's like the "start" button for your program.
Q8: How do you print something in Java?
A8: You use the [Link]() statement to display text or values on the console. For example, to print "Hello,
World!":
Java
[Link]("Hello, World!");
Q9: Why is Java platform-independent?
A: Java code compiles into bytecode, which runs on the Java Virtual Machine (JVM), an abstract machine existing on
any OS, enabling "Write Once, Run Anywhere".
Q10: What are the applications of java?
A1: -Real-World Applications & Examples
Mobile: Android apps (Spotify, Uber, Netflix).
Web Apps: E-commerce, banking (using Servlets, Spring MVC).
Enterprise: Large-scale systems (Finance, Airlines).
Desktop: Standalone apps (e.g., Eclipse IDE).
Scientific: Big Data, AI/ML (Hadoop uses Java).
Q11: What are the advantages of java?
A1: - Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most popular programming languages in the world
It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has huge community support (tens of millions of developers)
Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering
development costs
As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa.

Q12: Explain jvm in java?


A1: - All language compilers translate source code into machine code for a specific computer.
Java is platform independent or machine neutral!!!
Java compiler produces an intermediate code (byte code or virtual machine code) for a machine that does not exist. That
machine is Java Virtual Machine (JVM).
JVM exists only inside the computer memory.
JVM is a simulated computer within the computer and does all major functions of real computer.
Q13. Explain the structure of java?

Q14 What is the basic syntax java?


A1: -Java Syntax
public class Main {
public static void main(String[] args) {
[Link]("Hello World");
}
}
Example explained
Every line of code that runs in Java must be inside a class. The class name should always start with an uppercase first
letter. In our example, we named the class Main.
The main Method
The main() method is required in every Java program. It is where the program starts running:
public static void main(String[] args)
Any code placed inside the main() method will be executed.
[Link]()
Inside the main() method, we can use the println() method to print a line of text to the screen:
Example
public static void main(String[] args) {
[Link]("Hello World");
}

Note: The curly braces {} mark the beginning and the end of a block of code.
[Link]() may look long, but you can think of it as a single command that means: "Send this text to the
screen."

System is a built-in Java class.

out is a member of System, short for "output".

println() is a method, short for "print line".

Finally, remember that each Java statement must end with a semicolon (;).

Q15: Define Statements in java.

A1: -A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.

The following statement "instructs" the compiler to print the text "Java is fun!" to the screen:

[Link]("Java is fun!");

It is important that you end the statement with a semicolon ;.

If you forget the semicolon (;), an error will occur and the program will not run:

Q16: Define java comments and explain types of comments in java.

A1: Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent
execution when testing alternative code.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

// This is a comment
[Link]("Hello World");

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

Example

/* The code below will print the words Hello World


to the screen, and it is amazing */
[Link]("Hello World");

Q17: Define variables and explain types of variable.


A1: -Variables are containers for storing data values.
In Java, there are different types of variables, for example:
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
boolean - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable in Java, you need to:
Choose a type (like int or String)
Give the variable a name (like x, age, or name)
Optionally assign it a value using =
Here's the basic syntax:
type variableName = value;
For example, if you want to store some text, you can use a String:
Example
Create a variable called name of type String and assign it the value "John".
Then we use println() to print the name variable:
String name = "John";
[Link](name);
To create a variable that should store a number, you can use int:
Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
[Link](myNum);

Q18: Explain different types of data types with example.


A1: -int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String

Data types are divided into two groups:

Primitive data types - includes byte, short, int, long, float, double, boolean and char

Non-primitive data types - such as String, Arrays and Classes

Primitive Data Types

A primitive data type specifies the type of a variable and the kind of values it can hold.

There are eight primitive data types in Java:


Data Type Description

byte Stores whole numbers from -128 to 127

short Stores whole numbers from -32,768 to 32,767

int Stores whole numbers from -2,147,483,648 to 2,147,483,647

long Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double Stores fractional numbers. Sufficient for storing 15 to 16 decimal digits

boolean Stores true or false values

char Stores a single character/letter or ASCII values

Numbers

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types
are byte, short, int and long. Which type you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals. There are two
types: float and double.

Boolean Types

Very often in programming, you will need a data type that can only have one of two values, like:

YES / NO

ON / OFF

TRUE / FALSE

For this, Java has a boolean data type, which can only take the values true or false:

Characters

The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or
'c':

Example

char myGrade = 'B';


[Link](myGrade);
Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects.

The main differences between primitive and non-primitive data types are:

Primitive types in Java are predefined and built into the language, while non-primitive types are created by the
programmer (except for String).

Non-primitive types can be used to call methods to perform certain operations, whereas primitive types cannot.

Primitive types start with a lowercase letter (like int), while non-primitive types typically starts with an uppercase
letter (like String).

Primitive types always hold a value, whereas non-primitive types can be null.

Q19: Explain different types of operators.


A1: -Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example:
int x = 100 + 50;
ava divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example Try it

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y


++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Here is an example using different arithmetic operators in one example:

int x = 10;

int y = 3;

[Link](x + y); // 13

[Link](x - y); // 7

[Link](x * y); // 30

[Link](x / y); // 3

[Link](x % y); // 1

Example: Multiply Two Floating-Point Numbers

public class MultiplyTwoNumbers {

public static void main(String[] args) {

float first = 1.5f;


float second = 2.0f;

float product = first * second;

[Link]("The product is: " + product);


}
}

Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
int x = 10;
Example: Swap two numbers using temporary variable

public class SwapNumbers {

public static void main(String[] args) {


float first = 1.20f, second = 2.45f;
[Link]("--Before swap--");
[Link]("First number = " + first);
[Link]("Second number = " + second);

// Value of first is assigned to temporary


float temporary = first;

// Value of second is assigned to first


first = second;

// Value of temporary (which contains the initial value of first) is


assigned to second
second = temporary;

[Link]("--After swap--");
[Link]("First number = " + first);
[Link]("Second number = " + second);
}
}

Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because it
helps us to find answers and make decisions.

The return value of a comparison is either true or false. These values are known as Boolean values, and you will learn
more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

int x = 5;
int y = 3;
[Link](x > y); // returns true, because 5 is higher than 3

A list of all comparison operators:


Operator Name Example Try it

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Real-Life Examples
Comparison operators are often used in real-world conditions, such as checking if a person is old enough to vote:

Example
int age = 18;

[Link](age >= 18); // true, old enough to vote

[Link](age < 18); // false

Logical Operators
As with comparison operators, you can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values, by combining multiple conditions::

Operator Name Description Example Try it


&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is x < 5 || x < 4


true

! Logical not Reverse the result, returns false if the !(x < 5 && x <
result is true 10)

Q20: Explain java conditions and statements.


A1:- Conditions and if statements let you control the flow of your program - deciding which code runs, and which
code is skipped.

Think of it like real life: If it rains, take an umbrella. Otherwise, do nothing.

Every if statement needs a condition that results in true or false.

This means if statements work hand-in-hand with boolean values:

boolean isRaining = true;

if (isRaining) {

[Link]("Bring an umbrella!");

Else Statement

The else statement lets you run a block of code when the condition in
the if statement is false.

Syntax
if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

Think of it like real life: If it rains, bring an umbrella. Otherwise (else), go outside
without one:
Example
boolean isRaining = false;

if (isRaining) {

[Link]("Bring an umbrella!");

} else {

[Link]("No rain today, no need for an umbrella!");

Example: Check number is even or odd.


import [Link];

public class Odd_Even

public static void main(String[] args)

int n;

Scanner s = new Scanner([Link]);

[Link]("Enter the number you want to check:");

n = [Link]();

if(n % 2 == 0)

[Link]("The given number "+n+" is Even ");

}
else
{

[Link]("The given number "+n+" is Odd ");

}
}
}
Example: Check number is positive or negative.
import [Link];

public class Postive_Negative

public static void main(String[] args)

int n;

Scanner s = new Scanner([Link]);

[Link]("Enter the number you want to check:");

n = [Link]();

if(n > 0)

[Link]("The given number "+n+" is Positive");

else if(n < 0)

[Link]("The given number "+n+" is Negative");

}
else
{

[Link]("The given number "+n+" is neither Positive nor Negative ");

}
}
}

Nested If

You can also place an if statement inside another if. This is called a nested
if statement.

A nested if lets you check for a condition only if another condition is already true.

Syntax
if (condition1) {

// code to run if condition1 is true


if (condition2) {

// code to run if both condition1 and condition2 are true

Example
In this example, we first check if x is greater than 10. If it is, we then check if y is
greater than 20:

Example
int x = 15;

int y = 25;

if (x > 10) {

[Link]("x is greater than 10");

// Nested if

if (y > 20) {

[Link]("y is also greater than 20");

Result:

x is greater than 10
y is also greater than 20

Q20: Explain switch statements with example.


A1:-Instead of writing many if..else statements, you can use the switch statement.

Think of it like ordering food in a restaurant: If you choose number 1, you get Pizza. If you choose 2, you get a
Burger. If you choose 3, you get Pasta. Otherwise, you get nothing.

The switch statement selects one of many code blocks to be executed:


Syntax
switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

This is how it works:

 The switch expression is evaluated once.


 The result is compared with each case value.
 If there is a match, the matching block of code runs.
 The break statement stops the switch after the matching case has run.
 The default statement runs if there is no match.

The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;

switch (day) {

case 1:

[Link]("Monday");

break;

case 2:

[Link]("Tuesday");

break;

case 3:

[Link]("Wednesday");
break;

case 4:

[Link]("Thursday");

break;

case 5:

[Link]("Friday");

break;

case 6:

[Link]("Saturday");

break;

case 7:

[Link]("Sunday");

break;

// Outputs "Thursday" (day 4)

Q21: Explain loops and types.


A1:-Java For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop instead of
a while loop:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

Print Numbers
The example below will print the numbers 0 to 4:
Example
for (int i = 0; i < 5; i++) {
[Link](i);
}
[Link] [Link];
[Link] class Multiplication_Table
3.{
4. public static void main(String[] args)
5. {
6. Scanner s = new Scanner([Link]);
7. [Link]("Enter number:");
8. int n=[Link]();
9. for(int i=1; i <= 10; i++)
10. {
11. [Link](n+" * "+i+" = "+n*i);
12. }
13. }
14. }

Loops
Loops can execute a block of code as long as a specified condition is true.

Loops are handy because they save time, reduce errors, and they make code more
readable.

Java While Loop


The while loop repeats a block of code as long as the specified condition is true:

SyntaxGet your own Java Server


while (condition) {

// code block to be executed

In the example below, the code in the loop will run again and again, as long as a
variable (i) is less than 5:

Example
int i = 0;

while (i < 5) {
[Link](i);

i++;

}
import [Link];
public class Reverse_Number
{
public static void main(String args[])
{
int m, n, sum = 0;
Scanner s = new Scanner([Link]);
[Link]("Enter the number:");

m = [Link]();
while(m > 0)
{
n = m % 10;
sum = sum * 10 + n;
m = m / 10;
}
[Link]("Reverse of a Number is "+sum);
}
}

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true. Then it will repeat the loop as
long as the condition is true.

SyntaxGet your own Java Server


do {

// code block to be executed

while (condition);

Note: The semicolon ; after the while condition is required!

Do/While Example
The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:

Example
int i = 0;
do {

[Link](i);

i++;

while (i < 5);

Q22: Explain break and continue statements.


A1:-

Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of
a switch statement.

The break statement can also be used to jump out of a loop.

This example stops the loop when i is equal to 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

[Link](i);

Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {
continue;

[Link](i);

Q23: Explain array and types of array.

A1:- Java Arrays


Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets [ ] :

String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it,
you can place the values in a comma-separated list, inside curly braces { }:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You can access an array element by referring to the index number.
This statement accesses the value of the first element in cars:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

[Link](cars[0]);

// Outputs Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.

Think of an array as numbered boxes, where each box stores an element:

Index Element
0 Volvo

1 BMW

2 Ford

3 Mazda

Change an Array Element


To change the value of a specific element, refer to the index number:

cars[0] = "Opel";

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

[Link](cars[0]);

// Now outputs Opel instead of Volvo

Array Length
To find out how many elements an array has, use the length property:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

[Link]([Link]);

// Outputs 4
Loop Through an Array
You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.

This example creates an array of strings and then uses a for loop to print each
element, one by one:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < [Link]; i++) {

[Link](cars[i]);

Q24: What is OOP and explain advantages of oop.


A1:-OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the data, while object-
oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

OOP is faster and easier to execute

OOP provides a clear structure for the programs

OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and
debug

OOP makes it possible to create full reusable applications with less code and shorter development time

Q25: What are classes and explain objects.


A1:- Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and objects:

Class Fruit

Objects Apple Banana Mango

Another example:

Class Car

Objects Volvo Audi Toyota

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and methods from the class.
Java Classes/Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real
life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class.

In this example, we create a class named "Main" with a variable x:


[Link]

public class Main {

int x = 5;

Create an Object
In Java, an object is created from a class. We have already created the class named Main, so now we can use this to
create objects.

To create an object of Main, specify the class name, followed by the object name, and use the keyword new:

Example
Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

[Link](myObj.x);

Q26: Explain wrapper class with example.


A:-Wrapper class is used to convert any datatype in to object.
The primitive datatypes are not object. They do not belong to any class. They are defining in the language itself.
Sometimes, it is required to convert datatype into object in java.
For example: - In a java Vector class does not support primitive datatype. So, we have to compulsory convert primitive
datatype into object.
Wrapper class solves converting simple type.

Primitive Datatype Wrapper Class


boolean Boolean
char Character
double Double
float Float

int Integer

long Long
Example:
class WrapperDemo
{
public static void main(String args[ ])
{
int a=10;
Integer i=[Link](a); [Link](“a=”+a+”i=”+i);
}
}

Q27: Explain life cycle of Thread.


A:- There are five states in Thread life cycle.
1) Newborn state
2) Runnable state
3) Running state
4) Blocked state
5) Dead state
New born state

When we create a thread object, the thread is born and is said to be in newborn state.

The thread is not still scheduled for running.

Runnable state

The next state after the newborn state is Runnable state.

Runnable state means that the thread is ready for execution and is waiting for the availability of the processor.

The threads has joined waiting queue for execution based on priority of thread.

Running state

Running means that processor has given its time to the thread for its execution.

A running thread may change its state to another state using resume (), modify (), sleep (), wait () methods etc.

Blocked state

A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the
running state.

This happens when the thread is suspended, sleeping or waiting in order to satisfy certain requirements.

Dead state

Every thread has a life cycle. A running thread ends its life when it has completed executing its run ( ) method.

It is natural death. However we can kill it by sending the stop message to it as any state thus causing a premature
death for it.

Q28: Define package and write a steps to create package.


A:- Package:

Packages are grouping of variety of classes and/or Interfaces together.

Packages are conceptually similar as “class libraries “of other languages.

Packages act as “containers” for classes.

Java packages are classified into two types

Java API packages or system defined package

User defined packages

Steps to create user-defined package

Declare the package at the beginning of file using ,

Syntax : package packagename ;

Define the class that is to be put in the package and declare it public.

Create a subdirectory under the directory where the all main source files are stored.

Store the listing file as the [Link] file in subdirectory you have created.
Compile that file. This will create .class file in subdirectory.

Example:

File1: saved in D:\javapro\package1\[Link]


package package1; public class
ClassA
{
public void displayA ()
{
[Link] (“Class A”);
}
}

File2: saved in D:\javapro\[Link]

import [Link]; class PackageTest


{
public static void main (String args [])
{
ClassA objA=new ClassA (); objA. displayA ();
}
}
Output: Class A

Q29: Explain Exception Handling.


A1- An Exception is abnormal condition that is caused by a runtime error in the program.

The purpose of exception handling is to provide a means to detect and report an “abnormal condition “so we
can take proper actions.

Error handling code consist of two segments

Detect errors and to throw exceptions

Catch the exceptions and take appropriate actions

This mechanism performs following tasks in sequence.

Find the problem (Hit the Exception).

Inform that an error has occurred (Throw the Exception).

Receive the error information catch the exception)


Take corrective actions (Handle the Exception).

Exception Handling Code (Try Catch)

The basic concept of Exception handling are throwing an exception and catching it.

Q29: Define different types of errors.

Compile time errors. Run time errors.

Errors which are detected by javac at the compilation time of Errors which are detected by java interpreter at the time of
program are known as compile time errors. program are known as run time errors.

It is detected by javac (compiler) at compile It is detected by java (interpreter) at


time. rum time.
Whenever compiler displays an error, it will not create A program compiled successfully and creates a .class file
the .class file. but may not run properly.

Compile Time Errors are: Run time errors are:


Missing semicolon Dividing an integer by zero. Accessing element that is
Missing or mismatch of brackets in classes and methods out of the bounds of an array.
Misspelling of identifiers and keywords Missing double quotes Trying a store a value into an array of an
in strings incompatible class or type.
Use of undeclared variables

Example: Example:
class Error1 class Error2
{ {
public static void main(String args[]) public static void main(String args[])
{ {
[Link](“Hello”) int a=10,b=5 ,c=5;
//Missing ; int x = a / (b-c); // division by zero [Link](“x=“
} + x);
} int y = a / (b+c); [Link](“y=“ + y);
}}
Q30: Write a program for generating Exception “Divided by Zero”.

class Error3
{
public static void main (String args[])
{
int a=10,b=5,c=5; int x,y;
try
{
X=a / (b-c); //Exception here
}
Catch (ArithmeticException e)
{
[Link] (“division by zero”);
}
Y= a / (b +c );
[Link] (“y=”+y);
}
}
Output:
Division by zero y=1

Q31: What is Constructor? Explain any one with example.


A: Same name as class name is known as Constructor.
Constructor is a special Type of method.
Constructor does not have any return type not even Void.
There are three Type of Constructor
Default Constructor
Parameterize Constructor
Copy Constructor
Default Constructor
When user does not define any type of Constructor then Java create System define constructor which is known as
Default Constructor.
Example:

class A
{
A( )
{
[Link](“This is Default Constructor”);
}
void display( )
{
[Link](“This is Simple Method”);
}
}
class Testc
{
public static void main(String args[ ])
{
A a1=new A( ); [Link]( );
}
}

Q32: Define access specifier.


Modifiers

By now, you are quite familiar with the public keyword that appears in almost all of our examples:

public class Main

The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes,
methods and constructors.

We divide modifiers into two groups:

Access Modifiers - controls the access level

Non-Access Modifiers - do not control access level, but provides other functionality

Access Modifiers

For classes, you can use either public or default:


Modifier Description

public The class is accessible by any other class

default The class is only accessible by classes in the same package. This is used when you don't specify a
modifier. You will learn more about packages in the Packages chapter

For attributes, methods and constructors, you can use the one of the following:

Modifier Description

public The code is accessible for all classes

private The code is only accessible within the declared class

default The code is only accessible in the same package. This is used when you don't specify a
modifier.

protected The code is accessible in the same package and subclasses.

Public vs. Private Example


In the example below, the class has one public attribute and one private attribute.

Think of it like real life:

 public - a public park, everyone can enter


 private - your house key, only you can use it

Example
class Person {
public String name = "John"; // Public - accessible everywhere

private int age = 30; // Private - only accessible inside


this class

public class Main {

public static void main(String[] args) {

Person p = new Person();

[Link]([Link]); // Works fine

[Link]([Link]); // Error: age has private access in


Person

Example explained
Here, name is declared as public, so it can be accessed from outside the Person class.
But age is declared as private, so it can only be used inside the Person class.

Q33: What is Encapsulation? Explain Getter and Setter Methods.

A1:- The meaning of Encapsulation, is to make sure that "sensitive" data is hidden
from users. To achieve this, you must:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of
a private variable

Get and Set


You learned from the previous chapter that private variables can only be accessed
within the same class (an outside class has no access to it). However, it is possible to
access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case:

Example
public class Person {

private String name; // private = restricted access


// Getter

public String getName() {

return name;

// Setter

public void setName(String newName) {

[Link] = newName;

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from


outside this class:

Example
public class Main {

public static void main(String[] args) {

Person myObj = new Person();

[Link] = "John"; // error

[Link]([Link]); // error

If the variable was declared as public, we would expect the following output:

John

However, as we try to access a private variable, we get an error:

[Link][Link] error: name has private access in Person


[Link] = "John";
^
[Link][Link] error: name has private access in Person
[Link]([Link]);
^
2 errors

Instead, we use the getName() and setName() methods to access and update the
variable:

Example
public class Main {

public static void main(String[] args) {

Person myObj = new Person();

[Link]("John"); // Set the value of the name variable to


"John"

[Link]([Link]());

// Outputs "John"

Q 34: What are the Features of OOPs?


OOP in Java revolves around four main pillars:
Encapsulation: Bundling data and methods together in a class and controlling access (like using private fields and
public getters/setters).
Inheritance: One class can inherit properties and methods from another (like a child inheriting traits from a parent).

Polymorphism: Objects can take on multiple forms—like a method behaving differently based on the object calling
it.
Abstraction: Hiding complex details and showing only the necessary parts (like using an interface to simplify
interactions).
These make your code flexible, secure, and easier to work with.
Important Question-Answer

1. What is Variable?
Answer – A variable is a storage location for information whose value may vary while a programme is running. A
variable is, technically speaking, the name of a storage area in the computer’s internal memory. The data present
there serves as the variable’s value.

2. What are the different Variable naming rules in Java?


Answer – The variable naming rules in Java are –
a. Variable names can begin with either an alphabetic character, an underscore, or a dollar sign.
b. Space is not allowed in variable names.
c. Reserved words are not used in variables.
d. Java is a case-sensitive language.

3. What are the different Primitive Data Types in Java?


Answer – There are eight different types of primitive data types in Java.
a. Byte
b. Short
c. Int
d. Long
e. Float
f. Double
g. Char
h. Boolean

4. What is String Variable?


Answer – String variables, also known as alphanumeric or character variables, have values that are interpreted as text.
In other words, string variables’ values could be made up of letters, numbers, or symbols.

5. What is Operator and what are the different types of Operator?


Answer – Operators are special symbols in a programming language and perform certain specific operations. Java
support –
a. Arithmetic Operators : +, -, *, /, %, ++, —
b. Relational Operators : ==, !=, >, <, >=, <=
c. Assignment Operators : =, +=, -=, *=, /=, %=
d. Logical Operators : &&, ||, !

6. Difference between Entry control loop and Exit control loop.


Answer – Difference between entry control and Exit control loop are –
Entry Control Loop –
a. Entry Control Loop tests the condition first and then executes the body of the loop.
b. If the condition is false, Entry control loop will not execute
c. Example of entry control loop are – for loop and while loop

Exit Control Loop –


a. Exit Control loop tests the condition after running a block of code.
b. If the condition is false, the Entry control loop will execute at least one time.
c. Example of entry control loop are – do-while

7. What is an Array?
Answer – Arrays are variables that can hold more than one value, they can hold a list of values of the same type.
Example – marks = new double[5];
8. What is the purpose of user defined methods?
Answer – User-defined functions are techniques you can use to arrange your code within a body. Once a function has
been defined, it can be used in the same way that the built-in action and parser functions are used. Instead of being
passed by value, variables are passed by reference to functions.

9. What are OOPs?


Answer – OOPs stands for Object Oriented Programming, Java is an Object Oriented Programming (OOP) language.
In an OOP language, a program is a collection of objects that interact with other objects to solve a problem. Each
object is an instance of a class.

10. What is the difference between local and global variables?


Answer – Depending on their scope, variables are divided into global variables and local variables. Local variables
can only be accessed within the function or block in which they are defined, In other hand the global variables, which
can be used worldwide throughout the entire programme.

11. What is the purpose of Constructor in Java?


Answer – A special method member called the constructor method is used to initialize the data members of the class
(or any other initialization is to be done at time of object creation). The constructor has the same name as the class,
has no return type, and may or may not have a parameter list. Whenever a new object of a class is created, the
constructor of the class is invoked automatically. We do not call the constructor explicitly.

12. What are the different types of Access Modifiers?


Answer – Access modifiers are keywords that manage a class’s fields, methods, and function. Examples of access
modifiers are Public, protected, and private.

13. What is the purpose of Getter and Setter Methods?


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

In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of

characters 'h', 'e', 'l', 'l', and 'o'.

We use double quotes to represent a string in Java. For example,

// create a string
String type = "Java programming";

Here, we have created a string variable named type . The variable is initialized with the
string
Example: Create a String in Java
class Main {
public static void main(String[] args) {

// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";

// print strings
[Link](first); // print Java
[Link](second); // print Python
[Link](third); // print JavaScript
}
}

Java String Operations


Java provides various string methods to perform different operations on strings. We will
look into some of the commonly used string operations.

1. Get the Length of a String


To find the length of a string, we use the length() method. For example,
class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
[Link]("String: " + greet);

// get the length of greet


int length = [Link]();

[Link]("Length: " + length);


}
}
Run Code

Output

String: Hello! World


Length: 12

In the above example, the length() method calculates the total number of characters in
the string and returns it.

2. Join Two Java Strings


We can join two strings in Java using the concat() method. For example,
class Main {
public static void main(String[] args) {

// create first string


String first = "Java ";
[Link]("First String: " + first);

// create second
String second = "Programming";
[Link]("Second String: " + second);

// join two strings


String joinedString = [Link](second);

[Link]("Joined String: " + joinedString);


}
}
Run Code

Output

First String: Java


Second String: Programming
Joined String: Java Programming

In the above example, we have created two strings named first and second . Notice
the statement,

String joinedString = [Link](second);

Here, the concat() method joins the second string to the first string and assigns it to
the joinedString variable.
3. Compare Two Strings
In Java, we can make comparisons between two strings using the equals() method.
For example,
class Main {
public static void main(String[] args) {

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = [Link](second);

[Link]("Strings first and second are equal: " + result1);

// compare first and third strings


boolean result2 = [Link](third);

[Link]("Strings first and third are equal: " + result2);


}
}
Run Code

Output

Strings first and second are equal: true


Strings first and third are equal: fal
1. JVM Stands for ___________.
a. Java Virtual Machine
b. Java Verify Machine
c. Java Vector Machine
d. None of the above
2. Java programs are _____________.
a. Platform Independent
b. Highly Portable
c. Both a) and b)
d. None of the above
3. Java support __________.
a. Compiler
b. Interpreter
d. Assembler
e. None of the above
4. Java converts the program in __________.
a. Byte
b. Megabyte
c. Bytecode
d. None of the above
5. IDE Stands for __________.
a. Integrated Developer Environments
b. Integrated Development Environments
c. Internal Developer Environments
d. Internal Development Environments
6. Java NetBeans IDE is ________ software.
a. Close source
b. Middle source
c. Open Source
d. None of the above
7. How we can write comments in Java programs.
a. Two forward slashes (//)
b. /* and */
c. Both a) and b)
d. None of the above
8. In Java a group of related classes is known as _______.
a. Group
b. Package
c. Method
d. None of the above
9. In Java most common pre-built Java output methods are ___________.
a. [Link]();
b. Public class
c. Public static void main(String[] args)
d. None of the above
10. A Variable is a placeholder for data that can change its value during program execution.
a. Constant
b. Variable
c. Data type
d. None of the above
11. In Java, How many types of primitive Data Type.
a. 6
b. 7
c. 8
d. 9
12. In Java, Which type of datatype is used to store Integer values.
a. Byte
b. Int
c. Long
d. All of the above
13. Int Data Type can store ________ bit of data.
a. 8-bit
b. 16-bit
c. 32-bit
d. 64-bit
14. Float Data Type can store ________ bit of data.
a. 8-bit
b. 16-bit
c. 32-bit
d. 64-bit
15. Double Data Type can store ________ bit of data.
a. 16-bit
b. 32-bit
c. 64-bit
d. 8-bit
16. Char Datatype can store _________ bit of data.
a. 16-bit
b. 32-bit
c. 64-bit
d. 8-bit
17. Boolean Data Type can store _________ bit of data.
a. 16-bit
b. 32-bit
c. 1-bit
d. 8-bit
18. What are the naming rules we have to follow to declare a variable.
a. Variable names can begin with either an alphabetic character, Underscore or a dollar sign.
b. Space are not allowed in variable names
c. Reserved words cannot be used as a variable name
d. All of the above
19. To store more than one character, we use the _______ data type.
a. Integer
b. Character
c. String
d. None of the above
20. ___________ are special symbols in a programming language and perform certain specific operations.
a. Operators
b. Variable
c. Datatype
d. None of the above
21. ++ is known as which operator.
a. Increment Operator
b. Decrements Operator
c. Assignment Operator
d. Modulus
22. Which of the following belongs to logical operators.
a. &&
b. ||
c. !
d. All of the above
23. Which of the following is an example of selection structures.
a. If else statement
b. Switch statement
c. Else if statement
d. All of the above
24. The __________ in Java lets us execute a block of code depending upon whether an expression evaluates to true or
false.
a. If statements
b. For statements
c. Array Statements
d. None of the above
25. To combine two relational expressions in a program.
a. Logical OR
b. Logical AND
c. Logical NOT
d. None of the above
26. If inside the if is known as _________.
a. Outer If
b. Inner If
c. Nested If
d. All of the above
27. The ____________ is used to execute a block of code matching one value out of many possible values.
a. If statement
b. Switch Statement
c. For Statement
d. None of the above
28. The ability of a computer to perform the same set of actions again and again is called looping.
a. Looping
b. Actioning
c. Performing
d. None of the above
29. What are the different looping statements available in Java?
a. For loop
b. While loop
c. Do-while loop
d. All of the above
30. The ________ statement evaluates the test before executing the body of a loop.
a. Goto
b. While loop
c. Do-while loop
d. All of the above
31. The __________ statement evaluates the test after executing the body of a loop.
a. Goto
b. While loop
c. Do-while loop
d. All of the above
32. _________ is known as the entry control loop.
a. While loop
b. Do-while loop
c. Goto loop
d. All of the above
33. __________ is known as the exit control loop.
a. While loop
b. Do-while loop
c. Goto loop
d. All of the above
34. Which condition required for executing the loop –
a. Initial value
b. Condition
c. Counter
d. All of the above
35. __________ are variables that can hold more than one value, they can hold a list of values of the same type.
a. Loop
b. Constant
c. Variable
d. None of the above
36. __________ helps to create a tab between the numbers in the print statement.
a. \tt
b. \t
c. \tb
d. \tab
37. Array addresses always start from _________.
a. 0
b. 1
c. 2
d. 3
38. OOP Stands for ____________.
a. Object Oriented Programming
b. Outer Oriented Programming
c. Outer Object Programming
d. Oriented Object Programming
39. Java’s most fundamental features are _________.
a. Class
b. Objects
c. Both a) and b)
d. None of the above
40. Function declared inside the class is known as __________.
a. Member function
b. Inner function
c. Outer function
d. None of the above
41. The body of class is enclosed within ____________.
a. Small braces
b. Curly braces
c. Big braces
d. None of the above
42. The variable declared outside the class is known as ___________.
a. Local variable
b. Global variable
c. Inner variable
d. All of the above
43. The variable declared inside the class is known as __________.
a. Local variable
b. Global variable
c. Inner variable
d. All of the above
44. __________ is a data member that is declared but not initialized before using, and is assigned a default value by the
compiler, usually either zero or null.
a. Class
b. Object
c. Constructors
d. None of the above
45. __________ has the same name as the class.
a. Class
b. Object
c. Constructors
d. None of the above
46. Data members and method members of an object are accessed using the _________ operator.
a. Comma (,)
b. Dot (.)
c. Modular (%)
d. Dollar ($)
47. Data members of a class can be accessed from outside the class by default. Identify the access modifiers from the
below list __________.
a. Private
b. Public
c. Protected
d. All of the above
48. Private data members of a class cannot be accessed outside the class however, you can give controlled access to data
members outside the class through ____________.
a. Getter
b. Setter
c. Both a) and b)
d. None of the above
49. To import the class from the package, you have to use ____________ keyword.
a. Insert
b. Import
c. Add
d. None of the above
50. We can take input from the user using ___________ object.
a. Scanner
b. [Link]();
c. Both a) and b)
d. None of the above
51. _________ function helps to convert string value to the integer value in Java.
a. parseInt();
b. parseDouble()
c. parseString();
d. None of the above
52. To sort the array of integers in ascending order _______ function required.
a. Arrange()
b. Filter()
c. Sort()
d. None of the above
53. __________ function helps to convert all of the characters in lower case.
a. toLowerCase()
b. toSmallCase()
c. to BelowCase()
d. None of the above
54. __________ function helps to convert all the characters in Upper case.
a. toUpperCase()
b. toCaptialCase()
c. touppercase()
d. None of the above
55. __________ function helps to return a new string after replacing all occurrences of old string.
a. replace()
b. Change()
c. Convert()
d. None of the above
56. ________ function helps to return the length of the string.
a. replace()
b. isEmpty()
c. indexOf()
d. None of the above
57. _______ function helps to return the index of the first occurrence of a given substring.
a. length()
b. isEmpty()
c. indexOf()
d. None of the above
58. When unexpected errors come in the program it is handled by ___________.
a. Error handling
b. Exception handling
c. Both a) and b)
d. None of the above
60. Which keywords handle an exception in Java programming.
a. Try
b. Catch
c. Both a) and b)
d. None of the above
61. _________ helps to access the network services that are running on the local computer.
a. Localhost
b. Local Network
c. network
d. None of the above
62. What are the different ways to create threads in Java?
a. By extending the Thread class
b. By implementing the Runnable interface
c. Both a) and b)
d. None of the above
63. A ______________ is one that can perform multiple tasks concurrently so that there is optimal utilization of
the computer’s resources.
a. Resources program
b. Multithreaded program
c. Class program
d. None of the above
64. What are the different types of passing values in Java?
a. Pass by value & not Pass by reference
b. Pass by data & Pass by address
c. Pass by String & Pass by reference
d. None of the above
65. What are the basic idea in exception handling ____________.
a. Denote an exception block
b. Catch the exception
c. Handle the exception
d. All of the above
66. ___________ a file format based on the popular ZIP file format and is used for aggregating many files into one.
a. Java ARchive (JAR)
b. Java Bin (JB)
c. Java Method (JM)
d. None of the above
67. JDBC Stands for ___________.
a. Java Data Connection
b. Java Database Connection
c. Java Database Connectivity
d. Java Data Connectivity

You might also like