100% found this document useful (3 votes)
1K views18 pages

Java Programming Concepts and Examples

The document discusses various Java concepts like JDK, CLASSPATH, collections framework, readers and writers, static keyword, layout managers, throw keyword, difference between paint() and repaint(), access modifiers, polymorphism, features of Java, exceptions and exception handling, try and catch blocks, perfect numbers program, method overloading program to find area, program to store elements in ArrayList and display in reverse order, program to count digits, spaces and characters from a file, and program to display cursor position on keyboard movement.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
1K views18 pages

Java Programming Concepts and Examples

The document discusses various Java concepts like JDK, CLASSPATH, collections framework, readers and writers, static keyword, layout managers, throw keyword, difference between paint() and repaint(), access modifiers, polymorphism, features of Java, exceptions and exception handling, try and catch blocks, perfect numbers program, method overloading program to find area, program to store elements in ArrayList and display in reverse order, program to count digits, spaces and characters from a file, and program to display cursor position on keyboard movement.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Introduction to Java Programming
  • Java Throw Keyword and Modifiers
  • Features of Java
  • Exception Handling in Java
  • Try and Catch in Java
  • Java Program for Perfect Numbers
  • Method Overloading for Geometric Areas
  • ArrayList and Reverse Order
  • Counting Characters from a File
  • Cursor Movement Detection Program
  • Java Package Creation
  • Understanding Java Objects
  • Java Program Structure and Datatypes
  • Finally Block in Java
  • Constructor vs Method in Java
  • Abstract Class vs Interface
  • File Content Analysis Program

*What is JDK? How to build and run java?

->>JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is
a software development environment which is used to develop java applications
and applets. It physically exists. It contains JRE + development tools.

*What is use of class path?


-->CLASSPATH describes the location where all the required files are available
which are used in the application. Java Compiler and JVM (Java Virtual Machine)
use CLASSPATH to locate the required files.

*What is Collection? Explain Collection Framework in details?


-->A collection is an object that represents a of objects (such as the classic Vector
class). A collections framework is a unified architecture for representing and
manipulating collections, enabling collections to be manipulated independently of
implementation details.

*What is the use of reader and writer class?


-->Java readers and writers are character-based streams. A reader is used when
we want to read character-based data from a data source. A writer is used when
we want to write character-based data.

*Explain is static keyword.?


--> The static keyword in Java is used for memory management mainly.
can apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class

*What is the use of Layout Manager?


-->The Layout managers enable us to control the way in which visual components
are arranged in the GUI forms by determining the size and position of
components within the containers.
*Define Throw Keyword?
-->The throw keyword in Java is used to explicitly throw an exception from a
method or any block
code. We can throw either checked or unchecked exception. The throw keyword
is mainly used to throw custom exceptions.

Syntax:

throw Instance
Example:
throw new ArithmeticException("/ by zero");

*What is different between pain() and repaint().?


-->The paint() method contains instructions for painting the specific component.
The repaint() method, which can't be overridden, is more specific: it controls the
update() to paint() process. You should call this method if you want a component
to repaint itself or to change its look (but not the size)

Explain access Modifiers Used in Java?


There are four types of Java access modifiers:
1)Private:- The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2)Default: - The access level of a default modifier is only within the package. It
cannot be accessed from outside the package.
3)Protected:- The access level of a protected modifier is within the package and
outside the package.
4)Public:- The access level of a public modifier is everywhere. It can be accessed
from class, outside the class, within the package and outside the package.

*Define Polymorphism?
-->The word polymorphism means having many forms. In simple words, we can
polymorphism as the ability of a message to be displayed in more than one form.
*Explain features of java.?

1) Simple-:
Java is easy to learn and its syntax is quite simple, clean and easy to understand.

2) Object Oriented:-
In java, everything is an object which has some data and behavior. Java can be
easily extended as it is based on Object Model.

3) Robust:-
Java makes an effort to eliminate error prone codes by emphasizing mainly on
compile time error checking and runtime checking.

4) Platform Independent:-
Unlike other programming languages such as C, C++ etc. which are compiled into
platform specific machines.

5) Secure:-
When it comes to security, Java is always the first choice. With java secure
features it enable us to develop virus free, temper free system.

6) Multi Threading:-
Java multithreading feature makes it possible to write program that can do many
tasks simultaneously.

7) Portable:-
Java Byte code can be carried to any platform. No implementation dependent
features.

8) High Performance:-
Java is an interpreted language, so it will never be as fast as a compiled language
like C or C++.
*Explain the concept of exception and exception handling?
-->An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. When an error occurs
within a method, the method creates an object and hands it off to the runtime
system.

Exception Handling in Java is one of the effective means to handle the runtime
errors so that the regular flow of the application can be preserved. Java Exception
Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

**Types of Exceptions:-

1) Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java library.

2) User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called ‘user-
defined Exceptions’.

ADVANTAGES OF EXCEPTION HANDLING

*Provision to Complete Program Execution

*Propagation of Errors

*Meaningful Error Reporting

*Identifying Error Types


*Explain try and Catch with example.
1)TRY:- Java try block is used to enclose the code that might throw an exception.
It must be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute.
EXAMPLE.

public class TryCatchExample{


public static void main(String[] args) {
try
{
int data=50/0;
}

catch(Exception e)
{
[Link]("Can't divided by zero");
}
}
}

2) CATCH :-
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent class
exception ( i.e., Exception) or the generated exception type. However, the good
approach is to declare the generated type of exception.

EXAMPLE.
public class TryCatchExample {

public static void main(String[] args) {


int data=50/0;

[Link]("rest of the code");

}
}
*Write a java program to display all the perfect numbers between 1 to n?

import [Link];
public class Perfect
{
static boolean perfect(int num)
{
int sum = 0;
for(int i=1; i<num; i++)
{
if(num%i==0)
{
sum = sum+i;
}
}
if(sum==num)
return true;
else
return false;
}
public static void main(String[] args)
{
Scanner obj = new Scanner ([Link]);
[Link]("enter the value for n");
int n = [Link]();
for(int i=1; i<=n; i++)
{
if(perfect(i))
[Link](i);
}
}
}
*Java Program to Find Area of Square, Rectangle and Circle. (using Method
Overloading).?

class OverloadDemo
{
void area(float x)
{
[Link]("the area of the square is "+[Link](x, 2)+" sq units");
}
void area(float x, float y)
{
[Link]("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
[Link]("the area of the circle is "+z+" sq units");
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
[Link](5);
[Link](11,12);
[Link](2.5);
}
}
Output:

$ javac [Link]
$ java OverloadDemo

the area of the square is 25.0 sq units


the area of the rectangle is 132.0 sq units
the area of the circle is 19.625 sq units
*Write a java program to accept 'n' integers from the user and store them in an ArrayList
Collection. Display the elements of an ArrayList in Reverse order.?
import [Link].*;
class array
{
public static void main(String a[])

{
Scanner sc=new Scanner([Link]);

[Link]("Enter Limit of ArrayList :");

int n=[Link]();

ArrayList alist=new ArrayList();

[Link]("Enter Elements of ArrayList :");

for(int i=0;i<n;i++)

{
String elmt=[Link]();

[Link](elmt);
}

[Link]("Original ArrayList is :"+alist);

[Link](alist);

[Link]("Reverse of a ArrayList is :"+alist);


}
}
Output :-
Enter Limit Of Array List:
6
Enter Elements Of Array List:
43
26
87
56
97
12
Original array list is :[43,26,87,56,97,12]
Reversed Array list is:
[12,97,56,87,26,43]
*Write a java program to count Number of digits ,spaces and characters from a
file.?

import [Link].*;
class prac3 A
{
public static void main(String args[])
{
Scanner input=new Scanner([Link]);
[Link]("Enter A String: ");
String str=[Link]();
int letter=0,space=0,digit=0,other=0;
char ch[]=[Link]();
for(int i=0;i<[Link]();i++)
{
if([Link](ch[i]))
{
letter++;
}
else if([Link](ch[i]))
{
digit++;
}
else if([Link](ch[i]))
{
space++;
}
else{
other++;
}
}
[Link]("Letter are: "+letter);
[Link]("Space are: "+space);
[Link]("Digit are: "+digit);
[Link]("Other: "+other);
}
}
*Write a program that displays the x and y position of the cursor movement
using Keyboard..?
-->
import [Link].*;
import [Link].*;
import [Link].*;
/*

*/
public class Simplekey extends Applet implements KeyListener {
String msg = ” “;
int X = 10, Y = 20;
public void init() {
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke) {
showStatus(“Key Down”);
}
public void keyReleased(KeyEvent ke) {
showStatus(“Key Up”);
}
public void keyTyped (KeyEvent ke) {
msg += [Link]();
repaint();
}
public void paint(Graphics g) {
[Link](msg, X, Y);
}
}
*what is package. Write down all the steps for package creation.?

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.

"Steps for creating package:

To create a package, follow the steps .

Choose a package name according to the naming convention.

Write the package name at the top of every source file (classes, interface,
enumeration, and annotations).

Remember that there must be only one package statement in each source file.

Package name must be in lower case that avoids conflict with the name of classes
and interfaces.

Organizations used their internet domain name to define their package names.
For example, [Link].

Sometimes, the organization also uses the region after the company name to
name the package.
For example, [Link].

We use underscore in the package name if the domain name contains hyphen or
other special characters or package names begin with a digit or reserved keyword
*DEFINE OBJECT?
-->It is a basic unit of Object-Oriented Programming and represents real life
entities. A typical Java program creates many objects, which as you know, interact
by invoking methods. An object consists of :

1) State: - It is represented by attributes of an object. It also reflects the


properties of an object.

2) Behavior: - It is represented by methods of an object. It also reflects the


response of an object with other objects.

3) Identity: - It gives a name to an object and enables one object to interact with
other objects

*What is applet? Explain its types?

An applet is a Java program that can be embedded into a web page. It runs
inside the web browser and works at client side. An applet is embedded in an
HTML page using the APPLET or OBJECT tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.

TYPES OF APPLETS.

1)Local Applet--: is written on our own, and then we will embed it into web pages.
Local Applet is developed locally and stored in the local system. A web page
doesn't need the get the information from the internet when it finds the local
Applet in the system.

2)Remote Applet--:A remote applet is designed and developed by another


developer. It is located or available on a remote computer that is connected to
the internet. In order to run the applet stored in the remote computer, our
system is connected to the internet then we can download run it.
*How a Java program is structured? Explain Datatypes

-->Data types in java


 Primitive data types: The primitive data types include Boolean, char, byte,
short, int, long, float and double.
 Non-primitive data types: The non-primitive data types include Classes,
Interfaces, and Arrays.
*Define Term finally block?

--> Java finally block is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occur or not.

FLOW CHART OF FINALLY BLOCK---:


* Difference between Constructor And Method? Explain type of Constructor?

--> Constructor Types--


There are two types of constructors in Java:

1. Default constructor --> The constructor is called when an object is created.


It also allocates memory for that object
2. Parameterized constructor --> The parameterized constructor is a
constructor that accepts parameters. There can be one or more parameters
*Difference between abstract class and interface?

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
}
*Java Program to Count the Number of Lines, Words, Characters from a given File

import [Link].*;

public class Test {

public static void main(String[] args)

throws IOException

{
File file = new File("C:\\Users\\hp\\Desktop\\[Link]");

FileInputStream fileInputStream = new FileInputStream(file);

InputStreamReader inputStreamReader = new


InputStreamReader(fileInputStream);

BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String line;

int wordCount = 0;

int characterCount = 0;

int paraCount = 0;

int whiteSpaceCount = 0;

int sentenceCount = 0;

while ((line = [Link]()) != null) {

if ([Link]("")) {
paraCount += 1;
}
else {

characterCount += [Link]();

String words[] = [Link]("\\s+");

wordCount += [Link];

whiteSpaceCount += wordCount - 1;

String sentence[] = [Link]("[!?.:]+");

sentenceCount += [Link];

if (sentenceCount >= 1) {

paraCount++;

[Link]("Total word count = "+ wordCount);

[Link]("Total number of sentences = "+ sentenceCount);

[Link]("Total number of characters = "+ characterCount);

[Link]("Number of paragraphs = "+ paraCount);

[Link]("Total number of whitespaces = "+ whiteSpaceCount);

}
}

Common questions

Powered by AI

Polymorphism in Java supports object-oriented programming by allowing objects to be treated as instances of their parent class. It facilitates method overriding and method overloading. With polymorphism, a single method can have multiple implementations, thus enabling code reusability and flexibility. The two main forms of polymorphism in Java are compile-time (method overloading) and runtime polymorphism (method overriding). This ability to process objects differently based on their data type or class significantly simplifies the problem-solving process within the object-oriented paradigm .

Encapsulation in Java promotes object-oriented design by restricting access to certain internal components of an object, thereby safeguarding its integrity and use. This is achieved through the use of access modifiers (private, protected, default, and public) that control visibility and accessibility. By exposing only necessary operations through public methods while keeping the data private, developers can prevent external interference and misuse of data. Encapsulation thus contributes to maintaining consistency, reducing complexity, and facilitating maintenance by allowing modifications in class implementation without affecting external code that uses the class .

The static keyword in Java is crucial for memory management and determines how class members are accessed and exist within the Java Virtual Machine (JVM). It applies to variables and methods that belong to the class rather than a specific instance, leading to shared class resources. This approach reduces the memory footprint because static members are only stored once per class, regardless of the number of instances. Static members are accessed using the class name, simplifying code organization and interaction . The keyword also facilitates utility or helper methods within a class that do not require object context, promoting efficient coding practices .

Java's Collection Framework provides a standardized architecture for manipulating and managing collections of objects, offering significant improvements over earlier methods like arrays. Unlike arrays, collections can dynamically grow and shrink, allowing more flexible data handling. The framework includes a wide variety of interfaces and classes (such as List, Set, and Map) that provide different functionalities and performance characteristics tailored to specific use cases, enabling collections to be more easily manipulated and accessed than arrays. Additionally, collections provide robust iteration capabilities and operations like searching, sorting, and thread-safe manipulation through synchronized views, enhancing program efficiency and reliability .

Layout managers in Java enhance GUI design by automatically managing the size and position of components within containers. This abstraction handles component arrangement according to different criteria, such as the display size or resolution, which greatly reduces the amount of hard-coded positioning logic developers must write. Layout managers provide flexibility and responsiveness, ensuring that GUIs look appropriate across different devices and screen sizes without requiring separate designs. They also provide a systematic way to accommodate dynamic content changes, aiding in creating adaptive and maintainable user interfaces .

The Java Development Kit (JDK) supports Java application development by providing the necessary tools to develop, compile, and run Java programs. It consists of the Java Runtime Environment (JRE), which allows Java applications to run, and a variety of development tools, such as the Java compiler (javac) and the Java debugger. These components collectively enable developers to write and test code efficiently by providing essential services like code compilation, execution, and debugging .

The key differences between an abstract class and an interface in Java include their method and variable types, inheritance capabilities, and purpose. An abstract class can contain both abstract and non-abstract methods, supports inherited classes, and allows for a mix of static and non-static variables. Interfaces, on the other hand, primarily contain abstract methods (until Java 8, which allows default and static methods) and static final variables, supporting multiple inheritance . Choose an abstract class when you need a shared base with some implemented behavior, and use interfaces to define a contract for classes without enforcing method implementation. If multiple inheritance is needed across classes, interfaces are more appropriate .

The finally block in Java is a crucial part of exception handling, ensuring that specific code executes regardless of whether an exception is thrown or not. It is typically used to release resources like file handles, database connections, or sockets, preventing resource leaks and maintaining application stability. Since the finally block runs after try-catch or alone even if no exception occurs, it provides a reliable way to perform cleanup tasks. This guarantees that necessary cleanup actions are taken, which is essential in maintaining consistent and error-free operation and avoiding resource exhaustion .

Java achieves platform independence through its use of bytecode, an intermediate representation of Java code generated by the Java compiler. When Java code is compiled, it is not converted into processor-specific machine code; instead, it becomes bytecode, which can be executed on any system that has a Java Virtual Machine (JVM). The JVM interprets or compiles bytecode into machine code suitable for the host system at runtime. This process allows Java programs to run on any platform (Windows, Mac, Linux, etc.) without modification, ensuring that Java developers write code once and deploy it anywhere .

Exception handling in Java significantly improves the robustness and reliability of applications by providing a structured way to manage runtime errors. When an exception occurs, Java's exception handling mechanism uses try-catch blocks to catch and handle exceptions, preventing the program from crashing and enabling it to continue executing . By allowing developers to create meaningful error messages and handle specific exceptions, the application can gracefully recover from unexpected issues, thereby enhancing user experience and maintaining system integrity . Exception handling also allows errors to propagate through the call stack while preserving the application's flow .

*What is JDK? How to build and run java? 
->>JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is 
a
*Define Throw Keyword? 
-->The throw keyword in Java is used to explicitly throw an exception from a 
method or any block
*Explain features of java.? 
 
1) Simple-: 
Java is easy to learn and its syntax is quite simple, clean and easy to understan
*Explain the concept of exception and exception handling? 
-->An exception is an event, which occurs during the execution of
*Explain try and Catch with example. 
1)TRY:-  Java try block is used to enclose the code that might throw an exception. 
It
*Write a java program to display all the perfect numbers between 1 to n? 
 
import java.util.Scanner; 
public class Perfect
*Java Program to Find Area of Square, Rectangle and Circle. (using Method 
Overloading).? 
 
class OverloadDemo 
{ 
    void
*Write a java program to accept 'n' integers from the user and store them in an ArrayList 
Collection. Display the elements o
*Write a java program to count   Number of digits ,spaces and characters from a 
file.? 
 
import java.util.*; 
class prac3 A
*Write a program that displays the x and y position of the cursor movement 
using Keyboard..? 
--> 
import java.awt.*; 
impor

You might also like