Java Programming Concepts and Examples
Java Programming Concepts and Examples
1)What Is Java?
Ans:
Java is a widely used high-level, class-based, object-oriented programming language. It was
originally developed by Sun Microsystems (now a subsidiary of Oracle Corporation) in the
mid-1990s and has since become one of the most popular programming languages in use today.
Java is used for developing a wide range of applications, from mobile and web applications to
enterprise software solutions. Its popularity is due in part to its platform independence, which
means that Java applications can run on any computer or mobile device that has the Java Virtual
Machine (JVM) installed. Additionally, Java is known for its robustness, reliability, and security
features, making it a popular choice for developing mission-critical applications.
Ans:
Features Of Java:
1)Simple
2)Secure
4)Robust Language
5)High Performance
6)Multi Threading'
7)Platform Independent
OOPS Concepts:
Java is a popular programming language that is widely used for developing various types of
applications, including desktop, web, and mobile applications. One of the key features of Java is
its support for Object-Oriented Programming (OOP) concepts, which allows developers to
design and implement complex applications easily.
2. Inheritance:
Inheritance is a mechanism that allows a new class to be based on an existing class. The new
class contains all the attributes and methods of the existing class and can also add its own
attributes and methods. This helps to reduce code duplication and makes code more
manageable.
3. Polymorphism:
Polymorphism is the ability of an object to take on multiple forms. In Java, polymorphism can be
achieved through method overloading and method overriding. Method overloading allows a
class to have multiple methods with the same name but with different arguments, while
method overriding allows a subclass to provide its own implementation of a method that is
already defined in its superclass.
4. Abstraction:
Abstraction is the process of hiding implementation details and showing only the necessary
information to the user. Abstraction can be achieved in Java through abstract classes and
interfaces. An abstract class contains one or more abstract methods that are not implemented
and can only be implemented by subclasses. An interface is a collection of abstract methods
that is used to define the behavior of an object.
5. Encapsulation:
Encapsulation is the process of wrapping data and methods into a single unit called a class. This
helps to protect the data from unauthorized access and modification. In Java, encapsulation can
be achieved through the use of access modifiers such as public, private, and protected.
Ans:
The objects and classes in Java can vary widely depending on the specific context, but in
general, a class in Java is a blueprint or template for creating objects that represent real-world
entities or abstract concepts. An object in Java is an instance of a class that has attributes (data)
and methods (functions) associated with it.
For example, in a simple program that creates and manipulates shapes, we might have a class
called `Shape` and subclasses like `Circle`, `Rectangle`, and `Triangle`, each with their own
methods for calculating area and perimeter. We could then create objects of each of these
classes to represent specific shapes in our program.
In a more complex program, you might have classes and objects that represent users, products,
orders, or anything else that the program needs to interact with.
So, to classify the objects and classes in Java, you would need to consider the specific context
and identify the classes that represent entities or concepts in that context, and the objects that
represent specific instances of those entities or concepts.
Ans:
Polymorphism and abstraction are fundamental concepts in object-oriented programming,
including Java.
Polymorphism means the ability of an object to take on multiple forms. In Java, this is typically
achieved through inheritance and method overriding. For example, you can define a method in
a parent class, and override it with a different implementation in one or more of its child
classes. Then, you can call the method on either the parent or the child class object and get
different results. This can make your code more flexible and reusable.
Abstraction means the process of hiding complex details and showing only the essential
features to the user. In Java, this is typically achieved through abstract classes and interfaces. An
abstract class cannot be instantiated, but it can provide a partial implementation of a class so
that its child classes can inherit and customize its behavior. An interface, on the other hand,
defines a set of methods that a class must implement, but it does not provide any
implementation. This can make your code more modular and maintainable.
Overall, polymorphism and abstraction are powerful tools that can help you write efficient and
effective Java code. They can make your code more flexible, modular, and extensible.
Ans:
The structure of a Java program typically consists of several parts:
1. Documentation Section: This section contains comments about the program and its purpose.
2. Package Statement: This statement declares the package the program belongs to. It is an
optional statement and can be omitted if the program does not belong to a package.
3. Import Statements: These statements import other classes that the program will use.
4. Interface Section: This section defines the interfaces that the program implements. It is
optional and can be omitted if the program does not use interfaces.
5. Class Definition: This section defines the class or classes that form the core of the program.
6. Main Method: This method is the entry point of the program and is called when the program
is executed.
As for the diagram, it depends on what specifically is being referred to. There are several types
of diagrams used in Java programming, including class diagrams, sequence diagrams, and state
diagrams. Each diagram serves a different purpose in modeling and designing software.
Ans:
An Array Is a Collection Of Similar Type Of Data.
Here,the above array cannot store more than 100 names.The number of Values in Java
array is always fixed.
12 4 5 2 5
Array includes always Start From 0 that is the first element of an array is at index 0.
If the size of an array is n, then the last element of the array will be at index n-1.
Multidimensional Array:-
String[][]data=newString[3][4][2];
Two-Dimensional Array:-
Ex:-
publicstaticvoidmain(string[]args){
int[]a={
{1,2,3}
{4,5,6}
{7}
1. if statement: The if statement executes a block of code if a given condition is true. Here is an
example:
```
int x = 10;
if(x > 5) {
```
2. if-else statement: The if-else statement executes one block of code if a given condition is true,
and another block of code if the condition is false. Here is an example:
```
int x = 3;
if(x % 2 == 0) {
System.out.println("x is even");
} else {
System.out.println("x is odd");
}
```
```
int x = 10, y = 5;
if(x > 5) {
if(y > 2) {
```
4. else-if statement: The else-if statement allows you to check for multiple conditions. Here is an
example:
```
int x = 10;
if(x > 5) {
} else {
```
5. switch statement: The switch statement allows you to execute different blocks of code based
on the value of a variable. Here is an example:
```
int x = 2;
switch(x) {
case 1:
System.out.println("x is 1");
break;
case 2:
System.out.println("x is 2");
break;
default:
```
In this example, because `x` is equal to 2, the second case will be executed and "x is 2" will be
printed to the console.
8)What Is Loop Statement? Write Down For Loop And While Loop
With Example?
Ans:
A loop statement is used in programming languages to repeatedly execute a block of code until
a specific condition is met. In Java, there are mainly two types of loop statements: the for loop
and the while loop.
```
```
Here, the `initialization` statement is executed only once, at the beginning of the loop. The
`condition` statement is evaluated at the beginning of each iteration of the loop, and if it is true,
the code block inside the loop is executed. The `update` statement is executed at the end of
each iteration of the loop. The loop continues until the condition evaluates to false.
System.out.println(i);
```
```
while (condition) {
```
Here, the `condition` statement is evaluated at the beginning of each iteration of the loop, and
if it is true, the code block inside the loop is executed. The loop continues until the condition
evaluates to false.
```
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
```
```
3
4
```
```
Arrays.fill(myArray, 1);
```
This creates an array of integers with a size of 5 and fills all elements with the value of 1.
To sort the elements of an array in ascending order, you can use the `sort()` method provided by
the `Arrays` class. Here's an example of how to sort an array of integers:
```
Arrays.sort(myArray);
```
This would sort the elements of the `myArray` array in ascending order, resulting in the array
`{1, 2, 3, 4, 5}`.
To check if two arrays are equal, you can use the `equal()` method provided by the `Arrays`
class. Here's an example of how to check if two arrays of integers are equal:
```
```
In this example, `isEqual` would be set to `true` because the `firstArray` and `secondArray` have
the same values in the same order.
To perform a binary search on a sorted array, you can use the `binarySearch()` method provided
by the `Arrays` class. Here's an example of how to perform a binary search on an array of
integers:
```
```
In this example, `index` would be set to `2` because the value `3` is located at index `2` in the
`myArray` array. If the value is not found in the array, the method returns a negative number to
indicate that.
1. Compare Strings: You can use the `equals()` method or the `compareTo()` method to compare
two strings. The `equals()` method checks if two strings have the same value, while
`compareTo()` method returns an integer value that indicates the lexicographical order of two
strings.
Example:
```
System.out.println(str1.equals(str2)); // false
System.out.println(str1.compareTo(str2)); // -15
```
2. Combine Strings: You can use the `concat()` method or the `+` operator to concatenate two
strings.
Example:
```
System.out.println(str3); // HelloWorld
System.out.println(str4); // HelloWorld
```
3. Reverse Strings: You can use the `StringBuilder` class or the `StringBuffer` class to reverse a
string.
Example:
```
sb.reverse();
System.out.println(reversedStr); // olleH
```
4. Uppercase Strings: You can use the `toUpperCase()` method to convert a string to uppercase.
Example:
```
System.out.println(upperStr); // HELLO
```
11) Draw Compilation and interpretation process of java
Ans:
You have to create your program and compile it before it can be executed.You can use any text editor or
IDE to create and edit a Java source-code file, source file is officially called a compilation unit. This
process is repetitive, as shown in below.
We can declare a method as final, once you declare a method final it cannot be overridden. So, you
cannot modify a final method from a sub class.
The main intention of making a method final would be that the content of the method should not be
changed by any outsider.
Ordinary Method
The most common use of the super keyword is to eliminate the confusion between superclasses and
subclasses that have methods with the same name.
Example:
class Animal { // Superclass (parent)
}
}
Extends Keyword:
The extends keyword extends a class (indicates that a class is inherited from another class).
In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:
Example:
class Vehicle {
System.out.println("Tuut, tuut!");
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName
from the Car class
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default.
Example:
interface printable{
void print();
obj.print();
Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at
run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and
handled by the program. When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such as the name and
description of the exception and the state of the program when the exception occurred.
A static method is not part of the objects it creates but is part of a class definition. Unlike instance
methods, a static method is referenced by the class name and can be invoked without creating an object
of class.
In simpler terms, they are methods that exist even if no object has been constructed yet and that do not
require an invocation object
Finally:
A finally keyword is use to create a block of code that follows a try or catch block
A finally block of code always executes whether or not exception has occured
Pass By Reference: The pass by reference method passes the parameters as a reference(address) of the
original variable. The called function does not create its own copy, rather, it refers to the original values
only. Hence, the changes made in the called function will be reflected in the original parameter as well.
Example:
public class Example {
/*
*/
int a = 10;
eg.a = eg.a+10;
eg.call(eg);
Output:
Before Call By Reference:10
words[0] = "Hello";
words[1] = "World";
words[2] = "!";
}
In this example, we've created an array of String objects called words, and initialized it with 3 elements.
Each element of the array is a reference to a String object. We then assign String objects to each of the
elements of the array, and finally, print out the array elements using a for-each loop.
Note that when you create an array of reference type in Java, you are only creating an array of
references that point to objects of that type. You still need to create each object separately and assign its
reference to each element of the array.
Variable: When a variable is declared as final, its value cannot be modified after it has been assigned. In
other words, it becomes a constant throughout the program. For example:
Method: When a method is declared as final, it cannot be overridden in subclasses. This can be useful
when you want to ensure that a particular implementation of a method is used throughout your
program.
For example:
// implementation here
Class: When a class is declared as final, it cannot be subclassed. This means that the class cannot be
extended by other classes.
For example:
It's worth noting that using the final keyword can help make your code more robust and maintainable.
By preventing certain entities from being modified, you can reduce the risk of errors and unexpected
behavior in your program.
Ex:-
String name;
int age;
public Person() {
// Default constructor
name = "Unknown";
age = 0;
A parameterized constructor, on the other hand, is a constructor that takes one or more arguments. It is
used to initialize the object's variables with specific values passed as arguments. Here is an example of a
class with a parameterized constructor:
Ex:-
String name;
int age;
// Parameterized constructor
this.name = name;
this.age = age;
In this example, the constructor takes two parameters: name and age. The constructor assigns the
parameter values to the corresponding instance variables using the this keyword.
By using parameterized constructors, we can create objects with specific values for their instance
variables. For example, to create a Person object with the name "Alice" and age 25, we can do:
The public access modifier makes members and methods accessible from any class in any package. This
means that public members are the most accessible access level.
The protected access modifier makes members and methods accessible from the same class, a subclass
in the same package, or a subclass in a different package. This access modifier means that only
subclasses and classes in the same package can access the members.
The default or package-private access modifier makes members and methods accessible only within the
same package. This access modifier means that a class, interface, or member is only visible and
accessible within the same package, and it is not available to other packages.
Finally, the private access modifier makes members and methods only accessible within the same class
or interface. This access modifier is the most restrictive accessibility level, as it restricts the accessibility
of the member to only the same class or interface.
The choice of access modifier depends on the design goals and objectives of the programmer. Generally,
fields and methods should be restricted to the lowest accessibility level required by their intended use,
to ensure greater encapsulation and maintainability. It is important to use access modifiers correctly to
avoid coupling between classes and to ensure that code is well organized and well-structured.
In the above example, this is used to refer to the length and width instance variables, to avoid ambiguity
with the local variables that have the same names.
this.name = name;
this.age = age;
In the above example, the first constructor calls the second constructor using this, passing a default
value for age.
Overall, this is a useful keyword in Java that allows you to refer to the current instance of a class and to
differentiate between instance variables and local variables that may have the same name.
The difference between checked and unchecked exceptions is that checked exceptions are intended to
be used for exceptional conditions that can be reasonably anticipated and handled , whereas unchecked
exceptions are intended to be used for system-level errors that can't be easily handled in code.
For example, FileNotFoundException is a checked exception because it can be anticipated and handled in
code by the developer, while NullPointerException is an unchecked exception because it is usually the
result of a coding error and cannot be easily handled in code.
In Java, all exceptions that inherit from the RuntimeException class are unchecked exceptions, while
those that inherit from Exception but not from RuntimeException are checked exceptions.
It is important to choose the appropriate type of exceptions in your code to ensure that your code is
robust and handles errors appropriately.
In other words, Java achieves platform independence through its bytecode format and the JVM, which is
responsible for executing that bytecode on different platforms. The bytecode does not directly run on
the underlying hardware, but rather on the JVM implementation on each platform.
This approach allows Java programs to be written once and run on any platform that has a JVM installed,
without the need to recompile the code for each platform. This feature has made Java a popular
language for developing applications that need to run on multiple platforms, such as web and mobile
applications.
1. Creating a package:
- Choose the name of the package, which should follow the naming conventions for Java packages (i.e., it
should be in all lowercase letters).
- Create a new directory with the same name as the package in the file system.
- Include the package command as the first line of code in your Java source file, with the name of the
package.
For example, if you want to create a new package called "com.example.mypackage", you would create a
directory structure like this:
```
com
└── example
└── mypackage
└── MyClass.java
```
In the MyClass.java file, you would include the package command at the beginning:
```
package com.example.mypackage;
```
2. Importing a package:
- Use the import keyword to import the package and its classes into your Java program.
- You can use either a specific class from the package or import the entire package using the * wildcard
character.
For example, if you want to use the MyClass class from the com.example.mypackage package:
```
import com.example.mypackage.MyClass;
```
```
import com.example.mypackage.*;
```
Checked exceptions are those that must be declared in the method signature using the `throws` keyword
or caught using a `try-catch` block, and are usually recoverable. Examples of checked exceptions include
`IOException`, `SQLException`, and `InterruptedException`.
On the other hand, unchecked exceptions are not required to be declared in the method signature or
caught using a `try-catch` block, and are usually caused by programming errors such as null pointer
exceptions or index out of bounds exceptions. Examples of unchecked exceptions include
`NullPointerException`, `IndexOutOfBoundsException`, and `IllegalArgumentException`.
The main difference between checked and unchecked exceptions is that checked exceptions are checked
by the compiler at compile-time, while unchecked exceptions are not checked by the compiler.
Additionally, checked exceptions must be declared or caught, while unchecked exceptions do not have
this requirement.
Custom exceptions can be useful in situations where none of the standard exceptions apply or when it is
necessary to provide more specific information about the exception. Custom exceptions can be either
checked or unchecked, depending on whether they extend the `Exception` or `RuntimeException` class.
To define a custom exception, create a new class that extends either `Exception` or `RuntimeException`
and define any necessary constructors and methods. The name of the custom exception class should end
with "Exception", following Java convention.
```
super(message);
```
```
super(message);
31)Assume that there are two packeges, student and exam. A student
package contains Student class and exam package contain result
class. Write a java program that generatesca marksheet for students
Ans:
package marksheet;
import student.Student;
import exam.Result;
System.out.println("Marks Obtained:");
interface A {
void foo();
interface B {
void bar();
class C implements A, B {
obj.foo();
obj.bar();
Concept implemented:
Abstraction is the process of hiding implementation details while showing only the necessary features of
an object. In Java, abstraction can be achieved using abstract classes and interfaces.
Encapsulation is the practice of bundling data and methods that operate on that data within one unit,
such as a class. In Java, encapsulation is achieved using access modifiers to restrict access to the data and
methods of a class.
Inheritance is the process of creating new objects by reusing existing objects. In Java, inheritance is
accomplished by creating a new class that inherits the properties and methods of an existing class.
Polymorphism is the ability of an object to take on many forms. In Java, polymorphism can be achieved
through method overloading and method overriding.
These concepts are fundamental to understanding and developing robust and efficient applications in
Java.
Ans:
import java.util.Scanner;
Ans:
class Vehicle {
String vehicle_type;
public void display() {
System.out.println("Vehicle Type is = " + vehicle_type);
}
}
Ans:
Ans:
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU.
Each part of such program is called a thread. So, threads are light-weight processes within a
process.
Threads can be created by using two mechanisms:
Extending the Thread class
Implementing the Runnable Interface
If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance.
But, if we implement the Runnable interface, our class can still extend other base classes.
Multithreading is required because it allows us to write more efficient programs that can take
advantage of multiple CPUs or cores.
It also allows us to write programs that can perform multiple tasks simultaneously.
New
Runnable
Running
Blocked/Waiting
Terminated
When a new thread is created, it is in the New state3. When the thread starts running, it moves
to the Runnable state.
In this state, the thread is ready to run but it may not get CPU time immediately.
When the thread gets CPU time, it moves to the Running state.
In this state, the thread is actually executing its task.
If a running thread is blocked or waiting for some resource, it moves to the Blocked/Waiting
state.
Finally, when a thread completes its task or is terminated by some other means, it moves to the
terminated state.
39)Draw and explain life cycle of Thread. Also list and explain
various methods of thread
Ans:
Ans:
An abstract class in Java is a class that is declared with the abstract keyword.
It can have both abstract and non-abstract methods.
An abstract method is a method that has no implementation.
Abstract classes cannot be instantiated.
Instead, they are meant to be extended by other classes that provide an implementation for
their abstract methods.
interface Animal {
public void eat();
public void makeSound();
}
The main difference between an abstract class and an interface is that an abstract class can have
both abstract and non-abstract methods while an interface can only have abstract methods. Another
difference is that a class can extend only one abstract class while it can implement multiple interface.
41)What Is An Applet?
Ans:
In Java, an applet is a type of Java program that can be embedded in a web page. It runs
inside a web browser and can perform various interactive operations with the user. Applets
are designed to be small and portable, and they can be used to provide dynamic and
interactive content on a web page. Compared to other types of Java applications, applets
have some restrictions in terms of what they can do, such as not being able to access the
local file system directly, but they can easily communicate with a server-side application to
overcome these restrictions. Applets are typically written in Java but other programming
languages that can compile to Java bytecode can also be used.
1. Initialization: In this stage, the applet is created and initialized by the JVM. The init()
method is called only once during the applet's life cycle.
2. Starting: In this stage, the applet enters the running state and the start() method is called.
Once the start() method is called, the applet is visible on the user's screen and begins to
execute.
3. Painting: In this stage, the applet is redrawn on the screen if necessary using the paint()
method. The paint() method is called whenever the applet needs to be redrawn on the
screen, such as when a GUI component changes or the user interacts with the applet.
4. Stopping: In this stage, the applet enters the stopped state and the stop() method is
called. This happens when the user navigates away from the applet or the browser window
is minimized.
5. Destroying: In this stage, the applet is destroyed and the destroy() method is called. This
happens when the user closes the browser window or navigates away from the page
containing the applet.
Understanding the life cycle of an applet is important because it helps developers know
exactly when each method is called and what it does, which allows them to create more
efficient and robust applets.
It is important to note that applets are being phased out of modern web browsers due to
security concerns and compatibility issues. It is recommended to use other technologies,
such as HTML5 and JavaScript, instead of applets.
These restrictions are put in place for security purposes and to prevent untrusted applets
from accessing sensitive data or performing potentially harmful actions on the user's
system. However, privileged applets do not have some of these restrictions, and can run
outside the security sandbox.