0% found this document useful (0 votes)
7 views51 pages

Java Activity

The document outlines various activities related to Object-Oriented Programming and Design with Java for the academic year 2024-25 at Impact Polytechnic, Bangalore. It includes a rubric for evaluating activities, comparisons between Java and Python, explanations of Java bytecode, inheritance concepts, and a list of Java keywords with their uses. The document serves as a guide for students to understand essential Java programming concepts and their applications.

Uploaded by

geetha
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)
7 views51 pages

Java Activity

The document outlines various activities related to Object-Oriented Programming and Design with Java for the academic year 2024-25 at Impact Polytechnic, Bangalore. It includes a rubric for evaluating activities, comparisons between Java and Python, explanations of Java bytecode, inheritance concepts, and a list of Java keywords with their uses. The document serves as a guide for students to understand essential Java programming concepts and their applications.

Uploaded by

geetha
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

IMPACT POLYTECHNIC

Kodigehalli, Bangalore, Karnataka 560092

For the academic year 2024-25


OBJECT ORIENTED PROGRAMMING AND DESIGN AND
DESIGN WITH JAVA
Activity submitted by,

Under the guidance of Mrs. GEETHA S

Lecturer, CS DEPARTMENT
IMPACT POLYTECHNIC, BANGALORE-92
DEPARTMENT CS ACADEMIC 2024-2025
YEAR
SUBJECT JAVA SEMESTER 4
NAME OF THE REG NO.
STUDENT

RUBRICS SHEET
Sl no Name of the Activity DIMENSION
Beginner Intermediate Good Advanc Expert Student
ed scored
2 4 6 8 10 10
1 Various java IDE

2 Byte code

3 Inheritance concept
4 Java keywords

5 Static binding
6 ISP principles
7 Using CLA
8 Java features
9 Packages in java
10 Array
11 Abstract
12 Message logger

Average

Signature of student signature of course coordinator


ACTIVITY-1

a. Identify various Java IDE sand Identify difference between them

Java IDEs, or Integrated Development Environments, are software applications designed to


facilitate Java software development by providing a comprehensive set of tools, features, and
utilitieswithinaunifiedgraphicaluserinterface(GUI).TheseIDEsstreamlinethedevelopment process,
offering features such as code editing, debugging, compiling, testing, and project management.

Eclipse:
 OpenSource:Eclipseisanopen-sourceIDEmaintainedbytheEclipseFoundation.
 Extensibility: Eclipse has a vaste ecosystem of plugins, allowing users to
customize and extend its functionality according to their needs.
 RichFeatureSet: Eclipse offers a comprehensive set of features for Java
development, including code editing, debugging, version control integration, and
project management.
 Community Support:Eclipse has a large and active community, providing
resources, tutorials, and support forums.
 Suitable for Large Projects: Eclipse is often preferred for large-scale projects
due to its extensibility and robustness.

IntelliJIDEA:
 Commercial Option:IntelliJ IDEA is available in both free (Community Edition)
and paid (Ultimate Edition) versions. The Ultimate Edition includes additional
features such as advanced code analysis tools and support for more technologies.
 Productivity Tools:IntelliJ IDEA is known for its intelligent code assistance
features, including smart code completion, code refactoring, and code analysis.
 User Experience:IntelliJ IDEA is praised for its intuitive user interface,
smooth performance, and ergonomic design.
 Built-in Tools:IntelliJ IDEA provides built-in tools for version control, build
automation, and database management, reducing the need for external plugins.
 Frequent Updates: IntelliJ IDEA receives frequent updates and improvements,
ensuring compatibility with the latest Java technologies and frameworks.
NetBeans:
 Oracle Support: Net Beans was originally developed by Sun Microsystems and is
now [Link]
integration with Oracle technologies.
 Cross-Platform: Net Beans is across- platform IDE, available on Windows,
macOS, and Linux.
 Ease of Use: NetBeans is known for its simplicity and ease of use, making it
suitable for beginners and experienced developers alike.
 Comprehensive Tooling:NetBeans provides comprehensive tooling for
Java development, including features for GUI design, web development, and
enterprise application development.
 IntegratedProfiler:NetBeansincludesabuilt-inprofilerforanalyzingapplication
performance, identifying bottlenecks, and optimizing code.

Or acleJDeveloper:
 Tailored for Oracle Technologies:Oracle JDeveloper is specifically designed
for developing applications on Oracle platforms, such as Oracle Fusion Middle
ware and Oracle Database.
 VisualDevelopmentTools:JDeveloper provides visual and declarative
development tools, allowing developers to build enterprise applications using
drag-and-drop components.
 ADFSupport:JDeveloper includes support for Oracle
ADF(ApplicationDevelopment Framework), a Java EE framework for building
scalable and secure enterprise applications.
 Integration with Oracle Products:JDeveloper seamlessly integrates with
Oracle products and technologies, providing features for database development,
application server integration, and cloud deployment.
 Enterprise Support:JDeveloper is backed by Oracle Corporation ,offering
enterprise- level support and services for Oracle customers.

BlueJ:
 Educational Focus: BlueJ is specifically designed for teaching introductory
Java programming concepts, making it popular in educational settings.
 Visual Learning:BlueJ emphasizes visual learning by providing tools for
visualizing object-oriented concepts, such as class diagrams and object
interaction diagrams.
 Simplicity:BlueJ has as impleandintuitive interface, making it easy for beginners to
learn and understand Java programming.
 Minimalistic Features:BlueJ focuses on essential features for learning Java,
without overwhelming users with advanced tools or complexity.
 Supportfor Teaching:BlueJ includes features for teaching programming concepts,
such as step-by-step execution, visualization of object creation, and debugging
support.

[Link] and Contrast Java with Python

Syntax and Readability:


Java: Java has a more verbose syntax compared to Python. It requires semicolons at the
end of each statement and uses curly braces to define blocks of code. Variable types
must be
explicitly declared.
Python: Python has a concise and expressive syntax. It uses indentation to define code
blocks and doesn't require semicolons. Python is dynamically typed, meaning variable
types are inferred at runtime, leading to more readable and concise code.

Typing:
Java: Java is statically typed, meaning variable types must be explicitly declared at
compile time and cannot change during runtime. This can lead to more robust code
but may require more upfront effort.
Python: Python is dynamically typed, allowing variables to change types during runtime.
While this can lead to more flexible and concise code, it may also introduce type-
related errors that are caught only at runtime.

Performance:
Java: Java typically offers faster
execution speed compared to Python due to its compiled nature and optimizations
provided by the Java Virtual Machine(JVM). It is often used for performance-
critical applications.
Python: Python is generally slower than Java as it is interpreted at runtime. However,
form any applications, the difference in performance may not be significant,
especially for tasks that are I/O-bound rather than CPU-bound.
Concurrency:
Java: Java has built-in support formulate threading and concurrency with features like threads
and synchronization. It provides tools like the [Link] package for managing
concurrent tasks safely.

Python: Python also supports concurrency, but it has a Global Interpreter Lock (GIL) that prevents
multiplenative threads from executing Python bytecode simultaneously. As a result, Python's
multithreading may not offer the same level of parallelism as Java.

Community and Ecosystem:


Java: Java has a large and mature ecosystem with extensive libraries, frameworks, and tools for
various domains, including enterprise development, web development, and mobile app
development (Android).

Python: Python has a vibrant and diverse community with a rich ecosystem of libraries and
frameworks fort asks such as web development (Django, Flask), data science(NumPy, Pandas),
machine learning (TensorFlow, PyTorch), and scientific computing.

Usage and Domain:


Java: Java is widely used in enterprise applications, server-side development, Android app
development, and large-scale systems due to its performance, scalability, and platform
independence.

Python:Python is popular for web development, scripting, automation, dataanalysis, machine


learning, and artificial intelligence due to its simplicity, readability, and extensive libraries.
ACTIVITY-2
HOWDOESBYTECODEWORKINJAVA

Bytecode in Java is the reason java is platform-independent, as soon as a Java


program is compiled bytecode is generated. To be more precise a Java bytecode is the
machine code in the form of a .class file.
How does Bytecode Work?

When a Java program is executed, the compiler compiles that piece of code and a
Bytecode is generated for each method in that program in the form of a .class file.
We can run this byte code on any other platform as well. But the byte code is a non-
runnable code that requires or relies on an interpreter. This is where JVM plays an
important part.

The byte code generated after the compilation is run by the Java virtual machine.
Resources required for the execution are made available by the Java virtual machine
for smooth execution which calls the processor to allocate the resources.

Advantages of Bytecode.
Following are a few advantages of Byte code:

 It helps in achieving platform- independence which is one of the


reasons why James Gosling started the formation of Java.
 These to instructions for a JVM may differ from system to
system but can all interpret Byte code.
 Byte codes are non-runnable codes that rely on the availability
of an interpreter, this is where JVM comes into play.
 It is a machine-level language code that run son the JVM.
 It adds portability to Java which resonates with the saying,
“write once, read anywhere”.

Byte code vs Machine code.


 The main difference between the machine code and the bytecode is
that the machine code is a set of instructions in machine language or
binary which can be directly executed by the CPU.
 While the bytecode is a non-runnable code generated by compiling
a source code that relies on an interpreterto get executed.

How Java Program Works

When it comes to programming languages, Java is a versatile and powerful one. It follows a unique
process from code creation to execution. Having a thorough understanding of how a Java program
works is essential for developers, especially if they are newcomers, and aim to strengthen their
foundation to have a seamless journey ahead with the language.

In this guide, we will take you through the fundamental steps included in the compilation and
execution of a Java program.
How Does Java Programming Work?
 Java programming involves a series of steps that transform human-
readable code into machine-executable instructions.
 Let’s break down the process, one step at a time.
 Writing Java Code: Start by writing your Java code using at ext editor or
an integrated development environment (IDE). Java code is usually saved
with a ‘.java’ extension.

 //ExampleJavacode
 publicclassHelloWorld{
 publicstaticvoidmain(String[]args) {
 [Link]("Hello,World!");
 }
 }

 Compilation: Once you have written your Java code, the next step is to
compile it. Compilation is the process of converting human- readable Java
code into byte code, which is a low-level representation of the code that can
be executed only by the Java Virtual Machine (JVM).
 The next step is to open a command prompt or terminal and go to the
directory where your Javacode is located. Uset he ‘javac’ command to
compile the Java source file.

 [Link]

 If there are no errors in the code ,this will generate a byte code with
a ‘.class’ extension (e.g., [Link]).
 Java Virtual Machine (JVM): The computer’s hardware does not execute the
generated bytecode directly. Instead, it runs on the Java
VirtualMachine(JVM). The JVM is platform-independent, allowing Java
programs to run on any machine with a compatible JVM.
 Execution: To run the compiled Java program, use the ‘java’ command
followed by the name of the class containing the 'main' method(the entry
point of the program).

 java HelloWorld

 The JVM reads the bytecode and executes the program, producing the
output on the console.
Conclusion
 Understanding the workflow of the Java program, from code creation to
execution, is crucial for every Java developer. This process of compilation
and execution forms the foundation of Java’s ‘Write Once, Run
Anywhere’ principle.
 As you delve deeper into Java development, you’ll explore more advanced
concepts and features that contribute to the popularity and versatility of the
language.
Activity–3
Inheritance Concept

Inheritance Concept:

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs(Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.

Different types of Inheritance:

OOPs support the six different types of inheritance as given below :

1. Single inheritance
2. Multi-level inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid Inheritance

1. Single inheritance
In this inheritance, a derived class is created from a single base class. In the given
example, Class A is the parent class and Class B is the child class since Class B inherits
the features and behavior of the parent class A.
2. Multi-level inheritance
In this inheritance, a derived class is created from another derived class. In the given
example, class c inherits the properties and behavior of class B and class B inherits the
properties and behavior of class B. So, here A is the parent class of B and class B is the
parent class of C. So, here class C implicitly inherits the properties and behavior of class
A along with Class B i.e there is a multilevel of inheritance.

3. Multiple inheritance
In this inheritance, aderived class is created from more than one base class. This inheritance is
not supported by. NET Languages like C#, F#, etc., and Java Language.

In the given example, class c inherits the properties and behavior of class B and class A at
the same level. So, here A and Class B both are the parent classes for Class C.

4. Hierarchical Inheritance
In this inheritance, more than one derived class is created from a single base class and
further child classes act as parent classes form more than one child class. In the given
example, class
A has two children class B and class D. Further, class Band class C both are having two
children - class D and E; class F and G respectively.

5. Hybrid inheritance
This is a combination of more than one inheritance. Hence, it may be a combination of
Multilevel and Multiple inheritance or Hierarchical and Multilevel inheritance Hierarchical
and Multipath inheritance, or Hierarchical, Multilevel and Multiple inheritances.

Advantages of Inheritance
1. Reduce code redundancy.
2. Provides better code reusability.
3. Reduces source code size and improves code readability.
4. The code is easy to manage and divided into parent and child classes.
5. Supports code extensibility by overriding the base class functionality within child classes.
6. Code usability will enhance the reliability eventually where the base class code will
always be tested and debugged against the issues.

Disadvantages of Inheritance
1. In Inheritance base class and child class, both are tightly coupled. Hence If you change the
code of the parent class, it will affect all the child classes.
2. In a class hierarchy, many data members remain unused and the memory allocated to them
is not utilized. Hence it affects the performance of your program if you have not
implemented inheritance correctly.
Inheritance increases the coupling between the base class and the derived class. any small
change in the base class will directly affect all the child classes which are extended to the
parent classes.
ACTIVITY-4
JAVA KEYWORDS AND THEIR USES

Abstract Specifies that a class or method will be implemented later, in a


subclass.
Assert Assert describes a predicate placed in a Java program to indicate
that the developer thinks that the predicate is always true at that
place
Boolean A data type that can hold True and False values only

Break A control statement for breaking out of loops.

Byte A data type that can hold 8-bit data values.

Case Used in switch statements to mark blocks of text.

Catch Catches exceptions generated by try statements

Char A data type that can hold unsigned 16-bit Unicode characters.

Class Declares a new class.

Continue Sends control back outside a loop

Default Specifies the default block of code in a switch statement

Do Starts a do-while loop.


Double A data type that can hold 64-bit floating-point numbers

Else Indicates alternative branches in an if statement

Enum A Java keyword is used to declare an enumerated type.


Enumerations extend the base class.

Extends Indicates that a class is derived from another class or interface

Protected An access specified indicating that a method or variable may only


be accessed in the class it's declared in (or a subclass of the class
it's declared in or other classes in the same package)
Public An accesss pacifier used for classes, interfaces, methods, and
variables indicating that an item is accessible throughout the
application (or where the class that defines it is accessible).
Final Indicates that a variable holds ac onstant value or that a method
will not be overridden.

Finally Indicates a block of code in a try-catch structure that will


always be executed.

Float A data type that holds a 32-bit floating-point number

For Used to start a for loop.

If Tests a true/false expression and branches accordingly.

Implements Specifies that a class implements an interface.

Instance of Indicates whether an object is an instance of aspecific class or


implements an interface
Import References other classes

Int A data type that can hold a 32-bit signed integer

Interface Declares an interface

Long A data type that holds a 64-bit integer.

Native Specifies that a method is implemented with native(platform


specific) code

New Creates new objects.

Switch A statement that executes code base donates value

Synchronized Specifies critical sections or methods in multithread code

This Refers to the current object in a method or constructor

Throw Creates an exception.

Throws Indicates what exceptions may be thrown by a method

Transient Specifies that a variable is not part of an object's persistent state.

Try Starts a block of code that will be tested for exceptions.


Volatile This indicates that avariable may change a synchronously

While Starts a while loop


ACTIVITY-5
Static and Dynamic Binding in Java
There are certain key points that are needed to be remembered before adhering forward
where we will be discussing and implementing static and dynamic bindings in Java later
concluding out the differences.
 private, final and static members (methods and variables) use static binding while for
virtual methods (In Java methods are virtual by default) binding is done during run time
based upon the run time object.
 The static binding uses Type information for binding while Dynamic binding uses
Objects to resolve to bind.

Static Binding:

The binding which can be resolved at compile time by the compiler is known as static
or early binding. The binding of all the static, private, and final methods is done at
compile- time.

Example:

/Java Program to Illustrate Static Binding

// Main class

class NewClass{

//Staticnestedinnerclass

// Class 1

public static class

superclass {

// Methodofinner class
static void print()

// Print statement

[Link]("

print()insuperclassisc

alled");

//Staticnestedinnerclass

//Class2

publicstaticclasssubclassextendssuperclass{

//Methodofinnerclass

staticvoidprint()

//printstatement

[Link](
"print()in subclassiscalled");

//Methodofmainclass

// Main driver method

publicstaticvoidmain(String[]args)

//Creatingobjectsofstaticinnerclasses

// inside main() method

superclassA=newsuperclass();

superclass B = newsubclass();

//Callingmethodoveraboveobjects [Link]();

[Link]();

Output
print()insuperclassiscalled
print()insuperclassiscalled
Output Explanation: As you can see, in both cases the print method of the
Super class is called. Let discuss how this happens
 We have created one object of subclass and one object of the superclass with the
reference of the superclass.
 Since the print method of the superclass is static, the compiler knows that it will not be
overridden in subclasses and hence compiler knows during compile time which print
method to call and hence no ambiguity.
As an exercise, the reader can change the reference of object B to subclass and then check
the output.
Dynamic Binding
In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect
example of dynamic binding. In overriding both parent and child classes have the same
method.
Let us now finally see the During differences between static and dynamic binding that is
as follows:
Static Binding Dynamic Binding

It takes place at compile time for which is It takes place at run time sodoitis
referred to as early binding referred to as late binding.

It uses overloading more precisely operator


It uses overriding methods.
overloading method

It takes place using normal functions It takes place using virtual functions
ACTIVITY-6
PRINCIPLES HELP TO AVOID CODE SMELL SRP,
OCP, ISP

Introduction:
Code Smells are the traces in the code that indicates a deeper problem in the
application or codebase. They are not bugs or errors but are tangible and observable
violations of code design/development fundamentals that could eventually lead to
poor code quality and technical debt. The code will still compile and perform as
expected, but it may impede the development process and make the program
vulnerable to performance and security issues in the future. Code smells indicate the
underlying issues that lead to technical debt.
SOLID is an acronym for five principles of object-oriented design. These principles can
help developers to create more maintainable and scalable software systems.

Some of the best practices to fix this code smell are:

 Use Extract Function to explain what a block of code does.


 Change Function Declaration to rename the function to explain what a
method does.
 Liskov Substitution Principle(LSP), Interface Segregation Principle (ISP),
and Dependency Inversion Principle (DIP).
 Introduce Assertion to states ome rules about the required state
of the system.

Some other code smells that need your attention are:

 Global Data
 Mutable Data
 Divergent Change
 Shotgun Surgery
 Repeated Switches
 Loops
 Lazy Element
 Speculative Generality
 Temporary Field
 Message Chains
 Insider Trading
 Large Class
 Data Class
 Refused Bequest
Preventing Code Smells:

Violating SRP often results in code smells ,such as large and monolithic
classes, code duplication, and tangled dependencies. Adhering to SRP
helps developers avoid these issues and produce cleaner, more
maintainable code.

RelationtoOtherSOLIDPrinciples:

SRP is one of the SOLID principles, which together for maser of best
practices for object-oriented design. Following SRP complements the
other SOLID principles, such as the Open/Closed Principle (OCP),
Single Responsibility Principle(SRP):

This helps inpreventing code smell such as bloated classes with multiple
responsibilities and promotes a more maintainable and well-structured codebase. A
cleaner codebase contributes to better overall code quality.
SRP advocates that a class should have only one responsibility. By following
SRP, you prevent code smells associated with classes that are trying to do too
much. Each class focuses on a single responsibility, making the code base
more maintainable, and less prone to unintended consequences.

Open/Closed Principles(OCP):

OCP states that software entities should be open for extension but closed for
modification. This means that you should be able to extend the behavior of a module
without modifying its source code. By adhering to OCP, you can avoid code smells
related to frequent modifications challenges. Instead, you can use
techniqueslikeinheritance,composition,anddesignpatternssuchasstrategyor Decorator
to achieve extensibility. One of the SOLID principles, the Open/Closed Principle
(OCP), emphasizes that software entities, such classes, modules, and functions,
should be closed to modification but open for extension. In simpler terms, a module's
behavior can be extended without changing the source code.

Interface Segregation Principle(ISP):

This principle suggests that clients should not be forced to depend on interfaces
they do not use. By adhering to ISP, you can ensure that interfaces are tailored to
specific client requirements, avoiding unnecessary dependencies and potential code
smells related to unused or irrelevant interface methods. ISP splits interfaces that are
very large into smaller and more specific ones so that clients will only have to know
about the methods that are of interest to them.

A class should have small, focused interfaces rather than large, monolithic ones. ISP enables
developers to create more focused and reusable interfaces, reducing the likelihood of
unexpected consequences or errors during software development.
ACTIVITY-7
USING COMMAND LINE ARGUMENTS, WHAT ARE A
COMMAND LINE ARGUMENTS

When you run programs from the command line(pictured below)you enter the name of the
program followed by a list of arguments that the program can access (or ignore).

1. ″Command Line″ Arguments in Eclipse:

When you run a java program, you Would first type the
name of the Interpreter, followed by the name of The
class to run, followed by a list of Arguments.S methi ke
his:

Java Echo Word shell o world


So, when you run your program from Eclipse, where do the ″command
line″ arguments go?

You can specify themby

-Going to the Run menu, -selecting Run Configuration-going to the Argument stab. The
command line arguments can be entered in the Program arguments dialog.

2. Using Command Line Arguments


The operating system reads the command line arguments and passes them to the Java Virtual
Machine. Then JVM passes them to your class inside the String[] args array that is the
parameter to main ().

The length of the array args. length tells your program how many arguments there
are. You should always check that the user provided as many arguments as your
program expects before trying to access them.
The array locations are filled within dividable
arguments: Args [0], …, args [[Link] 1]

All the arguments are passed as String objects. Your program needs to convert the other
types, if need be.

*Example
PublicclassEchoWords{

Publicstaticvoidmain(String[]args){ [Link]("Thereare

%dcommandlinearguments.\n",

[Link]); for (int i

=0;i <[Link]; i++)

{[Link](args[i]);

For(inti =[Link]-1;i>= 0; i--) {[Link](args[i]);

}
ACTIVITY 8
Java Versions and Features

Java 21 Features
Java 21 is set to be released on 19-Sep-2023, as the next long-term support (LTS) release
of Oracle’s standard Java implementation. Java 21 will have the following 15 features.

String Templates
Sequenced Collections
Generational ZGC Record
Patterns Pattern Matching
for switch
Java18Features

Java 18 GA was released on 22 March 2022. It has nine new developer features,
including a simple web server and another preview of pattern matching for switch.

The below-listed 14 JEPs are part of Java18.


JEP- 400: UTF-8 by Default
JEP-408:Simple Web Server
JEP-413:Code Snippets in Java API Documentation
JEP-416:Reimplement Core Reflection with Method
Handles JEP-417: Vector API (Third Incubator)
JEP-418:Internet-Address Resolution SPI
JEP-419:Foreign Function & Memory API
(SecondIncubator) JEP-420: Pattern Matching for switch
(Second Preview) JEP-421:Deprecate Finalization for
Removal

JDK 21 is the latest long-term support release of Java SE Platform. JDK 22.
JDK 21.
JDK 17.
GraalVMforJDK22.
GraalVMforJDK21.
Java17Features(LTS)
Java 17was released on September 14, 2021. Java 17 is an LTS (Long Term
Support)release, like Java11 and J ava8.Spring6andSpringboot 3willhave
[Link] for upgrading to Java
17. Thebelow-listed14JEPsarepartofJava 17.
 (JEP-306) Restore Always- Strict Floating-Point Semantics
 (JEP-356)Enhanced Pseudo-Random Number Generators
 (JEP-382)New mac OS Rendering Pipeline
 (JEP-391) macOS/AArch64Port
 (JEP-398)Deprecate the Applet API for Removal
 (JEP-403)Strongly Encapsulate JDK Internals
 (JEP-406)Pattern Matching for switch(Preview)
 (JEP-407)Remove RMI Activation
ACTIVITY 9

What are packages in Java

A set of classes and interfaces grouped together are known as Packages in JAVA. The name
itself defines that pack (group) of related types such as classes, sub-packages, enumeration,
annotations, and interfaces that provide name-space management. Every class is a part of a
certain package. When you need to use an existing class, you need to add the package within
the Java program.

Why Are They Used For?

The benefits of using Packages in Java areas follows:

 The packages organize the group of classes into a single API unit
 It will control then among conflicts
 The access protection will be easier. Protected and default are the access level
control to the package
 Easy to locate there lasted classes
 Reuse the existing classes in packages

You can categorize packages into:

 Built-in Packages
 User-defined Packages

The built-in packages are from the Java API. The JAVA API is the library of pre-defined
classes available in the Java Development Environment. Few built-in packages are below:

 [Link]–Bundlest he fundamental classes


 [Link]-Bundle of input and output function classes
 [Link]–Bundle of abstract window tool kit classes
 [Link]–Bundle of windows application GUI tool kit classes
 [Link]–Bundle of network infrastructure classes
 [Link]–Bundle of collection framework classes
 [Link]–Bundle of creating applet classes
 [Link]-Bundle of related data processing classes
The built-in packages are again categorized into extension packages. These extension packages
start with javax. This is for all the Java languages, which have lightweight component
classes.

 [Link]
 [Link]

Note:The default package imported with node creation is [Link].

User-defined packages are bundles of groups of classes or interfaces created by the programmer
for their purpose.
There are several advantages of using Java Packages, some of them, are as follows–.

 Make easy searching or locating of classes and interfaces.

 Avoid naming conflicts. For example, there can be two classes with the name
Student in two packages, university. Cs dept. Student and college. itdept. Student
 Implement data encapsulation( or data-hiding).
 Provide controlled access: The access specifies protected and default have access
control on package level. A member declared as protected is accessible by classes
within the same package and its subclasses. A member without any access
specifier that is default specifier is accessible only by classes in the same package.
 Reuse the classes contained in the packages of other
programs. Uniquely compare the classes in other packages.
Activity10
WORKINGWITHARRAY

ARRAY
[Link],the elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in array. Normally, an array is a collection
of similar type of elements which has contiguous memory location.

Array in Java is index-based, the first element of the array is stored at the 0th
index,2ndelement [Link]/C++,we can get the length of the array
using the length member. In C/C++, we need to use the size of operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimensional or
multidimensional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
ADVANTAGES

 Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
 Random access: We can get any data located at an index position.

DISADVANTAGES
 Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in Java
which grows automatically.

TYPES OF ARRAY
There are two types of array:

 Single Dimensional Array


 Multi dimensional Array

SINGLE DIMENSIONAL ARRAY:


Syntax to Declare an Array in Java

 datatype[]arr;(or)
 datatype[]arr;(or)
 dataTypearr[];

DECLARATION, INSTALATIONAND
INITIALIZATIONOF JAVAARRAY
We can declare, instantiate and initialize the java array together by:
 inta[]={33,3,4,5};//declaration,instantiationandinitialization
Let's see the simple example to print this array.

 //JavaProgramtoillustratetheuseofdeclaration,instantiation
 //andinitializationofJavaarrayinasingleline
 classTestarray1{
 publicstaticvoidmain(Stringargs[]){
 inta[]={33,3,4,5};//declaration,instantiationandinitialization
 //printingarray
 for(inti=0;i<[Link];i++)//lengthisthepropertyofarray
 [Link](a[i]);
 }}

MULTI DIMENTIONAL ARRAY IN JAVA

In such case,data is stored in row and column based index(also known as matrix form).
Syntax to Declare Multi dimensional Array in Java

 dataType[][]arrayRefVar;(or)
 dataType[][]arrayRefVar;(or)
 dataTypearrayRefVar[][];(or)
 dataType[]arrayRefVar[];

EXAMPLE TO INSTANTIATE MULTI DIMENSIONAL ARRAY IN


JAVA
 int[][]arr=newint[3][3];//3rowand3column
EXAMPLE TO INITIALIZE MULTIDIMENSIONAL ARRAY IN JAVA
 arr[0][0]=1;
 arr[0][1]=2;
 arr[0][2]=3;
 arr[1][0]=4;
 arr[1][1]=5;
 arr[1][2]=6;
 arr[2][0]=7;
 arr[2][1]=8;
 arr[2][2]=9;

EXAMPLE OF MULTIDIMENSIONAL JAVA ARRAY


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

 //JavaProgramtoillustratetheuseofmultidimensionalarray
 classTestarray3{
 publicstaticvoidmain(Stringargs[]){
 //declaringandinitializing2Darray
 intarr[][]={{1,2,3},{2,4,5},{4,4,5}};
 //printing2Darray
 for(inti=0;i<3;i++){
 for(intj=0;j<3;j++){
 [Link](arr[i][j]+"");
 }
 [Link]();
 }
 }}
Activity11
Abstract Class in Java

Abstract class in Java is similar to interface except that it can contain default method

implementation. An abstract class can have an abstract method without body and it

can have methods with implementation also. Abstract keyword is used to create a

abstract class and method. Abstract class in java can’t be instantiated. An abstract

class is mostly used to provide a base for sub classes to extend and implement the

abstract methods and override or use the implemented methods in abstract class.
Abstract Class in Java

Abstract class in Java Important Points

1. Abstract key word is used to create an abstract class in java.


2. Abstract class in java can’t be instantiated.
3. We can use abstract keyword to create an abstract method, an abstract
method doesn’t have body.
4. If a class have abstract methods, then the class should also be
abstract using abstract keyword, else it will not compile.
5. It’s not necessary for an abstract class to have abstract method. We can mark
a class as abstract even if it doesn’t declare any abstract methods.
6. If abstract class doesn’t have any method implementation, its better to use
interface because java doesn’t support multiple class inheritance.
7. The sub class of abstract class in java must implement all the abstract
methods unless the subclass is also an abstract class.
8. All the methods in an interface are implicitly abstract unless
the interface methods are static or default. Static methods and
default
Methods in interfaces are added in Java8,form or details read Java 8 interface
changes.
9. Java Abstract class can implement interfaces without even
providing the implementation of interface methods.
[Link] Abstract class is used to provide common
method implementation to all the subclasses or to
provide default implementation.
[Link] can run abstract class in java like any other class if it has main() method.

Implement Interface using Abstract Class in Java

Interface contains only abstract methods that can’t be instantiated and it is declared by
keyword interface. A class that is declared with
the abstract keyword is known as an abstract class in Java. This is a class that usually
contains at least one abstract method which can’t be instantiated and It is also possible
for the class to have no methods at all. The instance of an abstract class can’t be
created.
Now as all methods in an interface are abstract methods there fore we can implement it
using Abstract Class.

When an Abstract Class Implements an Interface

In the section on Interfaces, it was noted that a class that implements an interface must
implement all of the interface's methods. It is possible, however, to define a class that
does not implement all of the interface's methods, provided that the class is declared
to be abstract

Class vs .Interface

First ,let’s look at the differences between a normal concrete class vs. an interface.
A class is a user-defined type that acts as a blueprint for object creation. It can have
properties and methods that represent the states and behaviors of an object,
respectively.
An interface is also a user-defined type that is syntactically similar to a class. It can have
a collection of field constants and method signatures that will be overridden by
interface implementing classes
Interface vs. Abstract Class

An abstract class is nothing but a class that is declared using


the abstract keyword. It also allows us to declare method signatures using the abstract
keyword (abstract method) and forces its subclasses to implement all the declared
methods. Suppose if a class has a method that is abstract, then the class itself must be
abstract.
Abstract classes have no restrictions on field and method modifiers, while in an interface,
all are public by default. We can have instance and static initialization blocks in an abstract
class, whereas we can never have them in the interface.
Abstract classes may also have constructors which will get executed during the child
object’s instantiation.
When to Use an Interface

Let’s look at some scenarios when one should go with an interface:

 If the problem needs to be solved using multiple inheritances and


is composed of different class hierarchies
 When unrelated classes implement our interface. For example,
Comparable provides the compareTo() method that can be
overridden to compare two objects

 When application functionalities have to be defined as a contract, but not


concerned about who implements the behavior .i.e., third- party vendors
need to implement it fully

When to Use an Abstract Class

 When trying to use the inheritance concept in code (share code among many
related classes), by providing common base class methods that the subclasses
override
 If we have specified requirements and only
partial implementation details
 While classes that extend abstract classes have several common fields
or methods (that require non-public modifiers)
 If one wants to have non-final or non-static methods to modifythe states of
an object

Consider using abstract classes and inheritance when our problem makes the
evidence “Aisa B”. For example, “Dog is an Animal”, “Lamborghini is a Car”, etc.
Activity-12
Message Logger

Message Logger:-

Overview The message logger records (system) events on the controller and displays
them in the Message logger editor of the Logic Builder. If an error is detected, this
information can help to localize the error and to solve the issue. The Message logger
editor allows you to retrieve and process data of various message logs consecutively
from the controller. You can also add message logger files which have previously been
saved. The Message logger editor provides the following functions: O Saving the
displayed message logs to a file. O Removing message logs from the list. O Adding
comments to each line. O Highlighting lines with certain properties in a specified
colour.
For a description of the IEC functions for interacting with the message logger, refer to the
System Interface Library Guide: O FC_MsgLogDelete O FC_MsgLogInsert O
FC_MsgLogReset O FC_MsgLogSave You have the following options to open the
Message logger editor: O Double-click the Message logger node in the Devices tree.
O Right-click the Message logger node in the Devices tree and execute the command
Edit object from the contextual menu. O Right-click the Message logger node in the
Devices tree, and execute the command Open view and add message logger from the
contextual menu to open the Message logger editor, and to load a new message log
Elements of the Message logger Editor The Message logger editor contains a list of
message logs numbered consecutively. The displayed time corresponds to the time the
item was added to this editor. To expand the sub entries of a message logger, click the
plus (+) icon to the left of the logger entry. Some entries are highlighted in colour. This
helps you to identify lines with comparable properties within the Message logger. You
can adjust it by right-clicking an entry and executing the commands of the contextual
menu. After
Command of the Keyboard shortcut Description
Contextual menu
Show help of diagnosis F1 Opens the help topic
code Corresponding to the
Diagnostic code
([Link])of the
Selected entry.
Edit comment _ You can add a
comment to each
entry. This allows you
to provide additional
information on the
detected error which
may help future
service requirements.
Copy Ctrl+c Copies the contents of the
selected line to the
Clipboard.
Reset message logger _ Creates an empty
(only available in message logger in the
Logic Builder) Message logger editor
and deletes the message
logger on the controller.
NOTE: All message
logger entries of the
controller are
deleted .Creates an
empty message logger
in the Message logger
editor and deletes the
message logger on the
controller. NOTE: All
message logger entries
of the controller are
deleted.
Save message logger _ Opens a Save as...
to file Save message dialog box. Enter a file
logger to file name and browse to the
directory where you
Want to save the file.
Load message logger _ An Import dialog box is
from file displayed. Browse to the
message logger file that
was saved (by a user or
the application) in the
controller. A new
message logger is added
to the Message logger
editor. A consecutive
Number is assigned, but
No time stamp is created
Remove message logger Deletes one or more
from list selected message loggers
from the list.
Mark lines _ Highlights selected
lines. For further
information
Add message logger _ Adds a new message
from the controller logger to the Message
logger editor inserting a
Consecutive number
and the present time
stamp.

Highlighting Lines You can colour lines to highlight message loggers that have certain
properties in common. Example: You can highlight in pink the rows that contain the
value 2 in the column Type. You can highlight in green the lines with Diag. code =
8002. If you choose a colour that is already assigned to a criterion, the assignment is
overwritten. After you have assigned these criteria, they will be shown for selection as
subentries of the command Mark lines of the contextual menu. To remove a specific
colour highlighting from the list, right- click a line that is highlighted in this colour, and
execute the command Mark lines > unmark. To remove all colours from the list, right-
click one highlighted line and execute the commands Mark lines >unmark all. NOTE: It
may happen that one line matches several valid colour selection criteria. For example,
the colour green and red could correspond to the Diag. code=8014. In this case, the
colour used is the colour that is listed first in the contextual menu. elates

Logger in java
Java Logging API was introducedin1.4andyoucanusejava logging API to log
application messages. In this java logging tutorial, we will learn basic features of Java
Logger. We will also look into Java Logger example of
differentlogginglevels,LoggingHandlers,Formatters,Filters,LogManager and logging
configurations.

Java Logging Levels

1. SEVERE(highest)
2. WARNING
3. INFO
4. CONFIG
5. FINE
6. FINER
7. FINEST

You might also like