[Go to site: main page, start]

0% found this document useful (0 votes)
3 views10 pages

Notes (Core Java)

The document provides an overview of Java fundamentals, including its features, data types, variables, expressions, operators, and the structure of a Java program. It also covers classes, objects, constructors, inheritance, and built-in packages, emphasizing Java's object-oriented nature and its tools for development. Key concepts such as the 'new' operator, 'this' keyword, and static variables are explained, along with the importance of inheritance in Java programming.
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)
3 views10 pages

Notes (Core Java)

The document provides an overview of Java fundamentals, including its features, data types, variables, expressions, operators, and the structure of a Java program. It also covers classes, objects, constructors, inheritance, and built-in packages, emphasizing Java's object-oriented nature and its tools for development. Key concepts such as the 'new' operator, 'this' keyword, and static variables are explained, along with the importance of inheritance in Java programming.
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

Chapter 1.

Java Fundamentals

1. INTRODUCING JAVА
 Java is a class-based, object-oriented, simple programming language. Java makes writing, compiling, and debugging
programming easy. It helps to create reusable code and modular programs.
 Java is used for Mobile applications, Desktop applications, Web applications, Web servers and Application servers,
Games, Database connection, etc.
 Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVМ).
1.1. Features of Java
1. Simple: There are various concepts that makes the Java as a simple language. Java is designed to be easy to learn.
Programs in Java are easy to write and debug because Java does not use the pointers, preprocessor header files,
operator overloading etc.
2. Secure: Java is aimed to be used in networked or distributed environments. Java does not allocate direct pointer to
memory this makes it impossible to accidentally reference memory that belongs to other program.
3. Portable: Being architectural-neutral and having no implementation dependent aspects of the specification makes
Java portable. Java code is portable.
4. Object-oriented: Java is a truly object-oriented language. Almost everything in java is an object. Java has a wide
variety of classes. These classes are organized in various packages. We can use them in our programs while
implementing inheritance
5. Robust: Java is a robust language because it provides many safeguards to ensure reliable code. Java does not allow
pointer which avoids security problem. There is no concept of reference variable.
6. Multithreaded: Java was designed to meet the real-world requirement of creating interactive, networked programs.
To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many
things simultaneously.
2. BASICS OF JAVA- DATA TYPES, VARIABLE, EXPRESSION, OPERATORS, CONSTANT
2.1. Data Types:
A computer has to process various types of data. Data type is a term that refers to the kind of data used in a program.
Every programming language comes with a set of data types ready to use.
1. The Primitive Types:
Various primitive data types are listed like Byte, short, int, long, float, double, Boolean, char.
2. Reference Data Types:
 Reference data types are made by the logical grouping of primitive data types.
 These are called reference data types because they contain the address of a value rather than the value itself.
 Arrays, classes, Enum etc., are the example of reference data type.
2.2. Variables:
Variables are the identifier of the memory location, which used to save data temporarily for later use in the program.
During execution of a program, values can be stored in a variable, and the stored value can be changed.
2.3. Expression:
 Expressions are essential building blocks of any Java program, usually created to produce a new value,
although sometimes an expression assigns a value to a variable.
 Expression evaluation in Java is based upon the following concepts:
1. Type conversion: It has two types based on how the conversion is performed:
i) Implicit conversion: It is also known as automatic conversion. This type of conversion is
performed automatically by Java due to performance reasons.
ii) Explicit conversion: It is also known as Type Casting. There may be situations where you
want to convert a value having a type of size less than the destination type size. In such cases
Java will not help you. You have done it on your own explicitly.
2. Operator Precedence: Operator precedence determines the order in which operators in an expression
are evaluated.

3. Associativity of Operators in Java: If an expression has two operators with similar precedence, the
expression is evaluated according to its associativity (either left to right, or right to left).
2.4. Operators:
1. Unary operators:
+ Unary plus operator; indicates positive value.
- Unary minus operator; negates an expression.
++ Increment operator; increments a value by 1.
-- Decrement operator; decrements a value by 1.
! Logical complement operator; inverts the value of a Boolean.
2. Arithmetic operators:
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
3. Bitwise and Bit Shift Operators
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
4. Logical operator: The logical 88 operator doesn't check the second condition if the first condition is false. It checks
the second condition only if the first one is true.
logical AND &&
logical OR ||
5. Ternary Operator: Java ternary operator is used as one line replacement for if-then-else statement and used a lot in
Java programming. It is the only conditional operator which takes three operands.
Syntax: variable = (expression)? expressionIsTrue: expressionIsFalse;
6. Equality and Relational Operators:
== Equal to
! = Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
2.5. Constant:
A value which is fixed and does not change during the execution of a program is called Constants in java. Java
constants are fixed (known as immutable) data values that cannot be changed.

3. STRUCTURE OF JAVA PROGRAM


 Java program may contain many classes, of which main () is defined in only one class.
 Classes in Java program contain data members and methods, that operate on the data members of the class.
Methods in Java program may contain datatype declarations and executable statements.
 A Java program structure contains following sections:
1. Documentation Section: This section is a set of comment lines giving the name of the program, the
author and the other details, which the programmer would like to refer.
2. Package Statement: In Java files, the first statement allowed is a package statement. This statement
declares a package name and informs the compiler that the classes defined here belong to this package.
For example: package employee;
3. Import Statement: Similar to #include statement in C. Import statement instructs the interpreter to load
the test class contained in package employee. Using import statement; we can access to classes that part
of other named packages.
For example, import [Link]:
4. Interface Statement: An interface is like class but includes group of methods declaration. Interfaces are
used when we want to implement multiple inheritance feature.
5. Class Definition: Java program may contain many/multiple class definition. Classes are primary feature
of Java program. The classes in Java are used to map real-world problems.
6. Main Method Class: Java stand-alone program requires main method as starting point and this is essential
part of program main() method in Java program creates object of various classes and on reaching, end of
the main the program terminate and the control passes back to the operating system.
4. JDK TOOLS:
 The JDK is a software development environment which is used to develop java applications and applets.
 JDK (Java Development Kit) provides environment to develop and run java applications.
 Java Development Kit has a collection of tools for Java Development. JDK contains JRE along with various
development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment
tools.
 The JDK comes with a set of tools that are used for developing and running Java program. It includes:
1. Javac: It is a Java compiler.
2. Java: It is a java interpreter.
3. Javah: It is forjava C header files.
4. Jdb: It is Java debugger.
5. AppletViewer: It is used for viewing the applet.
6. Javap: Java disassembler, which convert byte code into program description.
7. Javadoc: It is used for creating HTML document.
5. STRING
5.1. String (Basic Functions):
 The strings in Java are treated as objects of type 'String' class. This class is present in the package [Link].
 This package contains two string classes like String class, and StringBuffer class.
 The string class is used when we work with the string which cannot change whereas StringBuffer class is
used when we want to manipulate the contents of the string.
 We can use + operator to overload for string objects. Only two operators i.e. '+' & '+=" are overloaded for
string classes. In Java, when we use + operator it allows us to concatenate two or more number of strings
together.
Example: String str = "Kal" + "pa" + "na";
Output: Kalpana

5.2. StringBuffer:
 It is a peer class which provides the functionality of strings. The string generally represents fixed length,
immutable character sequence whereas StringBuffer represents growable and writeable character
sequences.
 Java generally manipulate the strings using + as overloaded operator. StringBuffer class in Java is used to
created mutable (modifiable) string. The StringBuffer class in Java is same as String class except it is
mutable it can be changed.
 The syntax is given below:
String subString(int startIndex, int endIndex)
6. BUILT IN PACKAGES AND CLASSES:
1. java. util: -
[Link] Package contains the collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator,
and a bit array).
1. Scanner: Scanner is a class in [Link] package used for obtaining the input of the primitive types like int,
double, etc. and strings.
2. Date: Java does not have a built-in Date class, but we can import the [Link] package to work with the
date and time API. The package includes many date and time classes.
3. Math: java Math class provides several methods to work on math calculations like min), max(), avg(), sin(),
cos(), tan(), round(), ceil(), floor(), abs() etc.
2. java. lang:
Provides classes that are fundamental to the design of the Java programming language. The most important
classes are object, which is the root of the class hierarchy, and class, instances of which represent classes at run
time.
1. ClassLoader: A class loader is an object that is responsible for loading classes.
2. StringBuffer: A thread-safe, mutable sequence of characters.
3. Thread: A thread is a thread of execution in a program.
Chapter 2. Classes, Objects and Methods

1. CLASS AND OBJECT:


1.1. Classes:
 Classes in Java provide a convenient method for packing together a group of logically related data items and
functions that work on them.
 A class can be defined as, "a template/blueprint that describes the behaviours that object of its type support".
 Example of Class:
Class Employee {
int EmpID;
float salary;
}
1.2. Objects:
 A real-world entity that has state and behaviour is known as an Object. These real-world objects share two
characteristics state and behaviour.
 In simple words, object is an instance of a class. Example:
A cat has states color, name, etc. as well as behaviors like walking and eating.
 Syntax: (Declaration)
<classname> objectname;
Where, classname is the name of the already defined class and the objectname is a valid identifier.
 Syntax: (Creating Objects)
<objectname> = new classname([arguments]);
2. CONSTRUCTOR:
 A constructor is a special method of a class in Java programming that initializes an object of that type.
 Constructors have the same name as the class itself. A constructor is automatically called when an object is created.
 Constructor constructs the values provides data for the object that is why it is known as constructor.
 Syntax:
 class_Name {
Constructor_Name(same as class_Name); // Constructor
{
//constructor body.....
} // end of Constructor
}// end of Class
2.1. Турes of Constructor
I. Default Constructor:
 The constructors which do not accept any argument is called Default Constructor. The argument list is void.
 when the object is created Java creates a no-argument constructor automatically known as Default
Constructor.
 It does not contain any parameters nor does it contain any statements in its body. Its only purpose is to
enable you to create object of class type.
 Default constructor provides the default values to the object like 0, null etc. depending on the tyре.
 Syntax: ConstructorName(){}
II. Parameterized Constructor:
 Constructor can take value, value is called as argument. A constructor that has parameters is known as
Parameterized Constructor. Parameterized constructor is used to provide different values to the distinct
objects.
 Using parameterized constructor, it is possible to initialize objects with different set of values at the time of
their creation. These different set of values initialized to objects must be passed as arguments when
constructor is invoked.
 The syntax for constructor is as follows:
ConstructorName([parameterList]){
//constructor body...
}

3. new OPERATOR, this and static KEYWORD, finalize () METHOD


1. 'new' Operator
 The new operator is used in Java to create new objects. It can also be used to create an array object.
 Instantiates a class by allocating memory for a new object and returning a reference to that memory. We can
also use the new keyword to create the array object.
 Syntaх: NewExample obj = new NewExample();
2. 'this' Keyword
 Many times, it is necessary to refer to its own object in a Method or a Constructor. To allow this Java
defines the 'this' keyword.
 'this' can be used inside any method to refer to the current object. It means that 'this' is always a reference to
the object on which the method was invoked.
 The 'this' is used inside the method or constructor to refer its own object 'this' is always a reference to the
object of the current class type.
 Syntax: [Link]
3. ‘static' Keyword
 The static keyword is used to create variables that will exist independently of any instances created for the
class. Only one copy of the static variable exists regardless of the number of instances of the class.
 Static variables are also known as class variables. Local variables cannot be declared static.
4. finalize () Method
 When the reference of an object is not exists, then it is assumed that object is no longer needed. And the
memory which is occupied by the object is reclaimed. So garbage collector automatically frees the memory
resources used by the objects.
 To add a finalizer to our class, we have to define it as a finalize() method.
 The finalize() method has following general form/Syntax:
protected void finalize() {
// finalization code here...
}

Chapter 3. Inheritance, Package and Collection

1. INHERITANCE:
 Object Oriented Programming (OOP) allows you to create new class based on a class that has been already
defined using inheritance.
 It is an important feature of the OOP's because it supports classifications, reusability of class and defined to
specialization.
 Using inheritance, a class can be inherited by another class. This base class is called superclass and the inherited
class is called as subclass.
 Inheritance can be defined as, "the process where one object acquires the properties of another". The mechanism
of deriving a new class from an old class is called inheritance.
1.1. extends Keyword:
 To inherit a class, we have to simply incorporate the definition of one class into another by using the
'extends' keyword.
 The syntax is given below:
class subclassname extends superclassname {
//Body of the class ...
}
 The keyword 'extends' specifies that the properties of superclassname are extended to subclassname.
2. Types of Inheritance:
1. Single Inheritance:
In this one class extends another class at single level. In case of single inheritance there is only a sub class and its
parent class. It is also called simple inheritance or one level inheritance.
2. Multilevel Inheritance:
We can create any layers/levels in the inheritance as we want, this is called Multilevel Inheritance. This hierarchy
can be created at any level of inheritance. When a subclass is derived from a derived class then this mechanism is
known as the Multilevel Inheritance.

3. Hierarchical Inheritance:
When a class has more than one child classes (sub classes) have the same parent class then such kind of inheritance
is known as Hierarchical Inheritance. In case of hierarchical inheritance, we derive more than one subclass from a
single super class.
3. USE OF 'super' AND 'final' KEYWORD
3.1. Use of 'super' Keyword
A subclass inherits the accessible data fields and methods from its superclass, but the constructors of the superclass
are not inherited in the subclass. They can only be invoked from constructors of the subclass using the keyword
'super'. 'super' keyword is used by subclass to refer its immediate superclass.

Ex,

class Animal {

String color = "White";

class Dog extends Animal {

String color = "Black";

void display() {

[Link]([Link]); // Access parent class variable

[Link](color);

public static void main(String args[]) {

Dog d = new Dog();

[Link]();}

3.2. Use of 'final' Keyword


 The word, 'final' is a keyword in Java Language. The 'final' keyword is used in several different contexts
with the variable declaration, methods and classes as a modifier meaning that what it modifies cannot be
changed in some sense.
 Any 'final' keyword when declared with variables, methods and classes specifically means:
1. A final variable cannot be reassigned once initialized.
2. A final method cannot be overridden.
3. A final class cannot be extended.
 Syntax: final datatype variableName;
 Example: final PI=3.14;

Ex,

class Demo {

final int x = 10;

void display() {

// x = 20; // Error

[Link](x);

public static void main(String args[]) {

Demo d = new Demo();

[Link]();

}
}

3.3. Interface Reference:


 If a class implements an interface, but does not implement all the methods declared by that interface, then
the class must be declared as abstract.
 For example, following class partially implementing the interface-conversions.

abstract class convert implements conversions {

public double gmtokg (double gm) {

return gm/GM TO KG;

4. ABSTRACT CLASS:
 An abstract class is a class in which one or more methods are declared, but not defined. That means the body of
these methods are omitted. Such methods are called Abstract Methods.
 Abstract class cannot be instantiated. Class that is declared with abstract keyword, is known as Abstract Class in
Java.
 Abstract class is a superclass that only defines a generalized form which will be shared by all of its subclasses.
 The purpose of abstract class is to function as base classes which can be extended by subclasses to create a full
implementation.
 Syntax: abstract class name {}
5. ACCESS CONTROL
 In this access of certain members of a class is restricted to specific parts of a program. Access modifiers can be
used to control the access to members of a class.
 There are four access modifiers in Java. They are public, protected, default, private.
 access modifiers (also called access specifiers) are keywords used to control the visibility and accessibility of
classes, variables, methods, and constructors in Java. They help provide security and data hiding in object-
oriented programming.
1. Public: Accessible from anywhere in the program. No restriction on access.
2. Private: Accessible only within the same class. Cannot be accessed outside the class directly.
3. Protected: Accessible within the same package and by subclasses (inheritance).
4. Default (No Modifier): Accessible only within the same package. Also called package-private [Link] 5.
Applet, AWT, Event and Swing Programming

1. APPLET INTRODUCTION:
 Applets are small Java programs that are mainly used in Internet Applications. They can be transported over the
Internet and can be executed using any web browser or an appletviewer.
 Applets which use Swing classes for GUI are inherited from class JApplet. But JApplet inherits Applet so all the
features of Applet are also available to JApplet.
 An Applet is a small Java program that runs inside a web browser or an applet viewer. It is mainly used to create
interactive GUI-based applications that can be embedded in web pages.
 Applet classes extend the [Link] class or [Link].
 Features of Applet
o Runs on the client-side (browser)
o Platform independent (Java bytecode runs on any JVM)
o Uses AWT/Swing for GUI
o Executes in a restricted environment
o No direct access to local system resources (files, OS)
o Event-driven programming model

Restrictions of Applet:

 No Access to Local File System.


 Cannot Execute Local Programs
 No Direct Access to System Resources
 Limited Network Access
 Cannot Load Native Libraries

TYPES OF APPLETS:

1. Local Applet: 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. It is specified or defined by the file name or pathname.
Example: < applet code = “[Link]” height=”500” width=”500”></applet>
2. Remote Applet:
When an applet is created by someone else and we can access it only when we are connecting with the internet. This type
of applet is stored in remote computer and it is known as remote applet. Stored on a remote server and downloaded and
executed via URL.
Example: <applet codebase=[Link] code “[Link]” width=200 height=200 </applet>

APPLET LIFE CYCLE:

Applet runs in the browser and its lifecycle method are called by JVM, when it is loaded and destroyed. Here, are the lifecycle
methods of an Applet:

1. Init (): This method is called to initialized an applet. Called once when applet is first loaded
Used for initialization tasks like Setting layout, initializing variables, loading resources (images, fonts) and Think of it as
a constructor-like method for applets.
2. Start (): This method is called after the initialization of the applet. Invoked each time applet becomes active. Used to Start
animations and Resume threads or processes.
3. Display State (paint () Method): The applet is said to be in display state when the paint method is called. This method can
be used when we want to display output in the screen. This method can be called any number of times. Paint() method is
must in all applets when we want to draw something on the applet window. Automatically called whenever:
o Applet window is opened
o Window is resized
o Screen needs refreshing
4. Stop (): This method can be called multiple times in the life cycle of an Applet. Called when the applet becomes inactive
Used to Stop animations and Suspend threads.
5. Destroy (): This method is called only once in the life cycle of the applet when applet is destroyed. Called when the
applet is completely removed from memory. Used for Releasing resources and Closing files or connections

Init () → start () → paint () → stop () → destroy ()

Applet Tags:

 The Applet tag is an HTML tag used to embed and run a Java applet inside a web page. It tells the browser which applet
to load and how to display it. The <applet> tag is used in HTML to load and execute an applet class file that extends the
java. applet. Applet.
 Syntax of Applet Tag:
<applet code="[Link]" width="300" height="200"></applet>

APPLET CLASSES:

 Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the
browser and works at client side.
1. COLOR: The color class is a part of Java Abstract Window Toolkit (AWT) package. The Color class creates color by
using the given RGBA values where RGBA stands for RED, GREEN, BLUE, ALPHA or using HSB value where HSB
stands for HUE, SATURATION, BRI components.
2. GRAPHICS: The Graphics class is the abstract super class for all graphics contexts which allow an application to draw
onto components that can be realized on various devices, or onto off-screen images as well. A Graphics object
encapsulates all state information required for the basic rendering operations that Java supports. The [Link]
class is used for drawing output in applets.
3. FONT: Text fonts in Java are represented by instances of the [Link] class. A Font object is constructed from a
name, style identifier, and a point size. We can create a Font at any time, but it's meaningful only when applied to a
particular component on a given display device.

LAYOUT MANAGERS:

 Layout means the arrangement of components within the container. In other waywe can say that placing the components
at a particular position within the container.
 The task of layouting the controls are done automatically by the Layout Manager. Layout manager is an object which
determines the way that components are arranged in a frame window. All of the components that we have shown so far
have been positioned by the default layout manager.
 A layout manager automatically arranges our controls within a window by using some type of algorithm. A layout
manager is an instance of any class that implements the LayoutManager interface.
 A Layout Manager in Java is used to control the arrangement (position and size) of components (like buttons, labels,
text fields) inside a container such as a Frame, Panel, or Applet. It belongs to the [Link] package.
 Syntax: void setLayout(LayoutManager layoutObj)

Types of Layout Managers:

1. FlowLayout:
The FlowLayout is one the most popular and simplest layout manager. FlowLayout Manager places components in a
container from left to right in the order in which they were added to the container. FlowLayout is Default layout for
Applet and Panel, Places components left to right in a row and moves to next line if space is full.
Ex, setLayout(new FlowLayout());
2. BorderLayout :
The BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-width
components at the edges and one large area in the center. The four sides are referred to as north (upper region), south
(lower region), east (left region), and west (right region). The middle area is called the center (central region). Each
region can hold one component.
Ex,
setLayout(new BorderLayout());
add(button1, [Link]);
3. GridLayout:
GridLayout components in a two-dimensional grid. When we instantiate a GridLayout, we define the number of rows and
columns. The GridLayout manager places items in rows (left to right) and columns (top to bottom). The number of rows
and columns is defined when the GridLayout manager is created. All cells are equal size.
Ex,
setLayout (new GridLayout (2, 3));

Adapterclasses:
 Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class, you will not
be forced to provide the implementation of all the methods of listener interfaces.
 An Adapter class is a class that implements a listener interface and provides empty method bodies, so the programmer
can override only the required methods instead of all methods.

Common Adapter Classes:

1. MouseAdapter: An abstract adapter class for receiving mouse events. The methods in this class are empty. This class
exists as convenience for creating listener objects. Used for mouse events and Implements MouseListener.\
2. Key Adapter: Create a listener object using the extended class and then register it witha component using the
component's addKeyListener method. When a key is pressed, released, or typed, the relevant method in the listener
object is invoked, and the KeyEvent is passed to it. Used for keyboard events and Implements KeyListener.

SWING:

 The swing components are defined in the package [Link]. This package provides more powerful and flexible
components. Swing is a Java foundation class's library and it is an extension to do Abstract Windowing Toolkit (AWT).
 Swing is a part of Java used to build Graphical User Interfaces (GUI). It provides a rich set of components like buttons,
labels, text fields, tables, etc., to create interactive desktop applications.
 Swing is a GUI toolkit in Java that provides lightweight, platform-independent components for building window-
based applications.

Features of Swing:

 Platform independent (runs on any OS with JVM)


 Lightweight components (written in Java, not OS-dependent)
 Rich set of controls (JButton, JTable, JTextField, etc.)
 Supports MVC architecture
 Customizable look and feel and Better than AWT in terms of flexibility and UI

Advantages of Swing

 Rich GUI components


 Platform independent
 Customizable UI
 Supports MVC architecture
 Easy to build desktop applications

AWT (Abstract Window Toolkit): AWT (Abstract Window Toolkit) is the earliest GUI framework in Java used to develop
window-based applications. It provides basic components like buttons, labels, text fields, and layouts to create graphical user
interfaces. AWT is part of the [Link] package.

Key Features:

 Provides basic GUI components (Button, Label, TextField, etc.)


 Uses native OS components (platform-dependent)
 Supports event handling (mouse, keyboard events)
 Includes layout managers for arranging components

Characteristics

 Heavyweight components (depend on OS)


 Platform dependent look and feel
 Less flexible compared to Swing

Advantages

 Simple and easy to use


 Direct interaction with system resources,
 Faster performance (uses native components)

You might also like