Vous êtes sur la page 1sur 14

2.

3 Fundamental programming Structures in Java A Simple Java Program In Java, all program codes must be written inside a class. Classes in Java are declared using the keyword class followed by class name. //Simple Java Program Class FirstProgram//declares a class, which is an object-oriented construct. { public static void main(String args[])//defines a method named main { System.out.println(My first program in Java);/*similar to printf or cout in c& c++ */ } } Comments Java permits both the single-line and multi-line comments. // for single line /* for multiple line comment used this */ Java Program Structure A Java program may contain many classes of which only one class defines a main method. Classes contain data members and methods that operate on the data members of the class. Methods may contain data type declarations and executable statements. To write a Java program, we first define classes and then put them together. A Java program may contain one or more sections as shown in fig 2.2. Documentation Package Statements Import Statements Interface Statements Class Definition Main Method Class { Main Method Definition } Fig 2.2 General Structure of Java Program Suggested Optional Optional Optional Optional Essential

Java Tokens Java token is the smallest element of a program that is meaning to the computer. When we submit a Java Program to Java compiler, the compiler goes through the text and extracts individual tokens. Java language includes five types of tokens. They are:
2. Introduction to Java Programming Language 1

Reserved Keywords Identifiers Literals Operators Separators

Keywords At the time of designing a programming language, some words are reserved to do specific tasks. Such words are known as keywords or reserved words. Java language has reserved 50 words as keywords. abstract byte class do extends for import long Private short Switch Throws Volatile Assert Case Const Double Final Goto Instanceof Native Protected Static Synchronized Transient While Boolean Catch Continue Else Finally If Int New Public Strictfp This Try Break char Default Enum Float Implement Interface Package Return Super Throw void

Identifiers Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, objects, labels, packages and interfaces in a program. Literals Literal is a constant value written into a program instruction. A literal does not change its value during the execution of a program. There are four types of literals. These are: Numeric literals Character literals String literals Boolean literals Operators It is symbol that takes one or more arguments and operates on them to produce a result. Separators Separators are symbols used to indicate where groups of code are divided and arranged. They basically divide the shape and function of our code. Name What it is used Parentheses() Used to enclose parameters in method definition and invocation, also used for defining precedence in expressions, containing expressions for flow control and surrounding cast types.
2. Introduction to Java Programming Language 2

Braces{} Brackets[] Semicolon ; Comma , Period .

Used to contain the values of automatically initialized arrays and to define a block of code for classes, methods and local scopes. Used to declare array types and for dereferencing array values. Used to separate statements Used to separate consecutive identifiers in a variable declaration, also used to chain statements together inside a for statement Used to separate package names from sub-packages and classes; also used to separate a variable or method from a reference variable.

Constant Constants in Java refer to the fixed values that do not change during the execution of a program. Numeric Constant Integer Constant Real Constant Character Constant Character Constant String Constant Variables It is an identifier that denotes storage location used to store a data value. A variable may take different values at different times during the execution of the program. Data Types Data Types specify the size and the type of values that can be stored.
Data Types in Java

Primitive (Intrinsic)

Non-Primitive (Derived)

Numeric

Non-Numeric

Classes

Interfac

Array

Integer

Floating-Point float (4 byte) double (8 bytes)

Character char (2 byte)

Boolean boolean (1 byte)

byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes)

Fig 2.4 Data types in Java


2. Introduction to Java Programming Language 3

Variables Declaration Declaration does three things: It tells the compiler what the variable name is. It specifies what type of data the variable will hold. The place of declaration (in the program) decides the scope of the variable. The general form of declaration of a variable is Type variable1, variable2 variableN; Variables are separated by commas. A decimal statement must end with a semicolon. Some valid declarations are: int count; float x,y; double pi; Operators Operators are used in program to manipulate data and variables. They usually form a part of mathematical or logical expressions. Java operators can be classified into a number of related categories as below: 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Increment and Decrement Operators 6. Conditional Operators 7. Bitwise Operators 8. Special Operators Arithmetic Operators Arithmetic Operators are used to construct mathematical expressions as in algebra. Operator Meaning //Arithmetic Operator Example + Addition and unary plus class ArithmeticOperator Subtraction or unary minus { * Multiplication Public static void main(String args[]) / Division { % Modulo division (Remainder) Int a=20, b=45; System.out.println(a=+a); System.out.println(b=+b); Output: System.out.println(a+b=+(a+b)); a=45 System.out.println(a-b=+(a-b)); b=20 System.out.println(a*b=+(a*b)); a+b=65 System.out.println(a/b=+(a/b)); a-b=25 System.out.println(a%b=+(a%b)); a*b=900 } a/b=2 } a%b=5
2. Introduction to Java Programming Language 4

Relational Operators Relational Operators are used to compare the values of two variables. //Relational Operators Example class RelationalOperators { Public static void main(String args[]) { float a=15.0F, b=20.0F, c=15.0F; System.out.println(a=+a); System.out.println(b=+b); Logical Operators System.out.println(b=+b); Logical Operators are used to System.out.println(a<b is +(a<b)); form compound conditions by System.out.println(a>b is +(a>b)); combining two or more relations. System.out.println(a==c is +(a==b)); System.out.println(a<=c is +(a<=b)); Operator Meaning System.out.println(b!=c is +(b!=c)); && Logical AND System.out.println(b==a+c is +( b==a+c)); || Logical OR } ! Logical NOT } Some examples of the usage of logical expressions are if(age>55 && salary<1000) if(number<0||number>100) Note: Op-1 && Op-2 is true if both op-1 and op-2 are true and false otherwise. Op-1 || Op-2 is false if both op-1 and op-2 are false and true otherwise. Operator < <= > >= != Meaning Is less than Is less than or equal to Is greater than Is greater than or equal to Is not equal to Assignment Operators Assignment Operators are used to assign the value of an expression to a variable. We have seen the usual assignment operator, =. In addition, Java has a set of shorthand assignment operators which are used in the form. v op= exp; Where v is a variable, exp is an expression and op is a Java binary operator. e.g a + =1// is equivalent to a = a + 1; Increment and Decrement Operator The operator ++ adds 1 to the operand while subtracts 1; Both are unary operators and used in the following form: ++m; or m++; //is equivalent to m=m+1; or m+=1; --m; or m--; //is equivalent to m=m-1; or m-=1; Conditional Operators The character pair ?: is a ternary operator available in Java. This operator is used to construct conditional expressions of the form Where exp1,exp2 and exp3 are expressions. exp1? exp2: exp3; e.g lar = (x>y) : x ? y ; // Here lar = 45
2. Introduction to Java Programming Language 5

Bitwise Operators Bitwise Operators are used to manipulate the individual bits within an operand. Operator & | ^ ~ << >> >>> Meaning bitwise AND bitwise OR Bitwise exclusive Ones complement Shift left Shift right Shift right with zero fill

Special Operator Java support some special operators of interest such as instanceof operator and member selection operator (.). instanceof: It 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. Dot Operator (.): It is used to access the instance variables and methods of class objects.

Big Numbers For handing the long number, there are couple of handy classes in the java.math package, called BigInteger and BigDecimal. BigInteger class implement arbitrary precision integer arithmetic BigDecimal does the same for floating point numbers. The java.math.BigInteger has got the following methods: BigInteger add(BigInteger other): return the sum of this big integer object and other. BigInteger subtract(BigInteger other): return the difference of this big interger object and other. BigInteger multiply(BigInteger other): return the product of this big integer object and other. BigInteger divide(BigInteger other): return the quotient of this big integer object and other. BigInteger mod(BigInteger other): return the remainder of this big integer object and other. Int compareTo(BigInterger other): Returns 0 if this big integer equals other, a negative result if this big integer is less than other, and positive results otherwise. //BigInteger Example import java.math.BigInteger; public class bigint { public static void main(String[] args) { BigInteger x = new BigInteger ("123456789"); BigInteger y = new BigInteger ("112334"); BigInteger bigIntResult =x.multiply(y); System.out.println("Result is ==> " + bigIntResult); } }
2. Introduction to Java Programming Language 6

Java Statement A statement is an executable combination of tokens ending with semicolon (;) mark. Statements are usually executed in sequence in the order in which they appear. However, it is possible to control the flow of execution, if necessary, using special statements. Java implements several types of statements as shown in fig 2.3
Control Statement

Selection Statements if

Iteration Statements

Jump Statements

while

break

if-else

do

continue

switch

for

return

Fig 2.3 Classification of Java Statement Simple if Statement The general form statement is ifelse Statement The ifelse statement is the extension of the simple if statement. The general form is if (test expression) { true- block statement(s); } else { false- block statement(s); } statement-x;

of

simple

if

if (test expression) { statement block; } statement-x; e.g if(age>=18) System.out.println(You can cast a vote);

2. Introduction to Java Programming Language

//Program to test the given number is even or not import java.util.Scanner; class oddtest{ Public static void main(String args[]){ Scanner input=new Scanner(System.in); int num; System.out.println(Enter your number: ); num=input.nextInt; if(num%2==0) System.out.println(num+ is even); else System.out.println(num+ is not even); }} switch statement The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statement associated with that case is executed. The general form of switch statement is as shown below: switch (test expression) { case value-1: Block-1 break; case value-2: Block-1 break; . . default: default-block break; } Statement-x; //Program simple Calculator import java.util.Scanner; class oddtest{ public static void main(String args[]){ Scanner input=new Scanner(System.in); int x,y,option; System.out.println(Enter the first value: ); x=input.nextInt; System.out.println(Enter the second value: ); y=input.nextInt; System.out.println(1. Addition\n2. Difference\n3. Multiplication\n4. Division\n); System.out.println(Choose your option: ); option=input.nextInt; switch(option) { case 1: document.out.println(The sum is +(x+y)); break; case 2: document.out.println(The difference is +(x-y)); break; case 3: document.out.println(The Product is +(x*y)); break; case 4: document.out.println(The division is +(x/y)); break; default: document.out.println(Invalid option); } } }
2. Introduction to Java Programming Language 8

The While Statement The simplest of all the looping structures in Java is the while statement. The basic format of the while statement is Initialization: While (test condition) { Body of the loop } Example: sum = 0; n=1; while (n <= 10) { sum = sum + n * n; n= n + 1; }

The do while Statement On some occasions it might be necessary to execute the body of the loop before the test performed. Such situations can be handled with the help of the do statement. Initialization: do { Body of the loop } While (test condition); Example: sum = 0; n=1; do { sum = sum + n * n; n= n + 1; } while (n <= 10);

The for Statement The for loop is entry controlled loop that provides a more concise loop control structure. The general form of the for loop is for (Initialization; test condition; modifier) { Body of the loop } Example: sum = 0; for(n=1; n<=10; n++) { sum = sum + n * n; n= n + 1; } Break Exit from the loop. Continue Jump to the beginning of the loop.

2. Introduction to Java Programming Language

Array An array is a group of contiguous or related data items that share a common name. Creating an Array 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 Form 2 type arrayname[ ]; type [ ] arrayname;

Example: int number[ ]; float average[ ]; int [ ]counter; float[ ] marks;

Creating of Arrays After declaring an array, we need to create it in the memory. Java allows us to create arrays using new operator only, as shown below: arrayname = new type[size]; Example: number = new int[5]; average = new float[10];

Initialization of Arrays The final step is to put values into the array created. This process is known as initialization. This is done using the array subscripts as shown below. Arrayname[subscript] = value; Example number [0] = 35; number [1] = 40; .. number [4] = 60; type arrayname[ ] ={list of values}; Example int number[ ]={36,78,23,67,89}; Array Length In Java, all arrays store the allocated size in a variable named length.

2. Introduction to Java Programming Language

10

//Sorting a list of numbers import java.util.Scanner; class NumberSorting{ public static void main(String args[]){ int number[]={55,45,67,78,79}; int n=number.length; system.out.print(given list: ); //sorting begins for(int i=0;i<n;i++) { for(int j=1;j<n-i;j++) { if(number[j]>number[j+1]) { //interchange value int temp=number[j]; number[j]=number[j+1]; number[j+1]=temp; } } } System.out.print(Sorted list); for(int i=0;i<n;i++) { System.out.print( +number[i]); } } } Strings String represents a sequence of characters. In Java, strings are class objects and implemented using two classes, namely, String and StringBuffer. Strings may be declared and created as follows: String StringName StringName = new String(string); Example: String firstname; firstname = new String(Danny); Or String firstname= new String(Danny); String Arrays We can create and use arrays that contain strings. The Statement String itemArray[ ]= new String[3];

2. Introduction to Java Programming Language

11

String Methods The String class defines a number of methods that allow us to accomplished a variety of string manipulation tasks. Method call s2=s1.toLowercase(); s2=s1.toUppercase(); s2=s1.replace(x,y); s2=s1.trim(); s1.equals(s2) s1.equalsIgnorecase(s2) s1.length(s2) s1.Chartat(n) s1.compareTo(s2) s1.concat(s2) s1.substring(n) s1.substring(n,m) String.Valueof(p) p.toString() s1.indexof(x) s1.indexof(x,n) String.Valuesof(Variable) Tasks performed Converts the string s1 to all lowercase Convert the string s1 to all Uppercase Replace all appearances of x with y Remove white spaces at the beginning and end of the strings s1 Returns true if s1 is equal to s2 Returns true if s1=s2, ignoring the case of characters Gives the length of s1 Gives nth character of s1 Returns negative if s1<s2, positive if s1>s2, and zero if s1 is equal s2 Concatenates s1 and s2 Gives substring starting from nth character Gives substring starting from nth character up to mth Creates a string object of the parameter p Creates a string representation of object p Gives the position of the first occurrence of x in the string s1 Gives the position of x that occurs after nth position in the string s1 Converts the parameter value to string representation

//Special String Operations class strConcat{ Public static void main(String args[]){ String name=Sunita; String str =Her +name +is +name; System.out.println(str); }}

2. Introduction to Java Programming Language

12

//Distinction between equals() method and == operator class Eq{ public static void main(String args[]){ String str1 = Hello!; String str2 = Hell; String str3 = str1; String str4 = new String(str1); //condition 1 if(str1.equals(str2)) System.out.println(1 is true); //condition 2 if(str1.equals(str3)) System.out.println(2 is true); //condition 3 if(str1.equals(str4)) System.out.println(3 is true); //condition 4 if(str1==str2) System.out.println(4 is true); //condition 5 if(str1==str3) System.out.println(5 is true); //condition 6 if(str1==str4) System.out.println(6 is true); } } StringBuffer Class StringBuffer is a peer class of String. While String creates strings of fixed_length, StringBuffer creates strings of flexible length that can be modified in terms of both length and content. Method call s1.setCharAt(n,x) s1.append s1.insert(n,s2) s1.setLength(n) Tasks performed Modifies the nth character to x Appends the string s2 to s1 at the end Replace all appearances of x with y Sets the length of the string s1 ton. If n< s1.length () s1 is truncated. If n>s1.length() zeros are added to s1

//Manipulation of Strings

public class StringMani { public static void main(String args[]){ StringBuffer str = new StringBuffer("Object Language"); System.out.println("Original String: "+str); System.out.println("Length of String: "+str.length()); //Modifying Character str.setCharAt(6, '-'); System.out.println("Modified String: "+str); //Appending String at end str.append(" improves security."); System.out.println("Appended String: "+str); } }

2. Introduction to Java Programming Language

13

Input/Output (I/O) Operations In Java, data can be read from or written to files or standard Input/Output devices like keyboard and VDU. However, I/O operations in Java are very complicated and awkward to use. This is so because, Java performs most of the input-output operations through the GUI (supported by java.awt package) and depends very rarely on text-based programming. Stream A stream is a file or a physical device, such as printer, disk, monitor etc. Pre-defined Streams Java defines the following three predefined stream objects: System.in (Standard input stream object) System.out (Standard output stream object) System.err (Standard error stream object) Using Scanner for Input from Console The Scanner splits input into substrings, or tokens, separated by delimiters, which by default consist of any white space. The tokens can then be obtained as strings or as primitive types if that is what they represent. For example, the following code snippet shows how to read an integer from the keyboard Scanner scanner = new Scanner (System.in); int i = scanner.nextInt ();
/** Demonstrate the Scanner class for input of numbers.**/ import java.io.*; import java.util.*; public class ScanConsoleApp { public static void main (String arg[]) { // Create a scanner to read from keyboard Scanner scanner = new Scanner (System.in); System.out.printf ("Input int (e.g. %4d): ",3501); int int_val = scanner.nextInt (); System.out.println (" You entered " + int_val +"\n"); System.out.printf ("Input float (e.g. %5.2f): ", 2.43); float float_val = scanner.nextFloat (); System.out.println (" You entered " + float_val +"\n"); System.out.printf ("Input double (e.g. %6.3e): ",4.943e15); double double_val = scanner.nextDouble (); System.out.println (" You entered " + double_val +"\n"); } // main } // class ScanConsoleApp

2. Introduction to Java Programming Language

14