0% found this document useful (0 votes)
84 views

S5 Java Programming Using Linux Full Note

This document provides an overview of object-oriented programming concepts in Java, features of the Java programming language, and Java tokens. It discusses the core OOP concepts like objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also lists the main advantages of OOP over procedural programming. For Java features, it covers portability, platform independence, security, robustness, performance, distribution capabilities, and support for multi-threading. Finally, it defines the different types of tokens in Java like keywords, identifiers, literals, operators, separators, comments, and constants.

Uploaded by

Ahsana T.K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views

S5 Java Programming Using Linux Full Note

This document provides an overview of object-oriented programming concepts in Java, features of the Java programming language, and Java tokens. It discusses the core OOP concepts like objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also lists the main advantages of OOP over procedural programming. For Java features, it covers portability, platform independence, security, robustness, performance, distribution capabilities, and support for multi-threading. Finally, it defines the different types of tokens in Java like keywords, identifiers, literals, operators, separators, comments, and constants.

Uploaded by

Ahsana T.K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

S5 - Module -1- Java Programming using Linux

#Concepts of Object oriented programming: is a methodology or paradigm to


design a program using classes and objects. It provides many concepts, they are
1.Object : -Any entity that has state and behavior is known as an object. For example,
a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
-Object can be defined as an instance of a class
eg: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
2. Class:- Collection of objects is called class.
-It is a logical entity.
-A class can also be defined as a blueprint from which you can create an individual
object.
3. inheritance: -When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance.
4. Polymorphism :- If one task is performed in different ways, it is known as
polymorphism. For example: to convince the customer differently, to draw
something, for example, shape, triangle, rectangle, etc.
-In Java, we use method overloading and method overriding to achieve
polymorphism.
-Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.
5. Abstraction:- Hiding internal details and showing functionality is known as abstraction.
For example phone call, we don't know the internal processing.
6. Encapsulation:-Binding (or wrapping) code and data together into a single unit are
known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
-A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here. 7 and 8

* Advantage of OOPs over Procedure-oriented programming language


- OOPs makes development and maintenance easier, whereas, in a procedure-oriented
programming language, it is not easy to manage if code grows as project size increases.
-OOPs provides data hiding, whereas, in a procedure-oriented programming language,
global data can be accessed from anywhere.
* Benefits of OOP / Adv of oops :-

# Features of java: - The reason behind of creating Java is to bring portability and
security feature into a computer language. Beside these two major features, there were
many other features that played an important role in java. They are :
1. Simple: - Java is very easy to learn, and its syntax is simple, clean and easy to
understand. Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features,
Eg; explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2. Object-oriented: - “mukaliundee”

3.portable:- Java is portable because it can carry the Java byte code to any platform. It
doesn't require any implementation

4. Platform Independent:- Java is platform independent because it is different from


other languages like C, C++, etc.
5. Secured:- Java is best known for its security. With Java, we can develop virus-free
systems.
-java provides a secure means of creating internet application.
-java provides secure way to access web application
6. Robust:-The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.

7. High-performance:- Java is faster than other traditional interpreted programming


languages because Java byte code is "close" to native code.
-It is still a little bit slower than a compiled language (e.g., C++).
-Java is an interpreted language that is why it is slower than compiled languages,
e.g., C, C++,
8. Distributed:- Java is distributed because it facilitates users to create distributed
applications in Java.
-This feature of Java makes us able to access files by calling the methods from any
machine on the internet.
-java was designed with the distribution environment .
-java can be transmit, run over internet.
9.Multi-threaded:- A thread is like a separate program, executing concurrently.
-We can write Java programs that deal with many tasks at once by defining multiple
threads.
-The main advantage of multi-threading is that it doesn't occupy memory for each thread.
-It shares a common memory area. Threads are important for multi-media, Web
applications, etc.
10.Dynamic:- Java is a dynamic language. It supports the dynamic loading of classes.
- It means classes are loaded on demand.
*Types of Java Programs:- there are two types of programs can be written. They are:
-Application Program:- Java can be used for writing programs that run in a PC under the control
of the operating system in that machine. Such programs are termed as application programs.
-Applet:- Programs can be written and compiled to give what is called byte codes. These
Byte codes can be downloaded mostly from a remote server and executed without any control
from the local operating system. Such programs are called applets. Or . 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.
#Java environment answer

# java tokens:- In Java, the program contains classes and methods. Further, the
methods contain the expressions and statements required to perform a specific
operation. These statements and expressions are made up of tokens.
-The tokens are the small building blocks of a Java program that are meaningful to
the Java compiler
-The Java compiler breaks the line of code into text (words) is called Java tokens. These
are the smallest element of the Java program.
*Types of Tokens;
1. Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the following
keywords: int, float, if, for, do, char etc
2. Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user.
-It uses letters, underscores, or a dollar sign as the first character.
-The label is also known as a special kind of identifier that is used in the goto statement.
-Remember that the identifier name must be different from the reserved keywords. There
are some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
3.Literals: In programming literal is a notation that represents a fixed value (constant) in
the source code.
-It can be categorized as an integer literal, string literal, Boolean literal, etc.
-It is defined by the programmer. Once it has been defined cannot be changed. Java
provides five types of literals are as follows:
Integer, Floating Point , Character , String , Boolean
4. Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators. There are eight
types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

Ternary (Condition) ? (Statement1) :


(Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>


5. Separators: The separators in Java is also known as punctuators. There are nine
separators in Java, are as follows:
o Square Brackets []: It is used to define array elements.
- A pair of square brackets represents the single-dimensional array, two pairs of
square brackets represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It
separates the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
6. Comments: Comments allow us to specify information about the program inside our Java
code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces. Java provides the following
two types of comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.
*Java Constant /constant :- constants in java refer to fixed values that do not change
during the execution of a program .java supports several types of constants are;

Integer Constants:- refers to a Sequence of digits which Includes only negative or positive
Values and many other things those are as follows
Eg;
-Decimal Integer Constants :- consists of a set of digits 0 through 9, preceded by an
optional –or + sign.
-Ocatal Integer Constants:- consists of any combimation of digits from the set 0
through 7, with an leading 0. Eg: 038, 320, 0456, 0552, 0432
-Hexadecimal Integer Constants :- consists of any combimation of digits from the
set 0 through F, with an leading 0x or 0X eg; 0x4, 0X456, 0x552, 0x32, 0x43
 An Integer Constant must have at Least one Digit
 it could be either positive or Negative
 if no sign is Specified then it should be treated as Positive
 No Spaces and Commas are allowed in Name
Real Constants :- Integer numbers are unable to represent distance, height, temperature,
price, and so on. These informations are contaning fractional parts or real parts like
56.890. Such numbers are called Real or Floating Point Contants .
Single Character Constants :-A Character is Single Alphabet a single digit or a Single
Symbol that is enclosed within Single inverted commas.
1. Character Constant Can hold Single character at a time.
2. Contains Single Character Closed within a pair of Single Quote Marks
3. Single Character is smallest Character Data Type in C.
4. Integer Representation: Character Constant reprent by Unicode
5. It is Possible to Perform Arithmetic Operations on Character Constants

String Constants :-String is a Sequence of Characters Enclosed between double Quotes


These Characters may be digits, Alphabets Like "Hello", "1234" etc.
1. The string is "Sequence of Characters".
2. String Constant is written in Pair of Double Quotes.
3. The string is declared as Array of Characters.
4. In C, String data type is not available.
5. Single Character String Does not have Equivalent unicode Value.
Eg;
"a" String with Single Character
"Ali" String With Multiple Characters
"123" String With Digits

*variables:- is an identifier that denotes a storage location used to store a data value.
-unlike constants the remain unchanged during the execution of a program , a variable
may take diff values at diff times during the execution of the prg.
-variable names may consist of alphabets, digits, underscore(_), and dollar.
-it has some conditions they are;
 Must not begin with a digit.
 Uppercase and lowercase are distinct that means TOTAL and total are diff
 It should not be a keyword
 White space is not allowed
 Variable names can be of any length.
#data types:- every variable in java has a data type. Data types specify the different sizes
and values that can be stored in the variable. There are two types of data types in Java
> Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
.

>>Integer type :- can hold whole numbers such as 123, -96 and 5639. The size of values that can be
stored depend on the integer data type we choose.java supports 4 types of integers they are byte
,short, int,long
>>Floating point type :- integer type can hold only whole numbers and therefore we use another
type known as floating point type to hold numbers containing fractional parts
-There are two kinds of floating point storage in java they are
1) float:- float type values are single- precision numbers
2) double:- double type represent double- precision numbers.
>> Character type/char:-in order to store character constants in memory, java provide a charater
data type called char.The char type assumes a size of 2 bytes but, basically ,it can hold only a single
character.
>>Boolean type:- Is used when we want to test a particular condition during the execution of the
program.
-there are only two value that a Boolean type can take: true or false.
-it is denoted by keyword Boolean and uses only one bit of storage.
>Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

#operators:- java supports a rich set of operators. Operators is a symbol that tells the
computer to perform certain mathematical or logical manipulations.

1.arithmetic
2.Relational operators

3.logical

4.Assignment Operators:
$ = Assign 10+10 = 20
$ += Add and assign
var a=10; a+=20; Now a = 30
$ -= Subtract and assign
var a=20; a-=10; Now a = 10
$ *= Multiply and assign
var a=10; a*=20; Now a = 200
$ /= Divide and assign
var a=10; a/=2; Now a = 5
$ %= Modulus and assign
var a=10; a%=2; Now a = 0
5.increment and decrement

6.conditional

7.Bitwise

*Arithmetic expression
#Control Statements/ decision making
*if statement
1. if Statement: if we want to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
N.B. that if is written in lowercase letters. Using uppercase letters (IF) will generate a JS
error!
2. if…else Statement
If we want to execute some code if a condition is true and another code if the condition is
not true, use the if….else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
3. if…else nesting
We should use the if….else nesting if we want to select one of many sets of lines to execute.
Syntax
if (condition1) {
code to be executed if condition1 is true
}
else if (condition2) {
code to be executed if condition2 is true
}
else {
code to be executed if condition1 and condition2 are not true
}
* switch Statement
We should use the switch statement if we want to select one of many blocks of code to be
executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case
in
the structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
”fig varakkan padikkanam”
* Branching statements:- are the statements used to jump the flow of execution from
one part of a program to another.
-The branching statements are mostly used inside the control statements.
-Java has mainly three branching statements, i.e., continue, break, and return.
-The branching statements allow us to exit from a control statement when a certain
condition meet.
# looping statements:- : if you want to run the same code over and over again, each
time with a different value.
-There are four types of loops in Java;
1)For loop: iterates the elements for the fixed number of times. It should be used if
number of iteration is known. The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
2)while loop: iterates the elements for the infinite number of times. It should be used if
number of iteration is not known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
3)do while loop: iterates the elements for the infinite number of times like while loop.
But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.
Do
{
code to be executed
}
while (condition);
4) for in loop: is used to iterate the properties of an object.
# jump statements:( break, cont, return)

* continue statement:- is used in loop control structure when you need to jump to th
next iteration of the loop immediately. It can be used with for loop or while loop.
- in Java continue statement is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition
- Java continue statement in all types of loops such as for loop, while loop and do-while
loop.
Syn;-
jump-statement;
continue;

* return statement:- is used for returning a value when the execution of the block is
completed. The return statement inside a loop will cause the loop to break and further
statements will be ignored by the compiler.
- This are the important points must remember while returning a value:
o The return type of the method and type of data returned at the end of the method
should be of the same type. For example, if a method is declared with the float
return type, the value returned should be of float type only.
o The variable that stores the returned value after the method is called should be a
similar data type otherwise, the data might get lost.
o If a method is declared with parameters, the sequence of the parameter must be the
same while declaration and method call.
Syn;- return returnvalue; “return value inta edakku space illa”
# labeled loops: in java ,we can give a label to block of statements .
- A label is any valid java variable name.
-To give a label to a loop , place it before the loop with a colon ath the end. eg;

Module -2

#Defining a Class:- A class is a user defined blueprint or prototype from which objects
are created.
-once class type has been defined, we can create “variables” of that type using declarations
that are similar to the basic type declaration.
-in java ,these variables are termed as instances of classes ,which are the actual object.

#Fields declaration:- Data is encapsulated in a class by placing data fields inside the
body of the class definition.
-These variables are called instance variables because they are created whenever an object
of the class is instantiated.
-Instance variables are declared in the same way as local variables are declared.
Syntax: type variable_name;
Example : int num;
String fname;
#Method declaration:- the method in Java is a collection of instructions that
performs a specific task.
- It provides the reusability of code. We can also easily modify code using methods.
-method declaration have four basic parts
1.the name of the method (method name).
2.the type of the value the method returns (type).
3.A list of parameters (parameter list)
4.the body of the method .

#Creating object:-An object in java is a block of memory that contains space to store
all the instance variables.
-Creating an object is referred to as instantiating an object
-object in java are created using the new operator.
-There are three steps when creating an object from a class. They are;
Declaration - A variable declaration with a valid name and an object type.
Instantiation − The new keyword is used to create the object.
Initialization − The new keyword is followed by a call to a constructor. This call
initializes the new object.
Syntax :
Declaration : classname objectname;
Initialization : objectname=new classname();
Both these statements can be combined as follows:
classname objectname=new classname();
Eg; Rectangle rect=new Rectangle();

# Accessing class members:- Objects of a class are created for accessing class
members from outside the class.
-To do this dot operator is used along with objects.
Syn;
objectname.variablename=value;
objectname.methodname(parameter_list);
#method overloading:-in java ,it is possible to create methods that have the same name
,but different parameter lists and different definitions this is called method overloading.
-it is used when object are required to perform similar tasks but different input parameters.
-when we call a method in an object, java matches up the method name first and then the
number and type of parameters to decide which one of the definitions to executed this
process is called polymorphism.
-There are three ways to overload a method, the argument lists of the methods must differ
in either of these.
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters
-if two methods have same name, same parameters and have different return type, then
this is not a valid method overloading.

#Constructors:- A constructor is a special method that is used to initialize an object.


-Every class has a constructor either implicitly or explicitly.
-If we don't declare a constructor in the class then JVM builds a constructor for that class.
This is known as default constructor
Syn;
className (parameter-list)
{ code-statements }
-className is the name of class, as constructor name is same as class name.
- parameter-list is optional, because constructors can be parameterize and
non parameterize as well.
-Java Supports two types of constructors: (2 types)
1) Default Constructor:- In Java, a constructor is said to be default constructor if it does not
have any parameter. Default constructor can be either user defined or provided by JVM
2)Parameterized constructor:- Most often, a constructor that accepts one or more
parameters is needed in a program. Parameters are added to a constructor in the same way
that they are added to a method; just declare them inside the parentheses after the
constructor's name.
Eg; class MyClass.

#constructor overloading:- constructor can also be overloaded.


-Overloaded constructors are differentiated on the basis of their type of parameters or
number of parameters.
-Constructor overloading is not much different than method overloading.
-In case of method overloading, multiple methods with same name but different signature
are defined, whereas in Constructor overloading multiple constructor with different
signature are defined but only difference is that constructor doesn't have return type.
#super keyword:-The super keyword refers to superclass (parent) objects.
-It is used to call superclass methods, and to access the superclass constructor.
-The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
-Usage of Java super Keyword
*super can be used to refer immediate parent class instance variable.
*super can be used to invoke immediate parent class method.
*super() can be used to invoke immediate parent class constructor.
#static Members:- “net ill nokkikonnam”
#Inheritance:- Inheritance is one of the key features of Object Oriented Programming.
-Inheritance provided mechanism that allowed a class to inherit property of another class.
-Inheritance in Java can be best understood in terms of Parent and Child relationship, also
known as Super class (Parent) and Sub class(child) in Java language.
-Inheritance defines is-a relationship between a Super class and its Sub class.
-extends keyword is used to describe inheritance in Java.
-Inheritance promotes the code reusability, the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
-Main disadvantage of using inheritance is that the two classes (parent and child class) gets
tightly coupled.
-This means that if we change code of parent class, it will affect to all the child classes
which is inheriting/deriving the parent class, and hence, it cannot be independent of each
other.
-Java mainly supports only three types of inheritance that are listed below.
1)Single Inheritance:- When a class inherits another class, it is known as a single
inheritance.
2) Multiple inheritance:- is not directly supported in java, To reduce the
complexity and simplify the language, multiple inheritance is not supported in java.
3) Multilevel Inheritance:- When there is a chain of inheritance, it is known
as multilevel inheritance.
4)Heirarchical Inheritance:- When two or more classes inherits a single class, it is
known as hierarchical inheritance.

“multiple um hybid chumma ittakunnathaa”


Q) Why multiple inheritance is not supported in java?
A) To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class. Since compile-time errors are
better than runtime errors, Java renders compile-time error if you inherit 2 classes

# overriding methods:- If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding.
-In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
->Usage
-Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
-Method overriding is used for runtime polymorphism.
->Rules for Method Overriding
-The method must have the same name as in the parent class
-The method must have the same parameter as in the parent class.
-There must be an IS-A relationship (inheritance).
*Difference between Overloading and Overriding
#dynamic method dispatch/Runtime Polymorphism:-is the mechanism in which a
call to an overridden method is resolved at run time instead of compile time.
-When an overridden method is called through a superclass reference, Java determines
which version (superclass/subclasses) of that method is to be executed based upon the type
of the object being referred to at the time the call occurs. Thus, this determination is made
at run time.
-bakki unde”.

#final(variables, methods and classes):- Final modifier is used to declare a


field as final.
-It can be used with variable, method or a class.
-If we declare a variable as final then it prevents its content from being modified.
-The variable acts like a constant.
-Final field must be initialized when it is declared
-If we declare a method as final then it prevents it from being overridden.
-If we declare a class as final the it prevents from being inherited. We cannot inherit final
class in Java.
-A method which is declared using final keyword known as final method. It is useful when
we want to prevent a method from overridden.
-A class can also be declared as final. A class declared as final cannot be inherited.

#Abstract methods and classes:- A class which is declared using abstract keyword is
known as an abstract class.
- An abstract class may or may not have abstract methods
-An abstract class can have concrete methods (normal methods).
-An abstract class you are not allowed to create an object of it. OR It cannot be instantiated.
-It is used for abstraction.
Syntax : abstract class class_name { }

-Method that are declared without any body within an abstract class are called abstract
method.
-The method body will be defined by its subclass.
-Abstract method can never be final and static.
-Any class that extends an abstract class must implement all the abstract methods.
Syntax: abstract return_type function_name (); //No definition.

#Interfaces:- Interface looks like a class but it is not a class.


-An interface can have methods and variables just like the class.
-the variables declared in an interface are public, static & final by default.
-Interface is a concept which is used to achieve abstraction in Java
-. An interface is declared by using the interface keyword.
->Advantages of Interface
It Support multiple inheritance
It helps to achieve abstraction
Interface can extend one or more other interface.
Interface cannot implement a class.
Interface can be nested inside another interface.
*Differentiate Between Concrete Class, Abstract Class, Final Class, Interface. Class, interface,
abstract class, final class are the important component of the Java language.
Concrete Class: A class that has all its methods implemented, no method is present without
body is known as concrete class. In other words, a class that contains only non-abstract
method will be called concrete class.
Abstract Class: A class which is declared as abstract using abstract keyword is known as
abstract class. Abstract contains abstract methods and used to achieve abstraction, an
important feature of OOP programming. Abstract class cannot be instantiated.
Interface: Interface is a blueprint of an class and used to achieve abstraction in Java. Interface
contains abstract methods and default, private methods. We cannot create object of the
interface. Interface can be used to implement multiple inheritance in Java.
Final class: Final class is a class, which is declared using final keyword. Final class are used to
prevent inheritance, since we cannot inherit final class. We can create its object and can
create static and non-static methods as well.888jhycytfty
*Difference between abstract class and interface

#Visibility control:- It is possible to inherit all the members of a class by a subclass using
the keyword extends
-The variables and methods of a class are visible everywhere in the program. However, it
may be necessary in some situations we may want them to be not visible outside.
- We can achieve this in Java by applying visibility.
- The visibility modifiers are also known as access modifiers.
- Java provides three types of visibility modifiers: public, private and protected
-> Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
-> Friendly Access (Default): The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
-> Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
-> Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.

Module – 3
#Arrays:- A group of related data items that share a common name.
-An array is a collection of similar data types.
-Array is a container object that holds values of homogeneous type. It is also known as
static data structure because size of an array must be specified at the time of its
declaration.
-Array starts from zero index and goes to n-1 where n is length of the array.
-Array can be single dimensional or multidimensional
->Features of Array
It is always indexed. Index begins from 0.
It is a collection of similar data types.
It occupies a contiguous memory location.
It allows to access elements randomly.
all arrays are dynamically allocated.
-Initialization of arrays
Eg; int number[] ={35,23,67,45,32}
->Types of Array in java they are;
1)Single Dimensional Array:- Single dimensional array use single index to store
elements.
⫸ Array Declaration
Syntax : datatype[] arrayName;
or datatype arrayName[];
-Java allows declaring array by using both declaration syntax, both are valid.
-The arrayName can be any valid array name and datatype can be any like: int, float,
byte etc. Example : int[ ] arr; char[ ] arr; short[ ] arr; long[ ] arr;
⫸Initialization of Array
Syntax : arrayName = new datatype[size]
-Initialization is a process of allocating memory to an array.
-At the time of initialization, the size of array to reserve memory area is specified.
-new operator is used to initialize an array.
-The arrayName is the name of array, new is a keyword used to allocate memory and
size is length of array.
- Both declaration and initialization can be combined into a single statement
Datatype[] arrayName = new datatype[size]
2)Multidimensional Array:- A multi-dimensional array is very much similar to a single
dimensional array.
-It can have multiple rows and multiple columns unlike single dimensional array, which
can have only one row index.
-It represents data into tabular form in which data is stored into row and columns.
⫸ Array Declaration
Syntax : datatype[ ][ ] arrayName;
⫸Initialization of Array
Syntax : datatype[ ][ ] arrayName = new int[no_of_rows][no_of_columns];

* Jagged array:- is an array that has different numbers of columns elements.


-In java, a jagged array means to have a multi-dimensional array with uneven size of
columns in it.
-Jagged array initialization is different little different. We haveto set columns size for each
row independently.
Example: int[ ][ ] arr = new int[3][ ];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[5];

# String Handling:- String is a sequence of characters.


- It is probably the most commonly used class in java library.
- In java, every string that we create is actually an object of type String.
-One important thing to notice is that once a string object is created it cannot be changed.
* String class -Creating a String object
- String can be created in number of ways. They are;
1) Using a String literal:- String literal is a simple string enclosed in double quotes " ". A
string literal is treated as a String object.
Eg; String s1 = "Hello Java";
2) Using new Keyword:- A new string object can be created by using new operator that
allocates memory for the object.
Eg; String s1 = new String("Hello Java");

* Java String class methods


method Description

char charAt(int index) returns char value for the particular


index
int length() returns string length
String toLowerCase() returns a string in lowercase
String toUpperCase() returns a string in uppercase
String trim() removes beginning and ending
spaces of this string
*StringBuffer class:- StringBuffer class is used to create mutable (modifiable) String
objects.
-string buffer is a peer class of string.
- The StringBuffer class is the same as String class except it is mutable (modifiable) i.e. it
can be changed.
- String represents fixed-length ,while string buffer creates string of flexible length that can
be modified.
-so , string that need modification are handled by string buffer class.
-we can insert character and substrings in the middle of a string , or append another strin
to end.
Method Description
append is used to append the specified string with this string.
insert is used to insert the specified string with this string at the specified position
replace is used to replace the string from specified startIndex and endIndex.
delete is used to delete the string from specified startIndex and endIndex.
reverse() is used to reverse the string.
*differences between String and StringBuffer
#Packages:- Package is a collection of related classes.
-Packages are stored in a hierarchical manner.
-A package can be assumed as a folder or a directory that is used to store similar files.
- Packages are used for Preventing naming conflicts.
-Packages can be considered as data encapsulation (or data-hiding).
->Advantage of Java Package
✶Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
✶Java package provides access protection.
✶Java package removes naming collision.
- two type of packages they are;
1. Java API packages:- The Java API is a library of prewritten classes that are free to use.

-The library is divided into packages and classes.

-Some of the commonly used built-in API packages are:


✦ java.util – consists of language utility classes such as date, time, hashtables etc.

✦ java.lang – include classes for primitive types, mathematical functions, threads,

exceptions etc.
✦ java.applet – classes for creating and implementing applets.
✦ java.io – provide the facilities for input and output.
✦ java.net – include classes for communication with local computers as well as with

internet servers.
2. User defined packages:- User defined packages are Java packages created by user to
categorize their project's classes and interface are known as user-defined packages.
-> Creating packages
-Creating a package in java is quite easy, simply include a package command.
-> Packages – Access Protection
• Anything declared public can be accessed from anywhere.
• Anything declared private cannot be seen outside a class.
• No modifier is the default.
-> Using packages
- Use import to access built-in and user-defined packages.
- import keyword is used
- It is used to access package and its classes into the java program.

# Exception Handling Techniques:- is a mechanism to handle exception at


runtime.
-Exception is a condition that occurs during program execution and lead to program
termination abnormally.
- Exception is an abnormal condition caused by a runtime error in the program.
- When java encounters an error, it creates an exception object and throws it.
- If exception object is not caught and handled properly, the interpreter will display an error
Message.
- exception handling that avoid program termination and continue the execution by
skipping exception code.
-Java exception handling provides a meaningful message to the user about the issue rather
than a system generated message, which may not be understandable to a user.
- Java provides controls to handle exception in the program. These controls are listed below
 try : It is used to enclose the suspected code.
 catch: It acts as exception handler.
 finally: It is used to execute necessary code.
 throw: It throws the exception explicitly.
 throws: It informs for the possible exception.
OR
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred (Throws the exception)
3. Receive the error information(Catch the exception)
4. Take corrective actions (Handle the Exception).
->Exception Types
1. Arithmetic Exception – caused by mathematical errors such as division by zero.
2. Array Index Out Of Bounds Exception – caused by wrong array indices.
3. Array Store Exception – caused when a program tries to store the wrong type of
data in an array
4. IO Exception – caused by general I/O failures.
-> Checked Exception: The exception that can be predicted error at the compile time.
->Unchecked Exception : Unchecked exception are ignored at compile time and checked at
runtime.
-> Exception Handling Techniques are
☞ try and catch
• both are Java keywords and used for exception handling.
• Try is to prepare a block of code that is likely to cause an error condition and throw
an exception.
• Catch block catches the exception thrown by the try block.
☞throw and throws
• Throw is used to throw the exception, whereas throws is declarative for the
method.
• They are not interchangeable.
• If a method is throwing an exception, it should either be surrounded by a try catch
block or the method should have throws clause in its signature.
• Throws clause tells the compiler that this particular exception would be handled by
the calling method.
☞Exception Handling- finally
• When exceptions are thrown, the flow of code follows a non linear path.
• finally block is executed always no matter the exception is caused or caught.

#Multithreading:- Multithreading is a concept of running multiple threads


simultaneously.
-Thread is a lightweight unit of a process that executes in multithreading environment.
-A program can be divided into a number of small processes. Each small process can be
addressed as a single thread (a lightweight process).
-it ia a concept in which the programs are divided into two or more processes which can be
run in parallel.
-Advantage of Multithreading is to reduces the CPU idle time that increase overall
performance of the system.
*multitasking:- In multitasking, tasks are known as heavy weight processes.
-Multitasking is a process of performing multiple tasks simultaneously.
-Multitasking can be achieved either by using multiprocessing or multithreading.
-Process is heavy weight, takes more memory and occupy CPU for longer time that may lead
to performance issue with the system.
-To overcome these issue process is broken into small unit of independent sub-process.
-These sub-process are called threads that can perform independent task efficiently.
-> Difference between multithreading and multitasking.

* Life Cycle of a Thread:-Durind the life of thread ,there are many state of thread they
are;

1. Newborn State:- When a new thread is created, it is in the newborn state.


-The thread has not yet started to run when thread is in this state.
-Schedule it for running using start() method.
-Kill it using stop() method.
2. Runnable State:- A thread that is ready to run is moved to runnable state.
- This state means the thread is ready for execution and is waiting for the availability of the
processor.
- These threads are executed in a FIFO manner.
-If all threads have equal priority, then they are given time slots for execution.
3. Running State :- When thread is executing, it’s state is changed to Running.
-Thread scheduler picks one of the thread from the runnable thread pool and change it’s
state to Running.
-Then CPU starts executing this thread.
-A thread can change state to Runnable, Dead or Blocked from running state .
- A running thread can move to blocked state in the following situations.

4. Blocked State:- When a thread is temporarily inactive, then it’s in one of the following
states: Blocked or Waiting.
-this is tha state when the tread is still alive, but is currently not eligible to run.
5. Dead State/terminated:- Kill the thread using the stop() method.
* Creating Threads:- Threads are implemented in the form of objects and contain a
method called run().
-The heart of the thread is the run() method.
-Threads can be implemented in 2 ways.
1. By extending the Thread class
2. By implementing Runnable interface

Module – 4

#Event Handling:- Event is an object that describes a state change in a source.


- Generated as a consequence of a person interacting with the elements in a GUI.
Eg;Entering a character via keyboard, selecting an item from a list, clicking the mouse etc.
- Events may also occur indirectly like
1. When a timer expires
2. When a counter exceeds a value
3. A software or hardware failure occurs
4. When an operation is completed
*Delegation Event Model:- Defines standard and consistent mechanisms to generate
and process events.
-Source generates an event and sends to one or more listeners.
-Listener simply waits until it receives an event.
-Once received, the listener processes the event and then returns.
-Listeners must register with a source in order to receive an event notification.
-The benefit is that notifications are sent only to listeners that want to receive them.

*Event Sources:- A source is an object that generates an event.


-Occurs when the internal state of that object changes in some way.
-A source must register listeners in order for the listeners to receive notifications about a
specific type of event.
-When an event occurs, all registered listeners are notified and receive a copy of the event
object.- Multicasting
-Some sources allow only one listener to register. When an event occurs, the registered
listener is notified. – Unicasting.

*Event Listeners:- A listener is an object that is notified when an event occurs. It has 2
requirements.
1. It must have been registered with one or more sources to receive notifications about
specific type of events.
2. It must implement methods to receive and process these notifications.
-Methods that receive and process events are defined in a set of interfaces in
java.awt.event.

*Event Class
1. ActionEvent - Generated when a button is pressed, a list item is double-clicked or a
menu item is selected.
2. AdjustmentEvent – Generated when a scroll bar is manipulated.
3. ComponentEvent – Generated when a component is hidden, moved, resized or
becomes visible.
4. ContainerEvent – Generated when a component is added or removed.
5. FocusEvent – Generated when a component gains or loses keyboard focus.
6. InputEvent – Abstract super class for all component input event classes.
7. ItemEvent - Generated when a checkbox or list item is clicked. Also occurs when a
choice selection is made or a checkable menu item is selected or deselected.
8. KeyEvent – Generated when input is received from the keyboard.
9. MouseEvent – Generated when the mouse is dragged, moved, clicked, pressed or
released. Also generated when the mouse enters or exits a component.
10.TextEvent – Generated when the value of a text area or text field is changed.
11.WindowEvent – Generated when a window is activated, closed, deactivated,
deiconified, iconified, opened or quit.

*Event Sources :-A source is an object that generates an event.


-This occurs when the internal state of that object changes in some way.
-Sources may generate more than one type of event.
-A source must register listeners in order for the listeners to receive notifications about a
specific type of event.
-Each type of event has its own registration method

*Event Listener Interface

1. ActionListener – Defines one method to receive action events.


2. AdjustmentListener – Defines one method to receive adjustment events.
3. ComponentListener – Defines 4 methods to recognize when a component is hidden,
moved, resized or shown.
4. ContainerListener – Defines 2 methods to recognize when a component is added to or
removed from a container.
5. FocusListener – Defines 2 methods torecognize when a component loses or gains
keyboard focus.
6. ItemListener – Defines 1 method to recognize when the state of an item changes.
7. KeyListener – Defines 3 methods to recognize when a key is pressed, released or
typed.
8. MouseListener – Defines 5 methods to recognize when a mouse is clicked, enters a
component, exits a component, is pressed or released.
9. MouseMotionListener – Defines 2 methods to recognize when a mouse is dragged or
moved.
10. TextListener – Defines 1 method to recognize when a text value changes.
11. WindowListener – Defines 7 methods to recognize when a window is activated,
closed, deactivated, iconified, deiconified, opened or quit.

#SWINGS:- Swing is a set of classes that provides more powerful and flexible components
such as buttons, checkboxes, labels etc.
Eg; a button may have both an image and a text string associated with it.
-Swing Features
 Light Weight − Swing components are independent of native Operating System's API
as Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
 Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, and table controls.
 Highly Customizable − Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
 Pluggable look-and-feel − SWING based GUI Application look and feel can be changed
at run-time, based on available values.
->Swing architecture “imp annu”

->Swing components
-component is an independent visual control and Java Swing Framework contains a large set
of these components.
-J Component class components are lightweight components.
-container holds a group of components. It provides a space where a component can be
managed and displayed. Containers are of two types
1. Top level Containers
 It inherits Component and Container of AWT.
 It cannot be contained within other containers.
 Heavyweight.
2. Lightweight Containers
 It inherits JComponent class.
 It is a general purpose container.
 It can be used to organize related components together
->JFrame
• JFrame is a java class that is extended by Frame class of Java.
• JFrame is treated as the main window
• Swing version of Frame.
•Top-level window with a title and a border.
->JButton
•JButton class provides functionality of a button.
• Swing version of Button. More powerful than buttons in AWT.
• JButton class has three constructors.

->JLabel
-Swing version of List.
- Displays a list of objects and allows the user to select one or more items.
-It is used to display a single line of read only text.
-The text can be changed by an application but a user cannot edit it directly.
->JCheckBox
-The JCheckBox class is used to create a checkbox.
-It is used to turn an option on (true) or off (false).
-Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".
->JRadioButton
-The JRadioButton class is used to create a radio button.
-It is used to choose one option from multiple options.
-It is widely used in exam systems or quiz.
-It should be added in ButtonGroup to select one radio button only.
->JTextField
-Swing version of TextField.
-JTextField is a subclass of JTextComponent.
-A JTextField object is a visual component that can display one line of editable text of one
font and color at a time.
-The text is placed inside a box.
->JPasswordField
- The JPasswordField creates a display for text field similar to JTextField.
-The only difference is that when text is displayed, the actual characters are replaced by *
character.
-This password field is useful where the text typed by a user is not to be seen by other
people.
->JTextArea
-is a subclass of JTextComponent.
-A JTextArea component displays multiple lines of text in one color and with one font.
-Text area text is displayed as such in the defined window.
-There is no scroll bar to view the text.
->JList JList
-is part of Java Swing package .
- JList is a component that displays a set of Objects and allows the user to select one or
more items .
-JList inherits JComponent class.
->JComboBox
-JComboBox is a part of Java Swing package.
- JComboBox inherits JComponent class.
-JComboBox shows a popup menu that shows a list and the user can select an option from
that specified list.
->JPanel
-The JPanel is a simplest container class.
- It provides space in which an application can attach any other component.
-It inherits the JComponents class.

*Difference between AWT and Swing


Java -5th module bakki
* -ignore, * -imp, * -very imp

*passing parameters to applets :- User defined parameters can be


supplied to an applet using tags.
-The PARAM tag allows you to specify applet-specific arguments in an HTML
page.
-Applets access their attributes with the getParameter( ) method.
- [<PARAM NAME=attributename1 VALUE=value1>]
• Each <PARAM> tab has a NAME attribute and a VALUE attribute.
Example
<Applet>
<PARAM NAME=COLOR VALUE=“Red”>
</Applet>

#Working with graphics


-One of the most important features of Java is its ability to draw graphics.
-We can write Java applets that draw lines, figures of different shapes, images
and text in different fonts and styles
-Every applet has its own area of the screen known as canvas ,
-A Java applet draws graphical image inside its space using the coordinate
system.

-Java coordinate system has the origin (0,0) in the upper left corner.
Positive x values are to the right, and positive y values are to the bottom.
The values of coordinates x and y are in pixels.
->The Graphics Class:-Java’s Graphics class includes methods for drawing many
different shapes, from simple lines to polygons to text in a variety of font
1. drawArc() – draws an arc.
2. drawLine() – draws a straight line.
3. drawOval() – draws an oval.
4. drawPolygon() – draws a polygon.
5. drawString() – displays a string.
6. fillArc() – draws a filled arc.
7. fillOval() – draws a filled oval.
8. fillPolygon() – draws a filled polygon.
9. fillRect() – draws a filled rectangle.
10. getColor() – retrieves the current drawing color.
11.setColor() – sets the drawing color.

•The drawLine():- method takes two pair of coordinates,(x1,y1) and (x2,y2) as


arguments and draws a line between them.
For example the following code draws a straight line from (10,10) to (50,50):
• drawRect():- method takes 4 arguments, first two represents the x and y co-
ordinates of the top left corner of the rectangle and remaining 2 represents
the width and height of the rectangle.
•drawOval():- method can be used to draw a circle.
-Takes 4 arguments. The first 2 represent the top left corner of the imaginary
rectangle and the other 2 represents the width and height of the oval itself.
-If the width and height are same, the oval becomes a circle.
•Color Class We can use static variables in Color to specify a number of
common colors
Example: Color.blue

#JDBC :- JDBC stands for Java DataBase Connectivity.


-which is a standard Java API for database-independent connectivity between
the Java programming language and a wide range of databases.
-Java Application cannot directly communicate with a database to submit data
& retrieve. This is because a database can interpret only SQL statements & not
java language statements.
-JDBC is a mechanism to translate java statements into SQL statements.
-JDBC is a Java API for executing SQL statements.

*JDBC Architecture:- The JDBC API supports both two-tier and three-tier
processing models for database access, but in general JDBC Architecture
consists of two layers:
1. The JDBC API uses a driver manager and database-specific drivers to
provide transparent connectivity to heterogeneous databases.
-The JDBC driver manager ensures that the correct driver is used to
access each data source.
-The driver manager is capable of supporting multiple drivers
connected to multiple heterogeneous databases

“Bakki unde padannu padikkan”

4th module bakki

#LAYOUT MANAGERS:- The Layout Managers are used to arrange


components in a particular manner.
-it is used to control the positioning and size of the components
1)flow layout:-is used to arrange the components in a line ,one after another
(in a flow)
-it is the default layout

-field of flow layout class are;


*public static final int LEFT
*public static final int RIGHT
*public static final int CENTER
2) Grid Layout :-is used to arrange the components in rectangular grid. One
compound is displayed in each rectangle.
-constructors supported by GridLayout are shown here:
*GridLayout( )
*GridLayout(int numRows, int numColumns)
*GridLayout(int numRows, int numColumns, int horz, int vert)

3) card layout:-
4)Border Layout:- is used to arrange the components in five regions: north,
south, east, west, and center.
-Each region (area) may contain one component only.
-The BorderLayout provides five constants for each region:
*public static final int NORTH
*public static final int SOUTH
*public static final int EAST
*public static final int WEST
*public static final int CENTER
-Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the
components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

5) Box Layout:- s used to arrange the components either vertically or


horizontally.
-fields of BoxLayout Class
*Public static final int X_AXIS: Alignment of the components are
horizontal from left to right.
*public static final int Y_AXIS: Alignment of the components are vertical
from top to bottom.
6) Null Layout

You might also like