Java 1
Java 1
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.
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.
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.
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.
Bytecode Verification:
Before executing Java bytecode, the JVM performs bytecode verification. This process ensures that the
bytecode adheres to certain safety and security constraints.
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.
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.
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.
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();
}
}
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.
17. Explain the process of building and running java application program.
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.
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.