You are on page 1of 39

JAVA PROGRAMMING

Unit 1 Introduction to Java Features of Java Object Oriented Concepts Data Types Variables Arrays Operators Control Statements Input and Output Scanner and System Class print(),println() & printf() methods

II B.Sc., Computer Science


Dr.R.K.Shanmugam College of Arts & Science, Indili, Kallakurichi - 606202

Java Programming

Department of CS

Introduction and History of Java


v In 1991, a group of programmers by developed a language named Oak by James Gosling at Sun Microsystems. This language was designed to be simple and platform-independent. v CPUs are capable of executing only the machine instructions. Different types of CPU have different sets of machine instructions. v To enable java programs to be executed on multiple CPUs without modifications, java programs are complied into machine instructions that can be understood and executed by a CPU. Such a CPU is called Java Virtual Machine (JVM). v Java program is first compiled into the machine code that is understood by JVM. Such a code is called bytecode. v Java complier is called Just ln Time(JIT) compiler. The JIT compiler compiles the bytecode into executable machine code in real time. v The JIT cannot compile the entire bytecode of a java program into executable machine code all at once, because java Runtime Environment carries out various run time checks that can be performed only at run time. v Java development tools are called java Development Kit. The important development tools included in JDK are Java compiler, java interpreter, java disassemble, java debugger, tools for C Header files, tool for creating HTML documents and tool for viewing java Applets. Tool in JDK appletviewer java javac javadoc javah javap jdb Java interpreter. Java compiler Create documentation in HTML Produces C header files Java disassembler Java debugger Purpose Execute a special type of java program known as applets.

v Three types of programs, namely applets, servlets and stand-alone applications, can be developed by using the rich features available in java. v Applet is a java program that is developed exclusively for the internet. v Applets are embedded in HTML documents that take care of the design of web pages. v Java has revolutionized the usage of the internet, as the applets have added animation and interactivity to the web pages. v One more special type of java program, namely the servlets enable us to obtain dynamic web content in the best possible manner. II B.Sc., Computer Science Dr.R.K.S.College Page 2

Java Programming

Department of CS

Features of Java
Object Oriented Java is a true object oriented programming language. In java everything is an Object. Java comes with a set of classes, arranged in packages with can use in our programs by inheritance. The object model in java is simple and easy to extend Platform independent Java program can be easily moved from one computer system to another, anywhere and anytime. Changes and upgrades in operating system, processors and system resources will not force any changes in java programs. Due to this reason java has become popular language for programming on internet. Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run. Simple, Secure and Robust Java is designed to be easy to learn. Many features of C and C++ are not used in java for example: Java does not support pointer, preprocessor header files, goto statement etc. it also eliminates operator overloading and multiple inheritance. Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time and run time checking for data types. It is garbage collection language relieving the programmers virtually all memory management problems. Java also incorporates the concept of exception handling which captures series errors and eliminates any risk of crashing the system. With Java secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Portable Being architectural neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler and Java is written in ANSI C with a clean portability boundary which is a POSIX subset. Multi-threaded With Java multi-threaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.

II B.Sc., Computer Science Dr.R.K.S.College

Page 3

Java Programming Compiled and Interpreted

Department of CS

Java combines both compiled and interpreted for running programs. First, java complier translates source code into byte code instructions. Second java interpreter generates machine code that can be directly executed by the machine that is running the java program. High Performance With the use of Just-In-Time compilers Java enables high performance. Java speed is comparable to the native C/C++. Java architecture is also designed to reduce overheads during runtime. Distributed Java is designed for the distributed language for creating applications on networks. It has the ability to share both data and programs. Java applications can open and access remote objects on internet as easily as local machine. This enables multiple programmers at multiple remote locations to collaborate and work together on a single project. Dynamic Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

Object Oriented Concepts


Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts: Objects Classes Encapsulation Polymorphism Inheritance Data Binding Message communication

Classes and Objects An object can be considered a "thing" that can perform a set of related activities. A collection of similar objects is known as a class. The set of activities that the object performs defines the object's behavior.

II B.Sc., Computer Science Dr.R.K.S.College

Page 4

Java Programming

Department of CS

Encapsulation Encapsulation is the concept of hiding the implementation details of a class and allowing access to the class through a public interface. For this, it is necessary to declare the instance variables of the class as private or protected. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it. The insulation of the data from direct access by the program is called data hiding. Inheritance Inheritance is the process by which objects of one class acquire the properties of objects of another class. The new class is called a derived class of the original class and the original class is called the base class of the new class. The derived classes are also known as subclasses. A new class is derived from only one base class is known as single inheritance and a new class is derived from one or more class is known as multiple inheritances. Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. They are three forms of polymorphism. The method of a subclass override the methods of a super class is called method overriding. The methods of a subclass implement the abstract methods of an abstract class are called Method overriding of the abstract methods. The methods of a concrete class implement the methods of the interface are called Method overriding through the java interface. Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at runtime. It is associated with polymorphism and inheritance Message Communication An OOPS program consists of a set of objects that communicate with each other. The process of programming in an object oriented language, involves the following basic steps: 1. Creating classes that defines objects and their behavior. 2. Creating objects from class definitions 3. Establishing communication among objects.

II B.Sc., Computer Science Dr.R.K.S.College

Page 5

Java Programming

Department of CS

Java Program Structure


Documentation Section Package Statement Import statements Interface Statements Class Statements Main Method Class { Main Method Definition } Documentation Section The documentation section comprises a set of command lines giving the name of the program. Comments (//) must explain why and what of class and how of algorithms. Java also uses a third style of comment /***/ known as documentation comment. Package Statement The first statement allowed in a java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here belong to this package. Example package student Import statements The next thing after the creation of package before any class definitions may be a number of import statements. This is similar to the #include statement in C. Example import student.test; This statement instructs the interpreter to load the text class contained in the package student. Using import statement, it is possible to access the part of package. Interface statements An interface is like a class but includes a group of method declarations. This is also an optional section and is used only when we wish to implement the multiple inheritance feature in the program. Class Definitions A java program may contain multiple class definitions. Classes are the primary and essential elements of a java program. These classes are used to map the objects of real world problems. The number of class used depends on the complexity of the problem II B.Sc., Computer Science Dr.R.K.S.College Page 6

Java Programming Main method class

Department of CS

Every java stand alone program requires a main method as its starting point; this class is the essential part of a java a program. The main method creates objects of various classes and establishes communications between them. Creating and Executing a Java Program Simple Java Program class Hello { public static void main(String arg[]) { System.out.println("Hello Welcome"); }} //output statement //Main Function //class name

Description of Program Java program is first complied and then interpreted. After compilation, the complied version of the source file is stored in a specified format is called bytecode format. Command for compiling java program is javac Hello.java After compilation, the code is stored under the name Hello.class (Filename of program) which called bytecode which used by Java Virtual machine A Java Virtual Machine (JVM) is a set of programs and data structures that use a virtual machine model for the execution of other computer programs and scripts. The model used by a JVM accepts a form of computer intermediate language commonly referred to as Java bytecode. Output statement : System.out.println("Hello Welcome"); this statement prints string values to output screen Command for running java program java Hello The java interpreter loads the byte code in Hello.class file, starts the execution of our program and loads the necessary

II B.Sc., Computer Science Dr.R.K.S.College

Page 7

Java Programming

Department of CS

Data Types
Data types Primitive Reference

Numeric

Non numeric

Classes

Arrays

Integer

Floating

Character

Boolean

Interface

Constants Constants in java refer to fixed values that do not change during the execution of a program. Java supports several types of constants CONSTANT Numeric constant Character Constants

Integer Constants

Real Constants (Float)

Character Constants

String Constants

Integer Constants An integer constant is always a whole number (0-9). It can be either positive or negative. This data type is further subdivided into four types. Byte, short, int and long on the basics of their size. The size of this data type is show below Type byte short int long Example 14, -120, 20 II B.Sc., Computer Science Dr.R.K.S.College Page 8 Size 1 byte 2 bytes 4 bytes 8 bytes Minimum -27 -215 -231 -263 Maximum 27 - 1 215 - 1 231 - 1 263 - 1

Java Programming Real Constants (Floating type)

Department of CS

A real constant will always have a fractional part (number shows in decimal point). The floating point is further divided into two types float and double. The values of floating point is shown table. Type float double Example 215, 0.95, .95, -.71 Character Constants A single character constant contains a single character enclosed within a pair of single quote marks. The default size that is made available for a char type constant is 2. A char type variable can store only a single character. Example 5, X, ;,s, + Backlash Character Constants Java supports some special backlash character constants that are used in output methods. For example, the symbol \n stands for newline character. The backslash characters are also called escape characters. Backlash character constant \b \n \t \r \f \\ \ \ Meaning Backspace New line Tab Carriage return Form feed Backslash Single quote Double quote Size 4 bytes 8 bytes Minimum 1.04012e 4.9406e-324 Maximum 3.4028e+38 1.7976e+308

String Constants A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters and blank spaces. Example Hello java 2010 WELLDONE ?...! 5+3 Page 9

II B.Sc., Computer Science Dr.R.K.S.College

Java Programming

Department of CS

VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. To name our variables, here are some rules followed are 1. The first character in a variable name should not be a digit. 2. A variable name may consist of alphabets, digits, the underscore character and the dollar characters. 3. A keyword should not be used as a variable name. 4. White spaces are not allowed within a variable name 5. A variable name can be of any length. 6. Java is a case sensitive, uppercase letters and lowercase letters are distinct. Example of Variables Total, average, root_2, branch_code

Declaration of Variables In java, variables are the name of storage locations. After designing suitable variable names, we must declare them to the compiler. Declaration does 1. 2. 3. 4. It tells the compiler what the variable name is It specifies what type of data the variable will hold. The place of declaration decides the scope of the variable. A variable must be declared before it is used in the program. Type variable1, variable2,variableN; Four basic data types are Data type Integer Float Character Boolean(True or False) Examples float cent; double rad char letter,c Declare Name int float/double char Boolean

Syntax

II B.Sc., Computer Science Dr.R.K.S.College

Page 10

Java Programming

Department of CS

OPERATORS
Arithmetic operator Arithmetic operators are used to construct mathematical expressions as in algebra. Operator + * / % Example Program Output class Test { public static void main(String args[]) { int a = 10; int b = 20; int c = 25; int d = 25; System.out.println("a + b = " + (a + b) ); System.out.println("a - b = " + (a - b) ); System.out.println("a * b = " + (a * b) ); System.out.println("b / a = " + (b / a) ); System.out.println("b % a = " + (b % a) ); System.out.println("c % a = " + (c % a) ); } } a + b = 30 a - b = -10 a * b = 200 b/a=2 b%a=0 c%a=5 Meaning Addition or unary plus Subtraction or unary minus Multiplication Division Modulo division

Relational Operator Relational operators are used compare two quantities and depending on their relation, take certain decisions.

II B.Sc., Computer Science Dr.R.K.S.College

Page 11

Java Programming Operator < <= > >= == != Example program class Test { public static void main(String args[]) { int a = 10; int b = 20; System.out.println("a == b = " + (a == b) ); System.out.println("a != b = " + (a != b) ); System.out.println("a > b = " + (a > b) ); System.out.println("a < b = " + (a < b) ); System.out.println("b >= a = " + (b >= a) ); System.out.println("b <= a = " + (b <= a) ); }} is less than is less than or equal to is greater then is greater than or equal to is equal is not equal to Meaning

Department of CS

Output a == b = false a != b = true a > b = false a < b = true b >= a = true b <= a = false

Logical Operator The logical operators && and || are used when form compound conditions by combining two or more relations. Operator && || ! Logical AND Logical OR Logical NOT Meaning

II B.Sc., Computer Science Dr.R.K.S.College

Page 12

Java Programming Example Program class Test { public static void main(String args[]) { int a = true; int b = false; System.out.println("a && b = " + (a&&b) ); System.out.println("a || b = " + (a||b) ); System.out.println("!(a && b) = " + !(a && b) ); }}

Department of CS

OUTPUT a && b = false a || b = true !(a && b) = true

Assignment Operator Assignment operator is used to assign the value of an expression to a variable. The usual assignment operator is = v op = exp; Example x+=y+1; Example Program class Test { public static void main(String args[]) { int a = 10; int b = 20; int c = 0; c = a + b; System.out.println("c = a + b = " + c ); }} Output C=a+b=30

Increment and Decrement Operator Java has two very useful operators not generally found in many other languages. These are the increment and decrement operators ++ and The main use of this operator is for and while loops For example x++ is equal to x=x+1

II B.Sc., Computer Science Dr.R.K.S.College

Page 13

Java Programming

Department of CS

On using x++ and ++x means the same thing when they form statements independently, they behave differently when they are used in expressions on the right hand side of an assignment statement Example Program class Test { public static void main(String args[]) { int d = 25; System.out.println("d++ = " + (d++) ); System.out.println("++d = " + (++d) ); }} Output d++ = 25 ++d = 2

Conditional Operator Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as: variable x = (expression) ? value if true : value if false The operator ? : works on the basic of expression first, then if the value is true it result second operator or its works on third statement. Example program public class Test { public static void main(String args[]){ int a , b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b ); } } Output Value of b is: 30 Value of b is: 20

II B.Sc., Computer Science Dr.R.K.S.College

Page 14

Java Programming Bitwise Operator

Department of CS

Bitwise operators are used for manipulation of data at values of bit level. These operators are used for testing the bits, or shifting them to the right or left. Bitwise operators may not be applied to float or double. The Bitwise Operators are Operator Description & | ^ ~ << >> >>> Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand. Binary XOR Operator copies the bit if it is set in one operand but not both. Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. Shift right zero fill operators. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

Special Operator Java supports some special operators of interest such as instanceof operator and member selection operator (.). Instanceof Operator The instanceof is an object reference operator and returns true if the object on the left hand side is an instance of the class given on the right hand side. This operator allows us to determine whether the object belongs to a particular class or not. Example Person instanceof student Instanceof operator is true if the object person belongs to the class student; otherwise it is false Example Program class Vehicle {} public class Car extends Vehicle { public static void main(String args[]){ Vehicle a = new Car(); boolean result = a instanceof Car; System.out.println( result); }} Output True

II B.Sc., Computer Science Dr.R.K.S.College

Page 15

Java Programming

Department of CS

Dot Operator The dot operator(.) is used to access the instance variables and methods of class objects Example personal.age personal.salary() it is also used to access classes and sub packages from a package Library Methods Library methods are normally used to write the expressions in a compact manner. For example, the expressions 4 2 can be compactly represented as shown below =

(-b + Math.sqrt(b * b 4 * a * c)) / (2 * a) Purpose To find square root of x(>0) To find xy To fine sine of x To find Cosine of x To find Tangent of x To find Arc sin of x To find Arc sine of x To find Arc tangent of x

Library method math.sqrt(x) Math.pow(x,y) Math.sin(x) Math.cos(x) Math.tan(x) Math.asin(x) Math.acos(x) Math.atan(x)

Math.toRadians(x) To convert x radians to degress Math.toDegrees(x) To convert x degress to radians Math.exp(x) Math.log(x) Math.round(x) Math.ceil(x) Math.floor(x) Math.abs(x) To find ex To find natural log To find closest integer to x To find smallest integer >x To find largest integer < x To find the absolute value(x)

II B.Sc., Computer Science Dr.R.K.S.College

Page 16

Java Programming

Department of CS

Input and output Statement


Output Statement (System Class print(),println(),printf()) System.out.print(Welecome to java); System.out.println(Welcome to java); System.out.printf(%d Welcome to java, + a); The out object in the System class represents the standard output stream. The out object has two methods for sending the output to the console screen. They are the print() and the println(). The print() method displays the output without a newline character. The println() method displays the output with a newline character. The printf is used in java for format output with variable type of the output.

Formatting the output Values The formatting the output values are used to round the values in the fractional point. For example 89.246 will be rounded to 89.25, But 89.198 will be rounded to 89.2, not 89.20. This can be achieve this by using the methods in the NumberFormat class Format NumberFormat f = NumberFormat.getNumberInstance(); f.setMaximumFractionDigits(2); System.out.printf("The Float \t:%f" + f.format(d)); The setMaximumFractionDigits is used to number of digits to be rounded. Example program import java.io.*; import java.util.*; import java.text.*; class input2 { public static void main(String arg[]) throws IOException { System.out.print("Enter Number:"); Scanner a =new Scanner(System.in); double b = a.nextDouble(); NumberFormat f = NumberFormat.getNumberInstance(); f.setMaximumFractionDigits(2); System.out.println("The Float \t:" + f.format(b)); }} II B.Sc., Computer Science Dr.R.K.S.College Page 17

Java Programming Input Statement Format System.out.print(Enter your Name:); InputStreamReader a = new InputStreamReader (System.in); BufferedReader b = new BufferedReader(a); String name = in.readLine(); @ @ @ @

Department of CS

In Java, any input is read as a String. The Input value is stored in the buffer System.in. After storing the values in System.in, it can be stored in variable a. An InputStreamReader object (name a) can read one by one character at time, to read whole string use BufferReader and store in variable b. @ The readLine() methods reads in a string and stores in it the String type variable name. Example Program import java.io.*; class input { public static void main(String arg[]) throws IOException { System.out.print("Enter your Name:"); InputStreamReader a = new InputStreamReader (System.in); BufferedReader b = new BufferedReader(a); String name = b.readLine(); System.out.print("The Given String:" + name); }} Output

Enter your Name : rks The Given String : rks

Exception public static void main(String arg[]) throws IOException In the above program in main method use throws IOException. An error is known as exception in java. If a problem is encountered while reading input, the readLine() method will generate an exception of type IOExeption. Java Runtime handle this exception or inform the Runtime.

II B.Sc., Computer Science Dr.R.K.S.College

Page 18

Java Programming Reading Numbers from Input

Department of CS

In Java, any input is read as a String. First integer, float & double value will be initially read in as the string and stored the value in variable text. The parseInt() is a method of Integer class which converts String to integer. This is the standard way of providing an integer value as input to a java program. The parseDouble() is a method of float class which converts String to float value with fractional value. Both the method are used with variable can be stored in any name. Format String name = b.readLine(); int c = Integer.parseInt(b); double c = Double.parseDouble(b); Example Program import java.io.*; class input { public static void main(String arg[]) throws IOException { System.out.print("Enter Number:"); InputStreamReader a = new InputStreamReader (System.in); BufferedReader b = new BufferedReader(a); String name = b.readLine(); double d = Double.parseDouble(name); int c = Integer.parseInt(name); System.out.print("The Integer \t:" + c); System.out.print("\nThe Float \t:" + d); }} Scanner Class v Disadvantage of BufferReader is storing values from InputStreamReader one by one, but stores string values only. It can be then converted into other data types. v Scanner Class is used to get data from input in any data types. v When type a value in a program and retrieve it, it can store in object of the System package (ie : System.in) v After getting the value it can be stored in variables. One of the class is Scanner class. II B.Sc., Computer Science Dr.R.K.S.College Page 19 Enter Number : 1000 The Integer : The Float : 1000 1000.0 Output

Java Programming

Department of CS

v Before using the Scanner class, it is necessary to import the java.util.Scanner package before main function. (ie: import java.util.Scanner) v To use the Scanner class to retrieve a value, use the following format Scanner VariableName = new Scanner(System.in); v After the above Statement, it necessary to declare what type data to be used. The following table shows the type of data type and its keyword Syntax int c = a.nextInt(); double d = a.nextDouble();
Method int nextInt() long nextLong() float nextFloat() double nextDouble() String next() String nextLine() void close() Returns Returns the next token as an int. Returns the next token as a long. Returns the next token as a float. Returns the next token as a long. Finds and returns the next complete token from this scanner and returns it as a string Returns the rest of the current line, excluding any line separator at the end. Closes the scanner.

Example Program import java.io.*; import java.util.*; class input1 { public static void main(String arg[]) throws IOException { System.out.print("Enter Number:"); Scanner a =new Scanner(System.in); int c = a.nextInt(); double d = a.nextDouble(); System.out.println("The Integer \t:" + c); System.out.print("The Float \t:" + d); }}

Output Enter Number: 100 87.23 The Integer : 100 The Float : 87.2

II B.Sc., Computer Science Dr.R.K.S.College

Page 20

Java Programming Strings

Department of CS

v A string is a sequence of characters. In java, string is enclosed in quotation marks. v Keyword used for declaring string variables is String. Example: String Variable-name =String. String a =india v A string that contains no characters is called an empty string. Its length is zero and it is written as . v Methods used to obtain information about an object are known as accessor methods. v Some of the string manipulation in java program is string concatenation, string length, and converting uppercase to lowercase & lowercase to uppercase. Example program for string manipulation import java.io.*; class S{ public static void main(String args[]){ String a = "india"; String a1 = "USA"; int len = a.length(); System.out.println( "String Length is : " + len ); System.out.println( "String Concatenation is : " + a + " " + a1 ); System.out.println( "String Lowercase is : " + a1.toLowerCase() ); System.out.println( "String Uppercase is : " + a.toUpperCase() ); }} Output String Length is : 5 String Concatenation is : india USA String Lowercase is : usa String Uppercase is : INDIA

II B.Sc., Computer Science Dr.R.K.S.College

Page 21

Java Programming

Department of CS

Control Statements
A program is a group of statements that are executed to achieve a predetermined task. Statements in a program are generally executed in a sequential manner, which is called sequential execution or sequential control flow. Use of the decision-making statement in the program to control the normal flow of the program. Statements that control the flow of the program are called control statements. Control statements are used in programming languages to cause the flow of control to advance and branch based on changes to the state of a program. Control statements

Decision making

Looping Statement

Jumping statement

If If else Nested if else Switch

do - while while for

Break Continue Return goto

If statement The If statement used to take decisions based on a condition. Such a condition is expressed in the form of a relational expression or a logical expression. The value of a relational or logical expression is always one of the two logical constants, namely true or false Flow of if Entry

Test expression

False

True

II B.Sc., Computer Science Dr.R.K.S.College

Page 22

Java Programming

Department of CS

Syntax if (text-expression) { statement-block-1 } else { statement-block-2 } Description 1. if and else are keywords 2. text-expression is a relational or logical expressions. 3. Statement-block-1 and Statement-block-2 may be a single statement or group statements. Simple Program class state { public static void main(String arg[]) { int a=10,b=20; if(a>b) { System.out.println("A is greater"); } else { System.out.println("B is greater"); }}} Output A is greater

Nested ifelse statement When a series of decisions are involved, then to use more than one if..else statement in nested form as follows

II B.Sc., Computer Science Dr.R.K.S.College

Page 23

Java Programming

Department of CS

if(test condition) { If(test condition2) { statement-1; } else { statement-2; } } else { statement-3; } statement-x; If the condtion-1 is false, the statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x. Example program (greatest among three numbers) class state1 { public static void main(String arg[]) { int a=100,b=120,c=55; if(a>b) { System.out.println("A is greater"); } else if(b>c) { System.out.println("B is greater"); } Else { System.out.println("C is greater"); }}} II B.Sc., Computer Science Dr.R.K.S.College Page 24 Output B is greater

Java Programming The Switch Statement

Department of CS

The main problem of nested if else statement is statement used are hard to read and write. A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. Syntax Switch(expression) { Case value-1: Statement-block-1; Case value-2: Statement-block-2; Case value-n: Statement-block-n; Default: Default-block; } Meaning 1. Switch, case and default are keywords. 2. Expression is any valid expression that yields an integer constant or character constant. 3. Each one of the entries values value-1, value-2,.., value-n is an integer constant or expression such as 6 *3; 4. Each statement block may be single statement or a group of statements. 5. default part is optional. The following rules apply to a switch statement: The variable used in a switch statement can only be a byte, short, int, or char. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The value for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

II B.Sc., Computer Science Dr.R.K.S.College

Page 25

Java Programming

Department of CS

Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. Example program class Test { public static void main(String args[]) { char maths = args[0].charAt(0); int a=10,b=20,c=0; switch(maths) { case 'a' : c=a+b; System.out.println("Addition of two number:"+ c); break; case 's' : c=a-b; System.out.println("Subtraction of two number:"+ c); break; case 'm' : c=a*b; System.out.println ("Multipulation of two numbers:"+ c); break; case 'd' : c=b/a; System.out.println("Div of two number:"+ c); break; default : System.out.println("Invalid input"); } } }

II B.Sc., Computer Science Dr.R.K.S.College

Page 26

Java Programming Output c:\>java Test a Addition of two number:30 c:\>java Test s Subtraction of two number:-10 c:\>java Test d Div of two number:2 c:\>java Test m Multipulation of two number:200 Looping Statement

Department of CS

The process of repeatedly executing a block of statements is known as looping. The statements in the block may be executed any numbers of times, from zero to infinite number is called infinite loop. In looping, a sequence of statements is executed until some conditions for the termination of the loop are satisfied. A program loop consists of two segments, one known as the body of the loop and other known as the control statements. Depending on the position of the control statements in a loop, a control structure may be classified either as the entry controlled loop or as exit controlled loop. A looping process in general would include the following four steps 1. 2. 3. 4. Setting and initialization of a counter Execution of the statements in the loop Test for a specified condition for execution of the loop Incrementing the counter.

The java language provides for three constructs for performing loop operations. They are 1. while loop 2. do while loop 3. for loop While Loop The execution of a while statement results in the repeated execution of a single or compound statement as long as specified condition remains true. The while is an entry controlled loop statement. Syntax while(text-condition) statement-block; II B.Sc., Computer Science Dr.R.K.S.College Page 27

Java Programming Meaning

Department of CS

1. while is a keyword. 2. Test-condition is a logical expression. 3. Statement-block may be single statement or a group of statements. When a while statement is executed, the value of the text-condition following the keyword while will be found. If it is true, the statement-block following the test condition will be executed. This simple cycle of evolution of the test-condition and the execution of the statement-block will continue until the value of the test-condition becomes false Example program public class loop { public static void main(String args[]) { int x= 0; while( x < 10 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); }}} output

value of x : 0 value of x : 1 value of x : 2 value of x : 3 value of x : 4 value of x : 5 value of x : 6 value of x : 7 value of x : 8 value of x : 9

Do- while Loop The while statement makes a test condition before loop is executed. Sometimes the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. Some cases it is necessary to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do while loop. Syntax do { statement-block; } while(test-condition);

II B.Sc., Computer Science Dr.R.K.S.College

Page 28

Java Programming Meaning

Department of CS

1. Statement-block may be a single statement or a group of statements 2. test-condition is a logical expression. 3. Do and while are keywords The statement-block that follows the keyword do will be repeatedly executed as long as the value of the test-condition remains true. Once the values of this test-condition become false, the programs control will pass on to the fist statement that follows this loop. Example program class loop1 { public static void main(String args[]){ int x= 0; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 10 ); }} for statement A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax for(initialization; Boolean_expression; update) { //Statements } Here is the flow of control in a for loop: 1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. If the statement is not required here, put a semicolon.(Example i=0) 2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.(Example:i<=n, i<=10) II B.Sc., Computer Science Dr.R.K.S.College Page 29 Output

value of x : 0 value of x : 1 value of x : 2 value of x : 3 value of x : 4 value of x : 5 value of x : 6 value of x : 7 value of x : 8 value of x : 9

Java Programming

Department of CS

3. After the body of for loop executes the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.(Example : i++, i--) 4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, for loop terminates. Example Program Output value of x : 0 value of x : 1 value of x : 2 value of x : 3 value of x : 4 value of x : 5 value of x : 6 value of x : 7 value of x : 8 value of x : 9

class loop2 { public static void main(String args[]) { for(int x = 0; x < 10; x++){ System.out.print("\nvalue of x : " + x ); }}}

Jumping Statement
The break Keyword: The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax: break; The continue Keyword: The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: continue;

II B.Sc., Computer Science Dr.R.K.S.College

Page 30

Java Programming

Department of CS

ARRAYS
v An array is a group of related data items that share a common name, the complete set of values is referred to an array, and the individual values are called elements. v The elements of an array are also known as subscripted variables. v All the values in array are collectively represented by a single variable name. Such a variable name is known as array name. One-Dimensional Arrays A list of items can be given one variable name using only one subscript and such a variable is called a single subscripted variable or a one-dimensional array. An one dimensional array is same as vector in mathematics and is also known as a linear array or list. One dimensional array can be mentioned by x[1],x[2],x[3]..x[n] Creating an Array Like other variables, array must be declared and created and creation in the computer memory before they are used. Creation of an array involves three steps 1. Declaring the array 2. Creating memory locations 3. Putting values into the memory locations. Declaration of Arrays Arrays in Java may be declared in two forms: Form -1 type arrayname[]; Form-2 type [] arrayname; Examples int number[]; float average[]; int [] counter; float [] a; Creation of Arrays After declaring an array, it is necessary to create memory allocation. Java allows us to arrays using new operator only as shown below: arrayname = new type[size]; II B.Sc., Computer Science Dr.R.K.S.College Page 31

Java Programming int y[] = new y[20]; Example : number = new int[5]; average = new float[10]; int a[] = new int[n]; Description v v v v The name of the array is y. It contains integer constants. It is an one dimensional array It may contain a maximum of 20 values.

Department of CS

Example Program class avg { public static void main(String args[]) { double nums[] = {10, 11, 12, 13, 14}; double result = 0; int i; for(i=0; i<5; i++) result = result + nums[i]; System.out.println("Average is " + result / 5); }}

Output Avg is 12.0

Two Dimensional Arrays v In Mathematics, a two dimensional array is known as a matrix. A matrix B having two rows and three columns is said to be a 2 X3 matrix. They are represented in java as the following array. b[0][0],b[0][1],b[0][2],b[1][0],b[1][1],b[1][2] v Each element in the above array has 2 subscripts. First the first subscript denotes the rows position; the second subscript denotes the columns positions. Array which contains two above subscript are known as two-dimensional arrays. v The declaration of the two dimensional array is also same as one dimensional arrays as follows double b[] [] = new double [2] [3]; v The above declaration defines o The name of the array is b o It is a two dimensional array II B.Sc., Computer Science Dr.R.K.S.College Page 32

Java Programming o It contains double type values o It may contain a maximum of 6 values. Example program import java.io.*; class sum { public static void main(String[] args) throws IOException { InputStreamReader reader = new InputStreamReader(System.in); BufferedReader in= new BufferedReader(reader); int a[][] = new int [3][3]; int b[][] = new int [3][3]; String text; System.out.println("Enter the elements of Matrix A one by one:"); for(int i=0;i<3;i++) for(int j=0;j<3;j++) { text=in.readLine(); a[i][j]=Integer.parseInt(text); } for(int i=0;i<3;i++) for(int j=0;j<3;j++) { b[i][j] = a[j][i]; } System.out.println("Elements of Transpose are listed below:"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) System.out.print(b[i][j] + " "); System.out.println(); }}}

Department of CS

II B.Sc., Computer Science Dr.R.K.S.College

Page 33

Java Programming

Department of CS

Output Enter the elements of Matrix A one by one: 1 2 3 4 5 6 7 8 9 Elements of Transpose are listed below: 147 258 369

II B.Sc., Computer Science Dr.R.K.S.College

Page 34

Java Programming

Department of CS

Important Questions
University Asked Questions 2 Marks 1. What us java Applet? An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). 2. Define Java Virtual Machine A Java Virtual Machine (JVM) is a set of computer software programs and data structures that use a virtual machine model for the execution of other computer programs and scripts. The model used by a JVM accepts a form of computer intermediate language commonly referred to as Java bytecode. 3. Define Byte Code Java bytecode is the form of instructions that the Java virtual machine executes. Each bytecode opcode is one byte in length, although some require parameters, resulting in some multi-byte instructions. Not all of the possible 256 opcodes are used. In fact, Sun Microsystems, the original creators of the Java programming language, the Java virtual machine and other components of the Java Runtime Environment (JRE) 4. Why java is important to internet. Applet is a java program that is developed exclusively for the internet. Java has revolutionized the usage of the internet, as the applets have added animation and interactivity to the web pages. One more special type of java program, namely the servlets enable us to obtain dynamic web content in the best possible manner. 5. Explain Servlets The Servlets enable to obtain dynamic web content in the best possible manner. A Servlet is a Java class which conforms to the Java Servlet API, a protocol by which a Java class may respond to http requests. Thus, a software developer may use a servlet to add dynamic content to a Web server using the Java platform. 6. What is a stand-alone application? A stand-alone application deploys services locally, uses the services, and terminates the services when they are no longer needed. If an application does not

II B.Sc., Computer Science Dr.R.K.S.College

Page 35

Java Programming

Department of CS

need to interact with any other applications, then it can be a stand-alone application with its own exclusive local service deployment. 7. What are the three important concepts involved in OOP? Encapsulation Inheritance that help reuse existing code with little or no modification. Polymorphism a Polymorphism is the characteristic of being able to assign Encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination. Inheritance is a way to form new classes using classes have already been defined. Inheritance is employed to

different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. 8. What is a JIT? The Just in Time (JIT) compiler compiles the bytecode into executable machine code in real time, on a piece-by-piece demand basis. JIT is a technique for improving the runtime performance of a computer program. 9. What are tokens? The smallest individual entities in a java program are known as tokens. Five important types of tokens are listed below are reserved keywords, identifiers, literals, operators, separators. 10. Explain identifiers The names that the programmers assign for the classes, methods, variables, objects, packages and interfaces in a java program are known as identifiers. 11. Explain Literals Literals in Java are a sequence of characters that represent constant values to be stored in variables. Java specifies five major types Integer, Float, Character, Strings and Boolean. 12. Name the different types of constants defined in java Integer Constant - It is always a whole number Real constant - It is always having a fractional part. II B.Sc., Computer Science Dr.R.K.S.College Page 36

Java Programming

Department of CS

13. What is the use of Type Declaration Statement? A type declaration statement specifies the type, length, and attributes of objects and functions. Initial values can be assigned to objects. 14. Name five important Control Statements in Java If, Switch, while, dowhile and for statements 15. What is an Array? In the Java programming language arrays are objects, are dynamically created, and may be assigned to variables of type Object. All methods of class Object may be invoked on an array. An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. 16. Write any two features of java 17. What is the use of println() method. With Example 18. Explain any two data types in Java 19. Define variables and its syntax 5 Marks 1. 2. 3. 4. 5. 6. 7. 8. Explain in detail about passing arrays to methods Describe in detail about break and continue statement How to declaring and creating arrays Explain one dimensional array? Give an example Discuss briefly about the usage of Arrays and variables in java with examples. List out the different kinds of operators used in java and explain. Discuss about any five important features of Java Explain the various control statements available in java

10 Marks 1. Explain the features of Java in detail 2. Explain the basic concept of object oriented programming in detail. 3. Explain in brief about control statement in Java 4. Explain in brief about operators in java

II B.Sc., Computer Science Dr.R.K.S.College

Page 37

Java Programming Other Possible Questions 5 marks 1. 2. 3. 4. Write down History of Java? Explain the Structure of Java Program Explain the method of creating and executing java program Explain use of Strings in java

Department of CS

10 Marks 1. Explain briefly about data types in java 2. Explain Input and output statement in java with scanner class

Summery
@ History in 1991 by James Gosling. o Running by Bitecode, JVM o JIT Compiler o Bytecode o Jdk o Java Applet @ Features OOPs, Platform, Secure & Robust, Portable, Multithread, compiled & Interpreted, High performance, distributed and dynamic. @ OOPS class & Object, Encapsulation, Inheritance, polymorphism, Dynamic binding and message communication. @ Java Program Structure Documentation, package, import, interface, class definition and main method class. @ Creating class name same as file name. @ Executing javac for compiling and java for running @ Data types Variables and constants @ Constants Integer, float, character and string. @ Variables - Integer, float, character, string and Boolean. @ Operators Arithmetic, relational, logical, assignment, increment & Decrement, conditional, Bitwise, special and Dot operator; Mathematical function @ Output Statement print, println and printf statements @ Input Statement - System.in , InputStreamReader, BufferReader, type conversation @ Scanner class System.in, Variable type @ Strings Declaration, Length. Concet, case conversation. II B.Sc., Computer Science Dr.R.K.S.College Page 38

Java Programming @ Control Statement Decision Making, Looping and @ Decision making if, nested if, switch @ Looping while, do..while, for @ Jumping break, continue

Department of CS

@ Arrays one dimensional array, creating ,Declare, Two Dimensional

II B.Sc., Computer Science Dr.R.K.S.College

Page 39

You might also like