0% found this document useful (0 votes)
36 views36 pages

Module 1 Java Notes - 1600 - PDF - Gdrive.vip

The document provides an introduction to Java, highlighting its features such as being high-level, robust, object-oriented, and platform-independent. It covers essential concepts including the Java Virtual Machine (JVM), Java Development Kit (JDK), and key object-oriented programming principles like encapsulation, inheritance, and polymorphism. Additionally, it discusses control statements, data types, and the structure of Java programs.

Uploaded by

Renuka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
36 views36 pages

Module 1 Java Notes - 1600 - PDF - Gdrive.vip

The document provides an introduction to Java, highlighting its features such as being high-level, robust, object-oriented, and platform-independent. It covers essential concepts including the Java Virtual Machine (JVM), Java Development Kit (JDK), and key object-oriented programming principles like encapsulation, inheritance, and polymorphism. Additionally, it discusses control statements, data types, and the structure of Java programs.

Uploaded by

Renuka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 36
Page 1 of 37 Sti Sel Vidya Vikas Shikshana Samithi ® e SAI VIDYA INSTITUTE OF TECHNOLOGY (A) C ‘Approved by AICTE, New Delhi, Afliated to VTU, Recognized by Govt of Kamataka Accredited by NBA RAIANUKUNTE, BENGALURU 560 064, KARNATAKA Phone:_080-28468191/96/97/98 ,Email: [email protected], URLwww saividyaacin DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (CSE) Module -1 Introduction to Java Java is a high level, robust, object-oriented, platform independent and secured programming language. The term WORA, write once and run everywhere is often associated with Java language. It means whenever we compile a Java code, we get the byte code (.class file), and that can be executed (without compiling it again) on different platforms provided they support Java. In the year 1995, Java language was developed. It is mainly used to develop web, desktop, and mobile devices. The Terminologies in Java > JVM Uava Virtual Machine): JVM is the specification that facilitates the runtime environment in which the execution of the Java bytecode takes place > Byte Code: Java compiler compiles the Java code to generate the .class file or the byte code. One has to use the javaccommand to invoke the Java compiler. > Java Development Kit (DK): It is the complete Java Development Kit that encompasses everything, including JREUava Runtime Environment), compiler, java docs, debuggers, etc. JDK must be installed on the computer for the creation, compilation, and execution of a Java program. DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. Page 2 of 37 > Java Runtime Environment (RE): JRE is part of the JDK. If a system has only JRE installed, then the user can only run the program. In other words, only the fava command works. The compilation of a Java program will not be possible (the /avac command will not work). » Garbage Collector: Garbage Collectors recollect or delete unreferenced objects. Garbage Collector makes the life of a developer/ programmer easy as they do not have to worry about memory management. Object-Oriented Programming Object-oriented programming (OOP) is at the core of Java. In fact, all Java programs are to at least some extent object-oriented. Object-oriented concepts form the heart of Java just as they form the basis for human understanding. object-oriented programming is a powerful and natural paradigm for creating programs. Two Paradigms All computer programs consist of two elements: code and data. These are the two paradigms that govern how a program is constructed. |. 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. object-oriented programming: 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. The Three OOP Principles object-oriented programming is a powerful and natural paradigm for creating programs. All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism. DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. Page 3 of 37 > Encapsulation * Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. « Encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper. Access to the code and data inside the wrapper is tightly controlled through a well-defined interface. * In Java, the basis of encapsulation is the class. * When you create a class, you will specify the code and data that constitute that class. * Collectively, these elements are called members of the class. « Specifically, the data defined by the class are referred to as member variables or instance variables. \n properly written Java programs, the methods define how the member variables can be used. This means that the behavior and interface of a class are defined by the methods that operate on its instance data. * Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the complexity of the implementation inside the class. Each method or variable in a class may be marked private or public. « The public interface of a class represents everything that external users of the class need to know, or may know. * The private methods and data can only be accessed by code that is a member of the class. Therefore, any other code that is not a member of the class cannot access a private method or variable. Since the private members of a class may only be accessed by other parts of your program through the class’ public methods, you can ensure that no improper actions take place. this means that the public interface should be carefully designed not to expose too much of the inner workings of a class. DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. Page 4 of 37 Public instanc (not recommended) veto Private A methods rrivate © - instance varicbles Figure 2-1. Encapsulation: public methods can be used to protect private data » Inheritance * Inheritance is the process by which one object acquires the properties of another object. * For example, a Golden Retriever is part of the classification dog, which in tum is part of the mamma/ class, which is under the larger class anima/ Without the use of hierarchies, each object would need to define all of its characteristics explicitly. It can inherit its general attributes from its parent. ¢ Most people naturally view the world as made up of objects that are related to each other in a hierarchical way, such as animals, mammals, and dogs. If you wanted to describe animals in an abstract way, you would say they have some attributes, such as size, intelligence, and type of skeletal system. Animals also have certain behavioral aspects; they eat, breathe, and sleep. DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. Page 5 of 37 aa Gee) Cai v Polymorphism * Polymorphism (from Greek, meaning "many forms") is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. * This helps reduce complexity by allowing the same interface to be used to specify a general class ofaction. \tis the compiler's job to select the specific action (that is, method) as it applies to each situation. You, the programmer, do not need to make this selection manually. * Extending the dog analogy, a dog's sense of smell is polymorphic. If the dog smells a cat, it will bark and run after it. If the dog smells its food, it will salivate and run to its bowl. + The same sense of smell is at work in both situations. The difference is what is being smelled, that is, the type of data being operated upon by the dog's nose! This same general concept can be implemented in Java as it applies to methods within a Java program. Reference eee Pieces DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java Two Control Statements ‘The if Statement * It determines the flow of execution based on whether some condition is true or false. Its simplest form is shown here: * _ if(condition) statement; + Here, condition is a Boolean expression. (A Boolean expression is one that evaluates to either true or false) If condition is true, then the statement is executed. If conaitionis false, then the statement is bypassed + Relational operators which may be used in a conditional expression. Here are a few. LE greater than’ Equal to ass ifSample{ public static void main(Stiingl] args) { int ys 0; 0; if(x < y) System out println("*xis less than y"); x = x *2; y) Systemoutorintin("x now equal to y") 72 if(x > y) System.out printin("x now greater than y’); ifo /[this won't display anything iffe == y) System.out println("you won'tsee this" ) } The output generated by this program is shown here! xisless thany xnow equal to y xnow greater than y The for Loop + Loop statements are an important part of nearly any programming language because they provide a way to repeatedly execute some task «The simplest form of the for loop is shown here: + for(nitialization; condition; iteration) statement; DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java Here is a short program that illustrates the for loop: dass ForTest { public static void main(Stringl] args) { int x forix = 0; x<10;x = x#1) System.out printin("This is x: "+ x) ) d This program generates the following output: Thisisx.0 Thisisxc 1 Thisisx:2 This is x3, Thisis 4 Thisisx:5 Thisis x6 Thisisxe7 Thisisx8 This is x $ Using Blocks of Code ‘+ _ Java allows two or more statements to be grouped into blocks of code, also called code blocks + This is done by enclosing the statements between opening and closing curly braces. = Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can For example, dass BlockTest { public static void main(Stringl] args) { ints, y; y= 20; fortx = 0; x<10:x+4){ Systemoutprintin("This is x" + »; System out printin( "This isy:* + yy = y-2; d y h The output generated by this program is shown here: This is x 0 This is y 20 This is x 1 DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java This is y: 18 This is x 2 This is y 16 This is x 3 This is ys 14 This is x 4 This is y: 12 This is 5 This is y: 10 This is x 6 This is y 8 This is x 7 This is ys 6 This is x 8 This is yo 4 This is 9 This is ys 2 Lexical Issues Java programs are a collection of whitespace, identifiers, literals, comments, operators, separators, and keywords, » Whitespace Java is a free-form language. This means that you do not need to follow any special indentation rules. For instance, the Example program could have been written all on one line or in any other strange way you felt like typing it, as long as there was at least one whitespace character between each token that was not already delineated by an operator or separator. In Java, whitespace includes a space, tab, newline, or form feed > Identifiers Identifiers are used to name things, such as classes, variables, and methods. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. They must not begin with a number, lest they be confused with a numeric literal Again, Java is case- sensitive, so VALUE is a different identifier than Value. Some examples of valid identifiers are faugtemp fount ba fiest his is_ok Invalid identifier names include these: feo fighsemp Nova SS DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java > Literals + Aconstant value in Java is created by using a /itera/ representation of it. + For example, here are some literals: fio 86 This is atest” Left to right, the first literal specifies an integer, the next is @ floating-point value, the third is a character constant, and the last is a string. A literal can be used anywhere a value of its type is allowed. >» Comments There are three types of comments defined by Java: single-line and multiline and documentation comment. This type of comment is used to produce an HTML file that documents your program. The documentation comment begins with a /** and ends with a */. Documentation comments are explained in Appendix A. > Separators In Java, there are a few characters that are used as separators. The most commonly used separator in Java is the semicolon. The separators are shown in the following table: Symbol [Name Purpose (> Farentheses [sed to contain lists of parameters in method definition and invocation. Also used for defining precedence in expressions] -ontaining expressions in control statements, and surrounding cast} pes. ) leraces bees to contain the values of automatically initialized arrays. Also| sed to define a blockof code forclasses, methods, and local scopes 1 lerackets sed to declare array types. Also used when dereferencing array values. [semicolon [Terminates statements comma Separates consecutive identifiers in a variable declaration. Also used| 0 chain statements together inside a for statement. period ed to separate package names from subpackages and classes. Als sed to separate a variable or method from a reference variable. colons [Used to create a method or constructor reference, leipsis |ndicates a variable-arity parameter. la lat-sign Begins an annotation. SS DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java > TheJava Keywords + There are 67 keywords currently defined in the Java language * These keywords, combined with the syntax of the operators and separators, form the foundation of the Java language. * In general, keywords cannot be used as identifiers, meaning that they cannot be used as names for a variable, class, or method. fabstract ssert hbootean foreak yt ase leatch har lass const continue efault ldo bouble bse enum xports tends inal Finally float f joto ji limplements _|mport instanceof __|nt interface Jong lmodule hative lhew lnon-sealed pen pens: ackage ermits rivate rotected rovides: uli lecord fequires feturn sealed hort ftatic Isticttp super witch synchronized _fhis fnrow khrows 0 ransient ransitive ses ar oid olatile ile ith eld Data Types, Variables, and Arrays The Primitive Types Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive types are also commonly referred to as simple types, and both terms will be used in this book. 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. DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java Integers + Java defines four integer types: byte, short, int, and long + All of these are signed, positive and negative values. + The width of an integer type should not be thought of as the amount of storage it consumes, but rather as the behaviorit defines for variables and expressions of that type. + Thewidth and ranges of these integer types vary widely, as shown in this table. Name [Width Range Jong fea [-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 jt b2 [147,483,548 to 2.147,483647 hort 6 [32.768 to 32,767 byte Fi28 to 127 byte The smallest integer type is byte. This is a signed 8-bit type that has a range from ~128 to 127. They are also useful when you're working with raw binary data that may not be directly compatible with Java's other built-in types. Byte variables are declared by use of the byte keyword. For example, the following declares two byte variables called b and ¢: byte b,c short short is a signed 16-bit type. It has a range from -32,768 to 32,767. It is the least- used Java type. Here are some examples of short variable declarations: shorts; short t int The most commonly used integer type is int It is a signed 32-bit type that has a range from -2,147,483,648 to 2,147,483,647. The reason is that when byte and short values are used in an expression, they are promoted to int when the expression is evaluated DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java long long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed For example, here is a program that computes the number of miles that light will travel in a specified number of days: /1 Compute distance light travels using long variables. ‘dass Light { public static void main(Stringl] args) « int lightspeed, long days long seconds; long distance; lightspeed = 186000; days = 1000; seconds = days * 24* 60 * 60; // convert to seconds distance = lightspeed * seconds; // compute distance System.outprint("in * + days) System outprint(” days light will travel about "); System outprintin(distance + * miles." y d output: In 1000 days light will travel about 1607040000000 miles. Floating-Point Types Floating-point numbers, also known as rea/ numbers, are used when evaluating expressions that require fractional precision, For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floating- point type. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. SS DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java [Name Width in Bits lhpprovimate Range Htouble a b9e-324 to 1.86+308 float 32. [1.4e-045 to 3.4e+038 float © 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, © 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 modem processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin(), cos(), and sqrt(), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice. Here is a short program that uses double variables to compute the area of a circle: J Compute the area of a circle dass Area { public static void main(Stringl] args) { double pir, @ pi= 2.1416; pitety; System out println("Area of cirde is" + a); } ) Characters “In Java, the data type used to store characters is char. ‘% Akey point to understand is that Java uses Unicode to represent characters. DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java Unicode defines a fully international character set that can represent all of the characters found in all human languages In Java char is a 16-bit type. The range of a char is 0 to 65,535. There are no negative chars. ‘The standard set of characters known as ASCII still ranges from 0 to 127 as always // Demonstrate char data type. ‘dass CharDemo { Public static void main(Stringl] args) { ‘char cht, ch2; cht = 88;// code for X ch2 = System.outprint(‘ch1 and ch2: System.out printingcht + ** + ch2); y d This program displays the following output ch1 and ch2: XY Booleans + Java has a primitive type, called boolean, for logical values. + It can have only one of two possible values, true or false. + This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if and for. lass BoolTest { public static void main(Stringl] args) { boolean b; b = false; System.out printin("b is" +b); b = true; System.out.printin("b is" +b); System.out printin("This is executed."); b = false; if(b) System out printin("This is not executed."); System.out.printin("10 > 9 is" + (10 > 9)}; } , SS DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java The output generated by this program is shown here: bis alse bis tue This is executed. 10> 9is tue A Closer Look at Literals > Integer Literals Integers are probably the most commonly used type in the typical program. Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are describing a base 10 number. ‘Two other bases that can be used in integer literals are octa/(base eight) and hexadecimal (base 16). Octal values are denoted in Java by a leading zero. Integer literals create an int value, which in Java is a 32-bit integer value. When a literal value is assigned to a byte or short variable, no error is generated if the literal value is within the range of the target type. An integer literal can always be assigned to a long variable. You can also specify integer literals using binary. To do so, prefix the value with Ob or OB For example, this specifies the decimal value 10 using a binary literal int 061010; You can embed one or more underscores in an integer literal. Doing so makes it easier to read large integer literals. When the literal is compiled, the underscores are discarded, For example, given int x = 123.456 789; the value given to x will be 123,456,789. The underscores will be ignored. Underscores can only be used to separate digits. They cannot come at the beginning or the end of a literal. It is, however, permissible for more than one underscore to be used between two digits. For example, this is valid: int x = 123_456_789; The use of underscores in an integer literal is especially useful when encoding such things as telephone numbers, customer ID numbers, part numbers, and so on. For example, binary values are often visually grouped in four-digits units, as shown here: int x = 0b1101_0101_0001.1010; DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java > Floating-Point Literals Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers. Examples include 6.022£23, 314159E-05, and 2e+100. Floating-point literals in Java default to double precision. To specify a float literal, you must append an For fto the constant. You can also explicitly specify a double literal by appending a Dor a. Hexadecimal floating-point literals are also supported, but they are rarely used. They must be in a form similar to scientific notation, but a P or p, rather than an E ore, is used For example, 0x12.2P2 is a valid floating-point literal. The value following the P, called the binary exponent, indicates the power-of-two by which the number is multiplied. Therefore, 0x12.2P2 represents 72.5. » Boolean Literals Boolean literals are simple. There are only two logical values that a boolean value can have, true and false The values of true and false do not convert into any numerical representation The true literal in Java does not equal 1, nor does the false literal equal 0 » Character Literals + Characters in Java are indices into the Unicode character set. + They are 16-bit values that can be converted into integers and manipulated with the integer operators, such as the addition and subtraction operators. + Aliteral character is represented inside a pzir of single quotes + All of the visible ASCII characters can be directly entered inside the quotes, such as ‘a, ‘2, and ‘@ ee DEEPIKA G, DEPT. OF CSE, SVIT, BENGALURU OOP with Java > String Literals + String literals in Java are specified like they are in most other languages—by enclosing a sequence of characters between a pair of double quotes. + Examples of string literals are "Hello World" "two\nlines" "\'This is in quotes\"” [Escape Sequence Description dk octal character (dde) W000 [Hexadecimal Unicode character (ooo) : ingle quote . Pouble quote \ Backstash ‘arriage return lew line (also known as line feed) f ‘orm feed t [rab ho fpackspace pace (added by JDK 15) lendtoftine ‘ontinue line (applies only to text blocks; added by JDK 15) Table 3-1 CharacterEscape Sequences 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. Declaring a Variable In Java, all variables must be declared before they can be used. ‘The basic form of a variable declaration is type identifier| = value}, identifier{= value) ...; DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU. OOP with Java ee 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 ¢ intd = 3,0, f= 1) declares three more ints, initializing Wdand f bytez = 22; Hinitalizes 2 double pi = 314159; // declares an approximation of pi char x = ‘ethe variable x has the value Dynamic Initialization Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared. For example, here is a short program that computes the length of the hypotenuse of a right triangle given the lengths of its two opposing sides: dass Dyninit ( Public static void main(Stringll args) ¢ double a = 3.0, b = 40; 11 cis dynamically initialized double ¢ = Math sqrt(a* a+ b* b); System out printin(’ Hypotenuse is" + 0 d y Here, three local variables—a, b, and ¢—are declared. The first two, a and b, are initialized by constants However, cis initialized dynamically to the length of the hypotenuse The program uses another of Java's built-in methods, sqrt), which is_a member of the Math class, to compute the square root of its argument. ‘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 It is not uncommon to think in terms of two general categories of scopes: global and local The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they too are included within the method’s scope. Amethod’s scope ends with its closing curly brace. This block of code is called the method body. Tounderstand the effect of nested scopes, consider the following program: DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU.

You might also like