




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An overview of java programming concepts, including data types, arrays, strings, classes, and exception handling. It covers topics such as two-dimensional arrays, string manipulation, constructors, inheritance, and file input/output streams. The document also includes examples of java code snippets and explanations of key concepts such as break statements, string objects, and exception handling mechanisms. It further explores java's collection framework, jdbc for database connectivity, and swing for gui development. Useful for understanding the fundamentals of java programming and its applications in networked environments. (407 characters)
Typology: Lecture notes
1 / 119
This page cannot be seen from the preview
Don't miss anything!





























































































programming(mku)
(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified) Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, INDIA.
[JAVA PROGRAMMING] Page 1
TEXT BOOK:
REFERENCE BOOKS:
Outcomes: An understanding of the principles and practice of object oriented analysis and design intheconstructionofrobust,maintainableprogramswhichsatisfytheirrequirements; Acompetencetodesign,write,compile,testandexecutestraightforwardprograms using a high levellanguage; An appreciation of the principles of object orientedprogramming; Anawarenessoftheneedforaprofessionalapproachtodesignandtheimportanceof good documentation to the finishedprograms. Beabletoimplement,compile,testandrunJavaprogramscomprisingmorethanone class, to address a particular software problem. DemonstratetheabilitytousesimpledatastructureslikearraysinaJavaprogram. BeabletomakeuseofmembersofclassesfoundintheJavaAPI(suchastheMathclass). Demonstrate the ability to employ various types of selection constructs in a Java program. Be able to employ a hierarchy of Java classes to provide a solution to a given set ofrequirements. Able to develop applications using Applet, AWT, JDBC andSwings
[JAVA PROGRAMMING] Page 3
UNIT I Java Programming‐ History of Java, comments, Data types, Variables, Constants, Scope and Lifetime of variables, Operators, Type conversion and casting, Enumerated types, Control flow‐ block scope, conditional statements, loops, break and continue statements, arrays, simple java stand alone programs, class, object, and its methods constructors, methods, static fields and methods, access control, this reference, overloading constructors, recursion, exploring string class, garbage collection
Introduction
Everywhere you look in the real world you see objects—people, animals, plants, cars, planes, buildings, computers and so on. Humans think in terms of objects. Telephones, houses, traffic lights, microwave ovens and water coolers are just a few more objects. Computer programs, such
as the Java programs you’ll read in this book interacting software objects.
We sometimes divide objects into two categories: animate and inanimate. Animate objects are ―alive‖ theyinmovesomearound andsensedothings. —Inanimate objects, on the other hand, do not move on their own .Objects of both types, however, have some things in common. They all have attributes (e.g., size, shape, color and weight), and they all exhibit behaviors (e.g., a ball rolls, bounces, inflates and deflates; a baby cries, sleep crawls, walks and blinks; a car accelerates, brakes and turns; a towel absorbs water). We will study the kinds of attributes and behaviors that software objects have. Humans learn about existing objects by studying their attributes and observing their behaviors. Different objects can have similar attributes and can exhibit similar behaviors. Comparisons can be made, for example, between babies and adults and between humans and chimpanzees. Object-oriented design provides a natural and intuitive way to view the software design process—namely, modeling objects by their attributes and behaviors just as we describe real- world objects. OOD also models communication between objects. Just as people send messages to one another (e.g., a sergeant commands a soldier to stand at attention), objects also communicate via messages. A bank account object may receive a message to decrease its balance by a certain amount because the customer has withdrawn that amount of money.
Object-Oriented:
Although influenced by its predecessors, Java was not designed to be source-code compatible with any other language. This allowed the Java team the freedom to design with a blank slate. One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally from many seminal object-software environments of the last few decades, Java manages to strike
a balance between the purist’s ―everything is of my way‖ model. The object model in Java i such as integers, are kept as high-performance non objects.
[JAVA PROGRAMMING] Page 4
Object-Oriented Programming:
Object-oriented programming is at the core of Java. In fact, all Java programs are object-oriented this isn’t an option the way that it is Therefore, this chapter begins with a discussion of the theoretical aspects of OOP.
Two Paradigms of Programming:
As you know, all computer programs consist of two elements: code and data. Furthermore,a program can be conceptually organized around its code or around its data. That is, some programs are writtenhappening‖aroundand―whatothersis are wri affected.‖ These are the two paradigms that g
The first way is called the process-oriented model. This approach characterizes a program as a series of linear steps (that is, code). The process-oriented model can be thought of as code acting on data. Procedural languages such as C employ this model to considerable success. Problems with this approach appear as programs grow larger and more complex. To manage increasing complexity, the second approach, called object-oriented programming, was conceived.
Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code. As you will see, by switching the controlling entity to data, you can achieve several organizational benefits.
Procedure oriented Programming:
In this approach, the problem is always considered as a sequence of tasks to be done. A number
of functions are written to accomplish these attention on data.
There are many high level languages like COBOL, FORTRAN, PASCAL, C used for conventional programming commonly known as POP.
POP basically consists of writing a list of instructions for the computer to follow, and organizing these instructions into groups known as functions.
A typical POP structure is shown in below: Normally a flowchart is used to organize these actions and represent the flow of control logically sequential flow from one to another. In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Global data are more vulnerable to an in advent change by a function. In a large program it is very difficult to identify what data is used by which function. In case we need to revise an external data structure, we should also revise all the functions that access the data. This provides an opportunity for bugs to creep in.
Drawback: It does not model real world problems very well, because functions are action oriented and do not really corresponding to the elements of the problem.
Characteristics of POP:
Emphasis is on doing actions. Large programs are divided into smaller programs known as functions. Most of the functions shared global data. Data move openly around the program from function to function. Functions transform data from one form to another. Employs top-down approach in program design.
OOP:
OOP allows us to decompose a problem into a number of entities called objects and then builds data and methods around these entities.
DEF: OOP is an approach that provides a way of modularizing programs by creating portioned memory area for both data and methods that can used as templates for creating copies of such modules on demand.
That is ,an object a considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modifications.
OOP Chars:
Emphasis on data. Programs are divided into what are known as methods. Data structures are designed such that they characterize the objects. Methods that operate on the data of an object are tied together. Data is hidden. Objects can communicate with each other through methods. Reusability. Follows bottom-up approach in program design.
Data Abstraction
An essential element of object-oriented programming is abstraction. Humans manage complexity through abstraction. For example, people do not think of a car as a set ofte ns of thousands of individual parts. They think of it as a well-defined object with its own unique behavior. This abstraction allows people to use a car to drive to the grocery store without being overwhelmed by the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. Instead they are free to utilize the object as a whole.
A powerful way to manage abstraction is through the use of hierarchical classifications. This allows you to layer the semantics of complex systems, breaking them into more manageable pieces. From the outside, the car is a single object. Once inside, you see that the car consists of several subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and so on. In turn, each of these subsystems is made up of more specialized units. For instance, the sound system consists of a radio, a CD player, and/or a tape player. The point is that you manage the complexity of the car (or any other complex system) through the use of hierarchical abstractions.
Encapsulation
An object encapsulates the methods and data that are contained inside it .the rest of the system interacts with an object only through a well defined set of services that it provides.
Inheritance
I have more information about Flora – not necessarily because she is a florist but because she is a shopkeeper. One way to think about how I have organized my knowledge of Flora is in terms of a hierarchy of categories:
Fig : A Class Hierarchy for Different kinds of Material objects
Concepts of classes and objects: Class Fundamentals Classes have been used since the beginning of this book. However, until now, only the most rudimentary form of a class has been used. The classes created in the preceding chapters primarily exist simply to encapsulate the main( ) method, which has been used to demonstrate the basics of the Java syntax.
Thus, a class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably.
The General Form of a Class
When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data.
A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. Classes can (and usually do) get much more complex. The general form of a class definition is shown here:
class classname {
type instance- variable1 ; type instance-variable2 ; // ... type instance-variableN ; type methodname1 ( parameter-list ) { // body of method } type methodname2 (p arameter-list ) { // body of method } // ...
type methodnameN ( parameter-list ) { // body of method } } The data, or variables, defined within a class are called instance variables. The code is contained within methods.^ Collectively, the methods and variables defined within a class are called members of the class. In most classes, the instance variables are acted upon and accessed
by the methods defined for that class. Thus, it is the methods that de can be used.
Declaring Objects
As just explained, when you create a class, you are creating a new data type. You can use this type to declare objects of that type. However, obtaining objects of a class is a two-step process. First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. Ex: Box mybox = new Box();
This statement combines the two steps just described. It can be rewritten like this to show each step more clearly:
As mentioned earlier, Java derives much of its character from C and C++. This is by intent. The Java designers knew that using the familiar syntax of C and echoing the object- oriented features of C++ would make their language appealing to the legions of experienced C/C++ programmers. In addition to the surface similarities, Java shares some of the other attributes that helped make C and C++ successful. First, Java was designed, tested, and refined by real, working programmers.
The Java Buzzwords:
No discussion of the genesis of Java is complete without a look at the Java buzzwords. Although the fundamental forces that necessitated the invention of Java are portability and security, other factors also played an important role in molding the final form of the language. The key considerations were summed up by the Java team in the Following list of buzzwords:
Simple Secure Portable Object-oriented Robust Multithreaded Architecture-neutral Interpreted High performance Distributed Dynamic
Simple Java was designed to be easy for the professional programmer to learn and use effectively. Assuming that you have some programming experience, you will not find Java hard to master. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object- oriented features of C++, most programmers have little trouble learning Java.. Object-Oriented
Although influenced by its predecessors, Java was not designed to be source-code compatible with any other language. Borrowing liberally from many seminal object-software
environments of the last few decades, Java manages to strike a balance between the everything is an
object‖ paradigm and the programming. Robust
The multi platformed environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of Java.
To better understand how Java is robust, consider two of the main reasons for
program failure: memory management mistakes and mishandled exceptional conditions (that is, run-time errors). Memory management can be a difficult, tedious ask in traditional programming environments. For example, in C/C++, the pro grammer must manually allocate and free all dynamic memory. This sometimes leads to problems, because programmers will either forget to free memory that has been previously allocated or, worse, try to free some memory that another part of their code is still using. Java virtually eliminates these problems by managing memory allocation and deallocation for you.
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. The Java run-time system comes with an elegant yet sophisticated solution for multiprocess .synchronization that enables you to construct smoothly running interactive systems. Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow—even on the same machine. Operating system up grades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation forever.‖ To a great extent, this goal was accomplished.
Interpreted and High Performance
As described earlier, Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be interpreted on any system that provides a Java Virtual Machine. Most previous attempts at cross platform solutions have done so at the expense of performance. Other interpreted systems, such as BASIC, Tcl, and PERL, suffer from almost insurmountable performance deficits. Java, however, was designed to perform well on very low-power CPUs.
Distributed
Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. The original version of Java (Oak) included features for intra address-space messaging. This allowed objects on two different computers to execute procedures remotely. Java revived these interfaces in a package called Remote MethodInvocation ( RMI ). This feature brings an unparalleled level of abstraction to client/server programming.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of bytecode may be dynamically updated on a running system.
Java defines eight simple (or elemental) types of data: byte , short , int , long , char , float , double , and boolean. These can be put in four groups:
Integers This group includes byte , short , int , and long , which are for whole valued signed numbers.
Floating-point numbers This group includes float and double , which represent numbers with fractional precision.
Characters This group includes char , which represents symbols in a character set, like letters and numbers.
Boolean This group includes boolean , which is a special type for representing true/false values.
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are
useful when you need a fractional component, but don’t require example, float can be useful when representing dollars and cents.
Here are some example float variable declarations: float hightemp, lowtemp; double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations.
Here is a short program that uses double variables to compute the area of a circle: // Compute the area of a circle. class Area {
public static void main(String args[]) { double pi, r, a; r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately a = pi * r * r; // compute area System.out.println("Area of circle is " + a); } } Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the same as char in C or C++. In C/C++, char is an integertype that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to representcharacters.. There are no negative char s. The standard set of characters known asASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1,ranges from 0 to 255. Booleans
Java has a simple type, called boolean , for logical values. It can have only one of twopossible values, true or false. This is the type returned by all relational operators, suc has a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if and for. Here is a program that demonstrates the boolean type: There are three interesting things to notice about this program. First, as
you can see,when a boolean value is output by println( ) , ―true‖ or ―false‖ Second,the value of a boolean variable is sufficient, by itself, to control the if statement. Thereis no need to write an if statement like this: if(b == true) ... Third, the outcome of a relational operator, such as < , is a boolean value. This is why
the expression 10 > 9 displays the value ―true.‖ Further, around 10 > 9 is necessary because the + operator has a higher precedence than the >. Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. These elementsare examined next.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: type identifier [ = value ][, identifier [= value ] ...] ;
The type is one of Java’s atomic types, or the nam interface types are discussed later in Part I of this book.) The identifier is the name of the variable.
Here are several examples of variable declarations of various types. Note that some include an initialization.
int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing // d and f. byte z = 22; // initializes z. double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'. The Scope and Lifetime of Variables
So far, all of the variables used have been declared at the start of the main( ) method. However, Java allows variables to be declared within any block. As explained in Chapter 2, a block is begun with an opening curly brace and ended by a closing curlybrace. A block defines a scope. Thus, each time you start a new block, you are creating a new scope. As you probably know from your previous programming experience, a scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects. Most other computer languages define two general categories of scopes: global and local.
However, these traditional scopes do not fit scope defined by a method begins with its opening
curly brace.
To understand the effect of nested scopes, consider the following program: // Demonstrate block scope. Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific elementin an array is accessed by its index. Arrays offer a convenient means of grouping related information. One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must create an array variable of the desired type. The general form of a one dimensional array declaration is
type var-name [ ];
Here, type declares the base type of the array. The base type determines the data type of each element that comprises the array.
// Demonstrate a one-dimensional array. class Array {
public static void main(String args[]) { int month_days[];
month_days = new int[12]; month_days[0] = 31; month_days[1] = 28;
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:
Operator Result
use them on boolean types, but you can use them on char types, since the char type in Java is, essentially, a subset of int. The Bitwise Operators
Java defines several bitwise operators which can be applied to the integer types, long , int , short , char , and byte. These operators act upon the individual bits of their operands. They are summarized in the following table: Operator Result ~ Bitwise unary NOT & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR
Shift right
Shift right zero fill << Shift left &= Bitwise AND assignment
|= Bitwise OR assignment ^= Bitwise exclusive OR assignment
= Shift right assignment
= Shift right zero fill assignment <<= Shift left assignment
Relational Operators
The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. The relational operators are shown here:
Operator Result == Equal to != Not equal to
Greater than < Less than = Greater than or equal to <= Less than or equal to
The outcome of these operations is a boolean value. The relational operators are most frequently used in the expressions that control the if statement and the various loop statements.
The Assignment Operator You have been using the assignment operator since Chapter 2. Now it is time to take
a formal look at it. The assignment operator is the single equal sign, =. The assignment operator works in Java much as it does in any other computer language. It has this general form: var = expression ; Here, the type of var must be compatible with the type of expression.
The assignment operator does have one interesting attribute that you may not be familiar with: it allows you to create a chain of assignments. For example, consider this fragment: int x, y, z; x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x , y , and z to 100 using a single statement. This works because the = is an operator that yields the value of the right-hand expression. Thus, the value of
z = 100 is 100, which is then assigned to y , which in turn is assigned to x. Using a ―cha assignment‖ is an easy way to set a group of
The? Operator
Java includes a special ternary (three-way) operator that can replace certain types ofif- then-else statements. This operator is the? , and it works in Java much like it doesin C, C++, and C#. It can seem somewhat confusing at first, but the? can be used very effectively once mastered. The? has this general form:
expression1? expression2 : expression
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true , then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the? operation is that of the expression evaluated. Both expression2 and expression3 are required to return the same void type,. which can’t be
CONTROL STATEMENTS if
The if statement was introduced in Chapter 2. It is examined in detail here. The if statement is Java’s conditionalprogrambranchexecution state through two different paths. Here is the general form of the if statement:
if ( condition ) statement1 ; else statement2 ; Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block ). The condition is any expression that returns a boolean value. The else clause is optional.
int a, b; // ... if(a < b) a = 0; else b = 0;
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested if s is the if-else-if ladder. It looks like this:
if( condition ) statement; else if (condition )