0% found this document useful (0 votes)
21 views

Java 1

Uploaded by

ssimmply862
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java 1

Uploaded by

ssimmply862
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1. What is the output of the below code?

If you insert another ‘int x’ before the for loop, what will be
the output?

class examp {
public static void main(String s[]) {
int s;
for( s=0;s<3;s++) {
int x = -1;
System.out.println(“ ” + x);
x = 50;
System.out.println(“ ” + x);
}
}
}

The output of the code will be a compilation error. This is because the variable ‘s’ has been passed as an
argument in the main method. The same variable name is then being used as an integer for iteration.
Upon adding another ‘int x’ before the for-loop, it will throw another compilation error, as the same variable
‘x’ is being declared twice.

2. Write a program to calculate the average among the elements {4,5,7,8} using for-each in Java. How
for-each is different from for loop?
Class For_each_Demo{
public static void main(String[] args){
int arr[] = {4,5,7,8};
int total = 0;
for (int temp : arr){
total += temp;
}
int avg = total/4;
System.out.println(“Average: ”+ avg);
}
}

 For-each is a looping statement like for loop. Instead of declaring and initializing the loop
counter, a variable is declared that is the same type as the base type of the array.
 It is commonly used to iterate over an array.
 They are not appropriate when an array must be modified.
 They do not keep track of index or the array.
 For-each only iterates forward in steps of one.
 It cannot process two decision-making statements at once.
3. Differentiate literal and whitespace.

Aspect Literals Whitespace


Used for formatting, separating tokens, and
Definition Represent constant values directly in code.
readability in code.
Examples int number = 42; int x = 5 + 3;<br>String message = "Hello, world!";
Purpose Provide specific values for variables. Improve code readability and structure.
Numeric literals (int, double), char, string,
Types Spaces, tabs, newline characters.
etc.
Used in variable assignments and
Usage Used to separate and organize code elements.
expressions.
Syntax Direct representation of values in code. Absence of code logic; used for visual separation.
Importance Essential for defining specific data values. Enhances code readability and maintainability.
Values may change based on program
Modification Alters for code formatting, not program logic.
requirements.

4. List and explain the features of JAVA.

Simple and Easy to Learn:


Java was designed to be easy to use and has a syntax similar to C++. It eliminates complex features such
as pointers, operator overloading, etc., making it simpler for developers to learn and use.

Object-Oriented:
Java follows the object-oriented programming paradigm. Everything in Java is treated as an object,
which allows for better code organization, reusability, and modularity.

Platform Independence (Write Once, Run Anywhere - WORA):


Java is platform-independent, meaning that Java programs can run on any device or operating system
without modification. This is achieved using the Java Virtual Machine (JVM), which interprets Java
bytecode.

Multithreading:
Java supports multithreading, allowing multiple threads of execution to run concurrently within a
program. This feature is useful for creating efficient and responsive applications, especially in scenarios
where tasks can be performed in parallel.

Robust and Secure:


Java incorporates features like strong memory management, exception handling, and a robust type-
checking mechanism, making it a robust and secure programming language. The platform also includes a
security manager to control access to resources.

Automatic Memory Management (Garbage Collection):


Java automatically manages memory through garbage collection. This process identifies and removes
unused objects, preventing memory leaks and making memory management more convenient for
developers.
5. Java Bytecode is the key to solve security and portability problems. Justify.

Platform Independence:
Java bytecode is an intermediate representation of the source code that is generated by the Java
compiler. This bytecode is not tied to any specific hardware or operating system. Instead, it is designed
to be executed on the Java Virtual Machine (JVM), which abstracts away the underlying platform details.
This abstraction ensures that a Java program written and compiled once can run on any device or
operating system with a compatible JVM, achieving the "Write Once, Run Anywhere" (WORA) principle.
This inherent platform independence enhances portability.

Security through the JVM:


The JVM acts as a sandbox for executing Java bytecode. It provides a secure execution environment by
enforcing access controls, memory management, and other security measures.

Bytecode Verification:
Before executing Java bytecode, the JVM performs bytecode verification. This process ensures that the
bytecode adheres to certain safety and security constraints.

6. Java is Robust language. Justify

Memory Management:
Java features automatic memory management through garbage collection. This process helps prevent
memory leaks and enhances the robustness of programs by automatically deallocating memory
occupied by objects that are no longer in use. Developers do not need to manually manage memory,
reducing the risk of memory-related errors.

Exception Handling:
Java has a robust exception-handling mechanism, making it easier to handle and recover from
unexpected runtime errors. This approach promotes more resilient code, as developers can catch and
handle exceptions, preventing program crashes and improving overall reliability.

Strong Type Checking:


Java enforces strong type checking during both compile-time and runtime. This means that variable
types are strictly checked, reducing the likelihood of type-related errors. The compiler catches many
potential issues before the program is executed, leading to more robust and reliable code.

Object-Oriented Nature:
Java's object-oriented programming (OOP) paradigm promotes modularity, encapsulation, and code
reusability. These principles contribute to the development of robust and maintainable software.
Objects encapsulate data and behavior, making it easier to manage and extend code without affecting
the entire system.

Compile-Time Checks:
Java's strong static typing and compile-time checks catch many errors before the program runs. This
early detection of potential issues helps developers identify and fix problems during the development
phase, reducing the likelihood of runtime errors.
7. Explain i) >> ii) >>> with example.

8. Explain : i) JVM ii) Type Casting

JVM : Java Virtual Machine


 It is a java run-time system which runs the java programs.
 It was originally designed as an interpreter for the bytecode.
 It is in control of the execution of the programs.
 It also contains a JIT compiler which compiles only the selected portions of the code.
Typecasting :
 Converting from one datatype to another data type is called typecasting.
 Since java is a strictly typed language, it only allows widening conversions.
 For literal values automatic conversion takes place from short, byte or char to int while
evaluating an expression.

9. Discuss three OOPs principles.

Encapsulation:
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together the
code and the data it manipulates. Another way to think about encapsulation is that it is a protective
shield that prevents the data from being accessed by the code outside this shield.
In encapsulation, the data in a class is hidden from other classes, which is similar to what data-hiding
does. So, the terms “encapsulation” and “data-hiding” are used interchangeably.
Encapsulation can be achieved by declaring all the variables in a class as private and writing public
methods in the class to set and get the values of the variables.

Inheritance:
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in Java by
which one class is allowed to inherit the features (fields and methods) of another class. We are achieving
inheritance by using extends keyword.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and methods of the existing class.

Polymorphism:
It refers to the ability of object-oriented programming languages to differentiate between entities with
the same name efficiently. This is done by Java with the help of the signature and declaration of these
entities. The ability to appear in many forms is called polymorphism.

Abstraction:
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.
The trivial or non-essential units are not displayed to the user. Ex: A car is viewed as a car rather than its
individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an
object, ignoring the irrelevant details. The properties and behaviors of an object differentiate it from
other objects of similar type and help in classifying/grouping the object.
10. List and explain the java buzzwords.

Simple:
Java was designed to be easy to use and uncomplicated. It eliminates complexities such as explicit
memory management and pointer manipulation found in other languages.
Object-Oriented:
Java is built on the principles of object-oriented programming (OOP). It emphasizes the use of objects,
classes, and inheritance for modular and organized code.
Distributed:
Java supports distributed computing, enabling the development of applications that can run on multiple
machines, communicate over a network, and share resources.
Robust:
Java is designed to be robust and reliable. It includes features like strong type-checking, exception
handling, and automatic memory management to prevent common programming errors.
Secure:
Java emphasizes security through features like the Java Virtual Machine (JVM), which provides a secure
execution environment, and the bytecode verifier, which ensures that code loaded into the JVM is safe.
Architecture-Neutral:
Java applications are compiled into an intermediate form called bytecode, which is platform
independent. This allows Java programs to run on any device with a compatible JVM, promoting the
"Write Once, Run Anywhere" (WORA) philosophy.
Portable:
Java's architecture-neutral bytecode and platform independence contribute to its portability. Java
programs can be easily moved from one platform to another without modification.
High Performance:
While Java is not as low-level as some languages, it is designed to deliver high performance through
features like Just-In-Time (JIT) compilation and various optimizations performed by the JVM.
Multithreaded:
Java has built-in support for multithreading, allowing developers to create applications that can execute
multiple threads concurrently. This is particularly useful for improving the performance of applications
on multicore processors.
Dynamic:
Java supports dynamic memory allocation and garbage collection, enabling efficient memory
management and reducing the chances of memory-related issues.
Interpreted and Compiled:
Java uses both interpretation and compilation. Java source code is compiled into bytecode, which is then
interpreted by the JVM. Some JVMs also use Just-In-Time (JIT) compilation to further optimize
performance.
11. Explain Type conversions in Java.

Type Conversion:
Type conversion, also known as casting, is the process of changing the data type of a variable in your
Java program. Imagine you have a box (variable) that holds a certain type of information. Type
conversion allows you to change the content of the box or use it in a different way.

Implicit Type Conversion (Widening):


This happens automatically when Java is confident that no data will be lost. It's like upgrading your box
to a bigger size. For example, if you have a small box for whole numbers (int) and want to store a
decimal number (double), Java will do it for you without you explicitly asking.

Explicit Type Conversion (Narrowing):


This is a manual process where you tell Java to change the type. It's like putting a label on your box
saying, "Now this is for something else." But be careful, you might lose some information if the new type
can't hold everything from the old type.

12. How “compile once and run anywhere” is implemented in java?

Java's "Write Once, Run Anywhere" (WORA) is realized through bytecode compilation. Developers write
code in Java, compile it into bytecode, which is platform independent. Any device with a Java Virtual
Machine (JVM) can interpret or compile this bytecode. JVM implementations are platform-specific,
allowing Java programs to be executed across diverse devices. This abstraction ensures portability,
simplifies distribution, and reduces platform-specific bugs, making Java applications versatile and widely
compatible.
13. Discuss the “labeled break” and “continue” statements .

Labeled Break:
class Break{
public static void main(){
boolean t = true;
first:{
second:{
third: {
System.out.println("Before the break");
if(t) break second; // break out of second block
System.out.println("This wont execute");
}
System.out.println("This wont execute");
}
System.out.println("after second block");
}
}
}

Labeled Continue:
public class ContinousLabel {
public static void main(String[] args){
outer: for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
if(j>i){
System.out.println();
continue outer;
}
System.out.print(" " + (i*j));
}
}
System.out.println();
}
}

14. Write short notes on JDK.

The Java Development Kit (JDK) is a comprehensive toolkit for Java development. It includes the Java
compiler (javac), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). With APIs, libraries,
and development tools, JDK facilitates the creation, debugging, and optimization of Java applications.
Regularly updated, it ensures backward compatibility and platform independence. The JDK's Integrated
Development Environment (IDE) support and documentation enhance the development experience,
making it an essential resource for building cross-platform Java applications with the latest features and
improvements.
15. Explain short circuit operators.

The secondary versions of the Boolean AND , OR operators are known as short-circuit logical operators.
They use the ‘|| ‘and ‘&&’ forms, rather than the ‘|’ and ‘&’ forms of these operators. Java will not
bother to evaluate the right-hand operand when the outcome of the expression can be determined by
the left operand alone.

16. How are arrays defined and used in java?

Arrays are a collection of variables with the same datatype.


Arrays can be declared in 2 ways.
• Since arrays in java are dynamic, we don’t need to specify the size of the array while declaring.
Syntax : datatype array_name[];
Example : int arr[];
• We can also allocate memory to the array by using the keyword ‘new’.
Syntax : datatype array_name[]=new datatype[size];
Example : int arr[]=new int [3];
• In multi-dimensional array we can allocate different memory sizes to different rows.
Syntax :
datatype array_name[][]=new int [3][];
array_name[0]=new int [3];
array_name[1]=new int [4];
array_name[2]=new int [3];
Example :
int arr[][]=new int [3][];
int arr[0]=new int [3];
int arr[1]=new int [7];
int arr[2]=new int [5];

17. Explain the process of building and running java application program.

Write Java Code:


Create a .java source code file containing the Java program using a text editor or an Integrated
Development Environment (IDE).
Compile Java Code:
Use the Java compiler (javac) to translate the source code into bytecode. Open a terminal or command
prompt and run javac YourProgram.java.
Bytecode Generation:
The compiler generates bytecode (.class files) that represent the program's instructions in a platform-
independent format.
Java Virtual Machine (JVM):
The bytecode is executed by the Java Virtual Machine (JVM), which interprets or compiles it into
machine code, providing platform independence.
Run Java Program:
Use the java command to run the program. In the terminal, execute java YourProgram.
Output:
The program's output is displayed in the console or terminal.
18. List down various operators available in JAVA.

 Arithmetic :+,-,*,/,%,etc.
 Logical : !=,||,==,&&
 Bitwise : ~,>>,<<,>>>,|,!,etc.
 Relational : <,>,<=,>=
 Assignment : =,+=,-=,etc.
 Unary : ++,--
 Ternary : ?,:

19. List out the decision-making statements available in Java. Explain with an example.
 If
 If-else
 If-else if
 Nested if
 If else ladder
 Switch

20. List out the looping statements available in Java. Explain with an example.
for(i=0;i<10;i++)
System.out.println(i);

for(int a : number)
System.out.println(number);

while(i!=0){
System.out.println(i);
i--;
}

do {
System.out.println(i);
i--;
}while(i!=0);
21. Define String. Explain the various ways of constructing string objects.

In Java, a String is a sequence of characters, representing text. It's an immutable class, meaning once
created, the content of a String object cannot be changed. Strings are widely used for storing and
manipulating textual data in Java applications.
String Literal:
The simplest way is to create a string using double quotes. Example: String greeting = "Hello";
Using the new Keyword:
You can use the new keyword to create a String object. Example: String name = new String("John");
String Builder:
For mutable string manipulation, use StringBuilder.
String Buffer (Thread-Safe):
Similar to StringBuilder but thread safe. Used in multithreaded environments.

22. Explain the following string handling methods.


a. concat() b. replace() c. trim() d. length()

concat() Method:
The concat() method is used to concatenate one string with another. It returns a new string that
represents the concatenation of the two original strings.
Example:
String str1 = "Hello";
String str2 = " World";
String result = str1.concat(str2);
// Result: "Hello World"

replace() Method:
The replace() method is used to replace all occurrences of a specified character or sequence of
characters in a string with another character or sequence.
Example:
String original = "Java is fun!";
String modified = original.replace("fun", "awesome");
// Result: "Java is awesome!"

trim() Method:
The trim() method is used to remove leading and trailing whitespace (spaces, tabs, etc.) from a string.
Example:
String withSpaces = " Hello, World! ";
String trimmed = withSpaces.trim();
// Result: "Hello, World!"

length() Method:
The length() method is used to retrieve the number of characters in a string.
Example:
String text = "Java";
int length = text.length();
// Result: length is 4
23. Write a Java program to remove duplicate characters from a given string and display the resultant
string.
24. Write a Java program to count the occurrence of characters in a given string.

You might also like