D1.1) what makes Java more powerful than C and C++?

The following features makes java more powerful than C and C++ 1) Graphical user interface Java supports graphical user interface. C and C++ doesn’t support graphical user interface. 2) Java is free Java can be downloaded free of cost. 3) Java is platform independent Java programs once compiled into java class file, can be run on many platforms like windows, Unix, while C and C++ programs can only run on windows environments. 4) Java is distributed With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objects across net via URLs. 5) Java is Multithreaded One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrently within the same program A single Java program can have many different threads executing independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU time. 6) Java is Secure Java was designed to allow secure execution of code across network. To make Java secure many of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory. 7) Garbage collection Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is done automatically with garbage collector. 8) Java Applications Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant enterprise-enabled programming language suitable for developing significant

<2>

and critical applications. Today, It is used for many types of applications including Web based applications, Financial applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and many more.

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<3>

D1.2) What is Java. Why do we say Java is a platform independent language?
JAVA JAVA is an object-oriented platform independent programming language developed by Sun. Java is widely used on the Web for both client and server processing. It is modeled after C++ and designed to run in limited memory, Java added programming enhancements such as "garbage collection," which automatically frees unused memory. When a Java program is launched from a Web page, the program is called a Java "applet." When run without the Web browser on a user's machine, it is a Java "application." When running in a Web server, it is a Java "servlet." Why JAVA is platform independent
Java is a platform independent language because when Java Code is compiled a byte code is generated which is independent of the system. This byte code is then fed to the JVM (Java Virtual Machine) which resides in the system. Since every system has its own JVM, it doesn't matter where you compile the source code. The byte code generated by the compiler can be interpreted by any JVM of any machine. Java's byte codes are designed to be read and interpreted in exactly same manner on any computer hardware or operating system that supports Java Runtime Environment.

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<4>

D1.3) Discuss Constants, Variables, Operators. Explain the different types of operators used in Java?
Constant A constant is a storage place that can hold information such as integers, floating-point numbers, true-false values, characters, and lines of text. The information stored in a constant can’t change it will always remain the same. Declaring constants Java does not directly support constants. However, a static final variable is effectively a constant. The static modifier causes the variable to be available without loading an instance of the class where it is defined. The final modifier causes the variable to be unchangeable. Words in Java constants should be separated by underscores. Example: public static final int max_units = 25;

Variable A variable is a storage place that can hold information such as integers, floating-point numbers, true-false values, characters, and lines of text. The information stored in a variable can change, which is where the name "variable" comes from. Declaring a variables Syntax (data type) (variable name); Eg. String greeting = "Saluton mondo!"; int s; char b=’C’;

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<5>

Operator Operators are special symbols that perform specific operations on operands, and then return a result. The table below shows the java operator groups.
Operators

Arithmetic operator

Bitwise operator

Relational operator

Logical Operator

Arithmetic Operator Arithmetic operators are used in mathematical expressions in the same way they are used in algebra. Operator + * / % ++ += -= *-= /= %= -Result Addition Subtraction Multiplication Division Modulus Increment Addition assignment Subtraction assignment Multiplication assignment Division assignment Modulus assignment Decrement

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<6>

Bitwise Operator The table below shows the java Bitwise operators which can be applied to integer, long, int, short, char and byte. These operators act upon the individual bits of their operand. Operator ~ & | ^ >> << Relational Operator The relational operator determine the relationship that one operand has to the other. Specifically they determine equality and ordering Operator == != > < >= <= Logical Operator The Boolean logical operator operates on Boolean operands. All of the binary logical operators combine two Boolean values to form a resultant Boolean. Operator & | ^ ! ?: != == Result Logical AND Logical OR Logical XOR Logical Unary NOT Ternary if – then - else Not Equal to Equal to Result Equal to Not Equal to Greater Than Less Than Greater Than or equal to Less Than equal to Result Bitwise Unary NOT Bitwise And Bitwise OR Bitwise Exclusive OR Shift Right Shift Left

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<7>

Escape Sequences
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences:
Escape Sequences Description Insert a tab in the text at this point. Insert a backspace in the text at this point. Insert a newline in the text at this point. Insert a carriage return in the text at this point. Insert a form feed in the text at this point. Insert a single quote character in the text at this point. Insert a double quote character in the text at this point. Insert a backslash character in the text at this point.

Escape Sequence \t \b \n \r \f \' \" \\

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence She said "Hello!" to me. you would write System.out.println("She said \"Hello!\" to me.");

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<8>

D1.4) Differentiate different Data types supported in Java?
Data type is the kind of data a variable can hold. The data types in the Java programming language are divided into two categories and can be explained using the following hierarchy structure :

• • •

Primitive Data Types Reference Data Types

Primitive Data Types

Primitive data types are predefined data types, which always hold the value of the same data type, and the values of a primitive data type don't share the state with other primitive values. These data types are named by a reserved keyword in Java programming language. There are eight primitive data types supported by Java programming language : Byte The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127 (inclusive). This type of data type is useful to save memory in large arrays. We can also use byte instead of int to increase the limit of the code. The syntax of declaring a byte type variable is shown as: byte b = 5;

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<9>

Short The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. short is used to save memory in large arrays. The syntax of declaring a short type variable is shown as: short s = 2;

Int The int data type is used to store the integer values not the fraction values. It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647 that is more enough to store large number in your program. However for wider range of values use long. The syntax of declaring a int type variable is shown as: int num = 50; Long The long data type is a 64-bit signed two's complement integer. It ranges from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range of values. The syntax of declaring a long type variable is shown as: long 746; ln =

Float The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float (instead of double) to save memory in large arrays. We do not use this data type for the exact values such as currency. For that we have to use java.math.BigDecimal class. The syntax of declaring a float type variable is: float f = 105.65; float f = -5000.12;

Double This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<10>

4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This data type is generally the default choice for decimal values. The syntax of declaring a double type variable is shown as: double d = 6677.60;

Char The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535. They are not integral data type like int, short etc. i.e. the char data type can't hold the numeric values. The syntax of declaring a char type variable is shown as: char caps = 'c'; Boolean The boolean data type represents only two values: true and false and occupy is 1-bit in the memory. These values are keywords in Java and represents the two boolean states: on or off, yes or no. We use boolean data type for specifying conditional statements as if, while, do, for. In Java, true and false are not the same as True and False. They are defined constants of the language. The syntax of declaring a boolean type variable is shown as: boolean result = true;

The ranges of these data types can be described with default values using the following table:
Default Value Size (in bits) (for fields) 0

Data Type

Minimum Range

Maximum Range

byte

Occupy 8 bits in -128 memory Occupy 16 bits in -32768 memory Occupy 32 bits in -2147483648 memory Occupy 64 bits in -9223372036854775808 memory

+127

short

0

+32767

int

0

+2147483647

long

0L

+9223372036854775807

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<11>
Occupy 32-bit IEEE 1.40129846432481707e-45 754 floating point Occupy 64-bit IEEE 4.94065645841246544e754 floating point 324d Occupy unsigned character 16-bit, Unicode

float

0.0f

3.40282346638528860e+38

double

0.0d

1.79769313486231570e+308d

char

'\u0000'

0 to 65,535

boolean

false

Occupy 1- bit in NA memory

NA

When we declare a field it is not always essential that we initialize it too. The compiler sets a default value to the fields which are not initialized which might be zero or null. However this is not recommended. Integer Data Types

An integer number can hold a whole number. Java provides four different primitive integer data types that can be defined as byte, short, int, and long that can store both positive and negative values. The ranges of these data types can be described using the following table:
Data Type byte short int long Size (in bits) Occupy 8 bits in memory Occupy 16 bits in memory Occupy 32 bits in memory Occupy 64 bits in memory Minimum Range -128 -32768 -2147483648 -9223372036854775808 Maximum Range +127 +32767 +2147483647 +9223372036854775807

Examples of floating-point literals are: 0 1 123 -42000

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<12>

Floating-point numbers A floating-point number represents a real number that may have a fractional values i.e. In the floating type of variable, you can assign the numbers in an in a decimal or scientific notation. Floating-point number have only a limited number of digits, where most values can be represented only approximately. The floating-point types are float and double with a singleprecision 32-bit IEEE 754 floating point and double-precision 64-bit IEEE 754 floating point respectively. Examples of floating-point literals are: 10.0003 48.9 -2000.15 7.04e12

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<13>

D1.5) Briefly explain the structure of a Java program and input and output statements used in Java?
Eg.

Structure of Java program
class Example

class name_of _the_class
{

{
Public static void main(String args[])

public static void main(String args[]) { // statements } }
}

{ System.out.println(“hello”); }

class name_of _the_class This line uses the keyword class to declare that a new class is being defined. The class is Java’s basic unit of encapsulation. Example is the name of the class. The class definition begins with the opening curly brace ({) and ends with the closing curly brace (}).The elements between the two braces are members of the class. public static void main(String args[]) This line begins the main( ) method. This is the line at which the program will begin executing. All Java applications begin execution by calling main( ) method. The public keyword is an access specifier. An access specifier determines how other parts of the program can access the members of the class. When a class member is preceded by public, then that member can be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.) In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called before an object of the class has been created. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value.

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<14>

The { } (curly braces) below “public static void main(String args[])” The “{“ curly braces means the place where the programming code starts for the main method. And the “}” curly braces means the end of the main method.

Input Statement Java doesn’t have a predefined input statement like “c” and “c++”. But input can be got using
the Scanner class which is new in version 5.0 of the Java API. If you use version Java 1.4.2, then you don’t have access to the Scanner class. (You get an error when you try tocompile Listing 5-1.) Example

import java.util.Scanner; Scanner input=new Scanner(System.in); System.out.println("Please enter a Number:"); Int no=input.nextInt();

Output Statement System.out.println(“Hello”); System.out.prinln(“ the sum is…”+x); This is similar to the printf() statement in C . since java is a true object oriented language, every method must be a part of an object. The println method is a member of the out object, which is a static data member of system class. This line prints the string to the screen. The method println always appends a newline character to the end of the string. Any subsequent outputs will start on a new line. Every java statement must end with a semicolon

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<15>

D1.6) Explain control statements in Java with syntax?
Conditional statements A java program is a see of statement, which are normally executed sequently in the order in which they appear. Conditional statements are used to repeat a statement based on certain conditions, or repeat a group of statements until certain specified conditions are met.

Conditional statements

Selection Statements

Iteration Statements

Jump Statements

If, if-else, Switch

While, do-while, for

Break, continue, return

If statement The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically 2 way decision statement and is used in conjunction with an expression. It allows the computer to evaluate the expression first and then depending on whether the value of the expression is true or false, it transfers the control to a particular statement. Syntax of IF statement If (condition) { Statements; } The statements inside the if condition will only be executed if the given condition is true. If the given condition is false the statements inside the if condition will not be executed. Eg: a=1;b=1 If(a == b) { System.out.println(a +”=” b); }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<16> IF …Else statement The if..else statement is an extension of the simple if statement. Syntax of If..else If(test expression) { True block statement(s) } Else { False block statement(s) } Statement-x If the test expression is true, then the true block statement(s) executed. Otherwise, the false block statement(s) are executed. In either case either true block or false block is executed. Eg Program to check whether given variable is equal to 1 or not Int a=1; If (a==1) { System.out.println(“a=1”); } Else { System.out.println(“a is not equal to 1”); } The if statement checks whether variable “a” is equal to 1. If a is equal 1 then the System.out.println(“a=1”) is executed. If “a” is not equal to 1 then the else part of the if statement is executed. The if..if Else..else statement: There is another way of putting if’s together when multiple decisions are involved. As soon as the true condition is found the statement associated with it is executed and all the false condition are skipped. If all conditions are false then the default statement will be executed.

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<17> class Alphabet { public static void main(String arg[]) { char a='2'; if ((a>='A') && (a<='Z')) { System.out.println(a+":Is an Alphabet"); } else if ((a>='a') && (a<='z')) { System.out.println (a+":Is an Alphabet"); } else { System.out.println (a+":Is not an Alphabet"); } } } The switch statement Java has a built in multiway decision statement known as a switch. 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 statements associated with that case is executed. The syntax of the switch statement is as shown below: switch(expression) { case value-1: block-1; break; …………. …………. case value-2: block-2; break; …………. …………. default: default-block break; } statement-x The expression is an integer expression or character. Value 1 , value 2 are constants or constant expressions(evaluable to an integral constant) and are known as case labels. Each of these values should be unique within a switch statement. Block1, block 2 are statement list and may contain zero or more statements. There is no need to put braces around these blocks but it is important to note that case labels end with a colon.

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<18> When the switch is executed the value of the expression is successfully compared against the expression values value-1, value-2. If a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed. The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch.The default is an optional case. When present, it will be executed if the value of the expressions does not match with any of the case.

Eg: import java.util.Scanner; class switch { public static void main(String arg[]) { int n; Scanner input=new Scanner(System.in); System.out.print("Enter the Number "); n=input.nextInt(); switch(n) { case 0: System.out.println("ZERO"); break; case 1: System.out.println("ONE"); break; case 2: System.out.println("TWO"); break; default: System.out.print("invalid input"); } } } Iteration statements A computer is well suited to perform repeative operations. It can do any number of times. The process of repeatedly executing a block of statements is known as looping or Iteration. The statements in the block may be executed any number of times, from zero to infinite numbers. In looping, or iteration a sequence of statements are executed until some conditions for the termination of the loop are satisfied. A program loop therefore consist of two segments, one known as the body of the loop and the other known as the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. A looping process in general would include the following four steps:

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<19> 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

While statement The simplest of all the looping structures in java is the while statement. The syntax of the while statement: Initialization; While (test condition ) { Body of the loop } The while is an entry-controlled loop statement. The test condition is evaluated and if the condition is true, then the body of the loop is executed. After the execution of the body , the test condition is again evaluated and if is true, the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop.and the statement immediately after the body of the loop is executed. n=1; while(n<=10) { System.out.prinln(“counter=” +n); } ………….. The body of the loop is executed 10 times for n, each time displayin the value of counter value of n, which is incremented inside the loop. The loop will display numbers from 1-10 and will terminate. Do while The while loop construct test a given condition before the loop is executed. Therefore the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the body of the loop once before the test is performed. Such situations can be handled with the help of the do statement. Intialization; Do { Body of the loop } While (test condition)

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<20>

On reaching the do statement the program proceeds to evaluate the body of the loop first .At the end of the loop, the test condition in the while statement is evaluated. If the condition is true the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false the loop will terminated and the control goes to the statement that appears immediately after the while statement. Since the test condition is evaluated at the bottom of the loop, the do … while construct provides an exit controlled loop and therefore the body of the loop is always executed atleast once. Eg: n=1; do { System.out.println(“counter=”+n); }while(n <= 10 );

For statement The for loop is another entry-controlled loop that provide a more concise loop control structure. One of the important points about the for loop is that all the tree actions, namely initialization, testing and incrementing are placed in the for statement itself, thus making them visible to the programmers and used, in one place.

The syntax of the for loop: For (initialization ; test condition ; increment or decrement ) { Body of the loop } The for loop executes in the following way: 1) Initialization of the control variables is done first, using assignment statement such as I =1 and count = 0. The variables I and count are known as loop control variable. 2) The value of the control variable is tested using the test condition. The test condition is relational expression, such as I < 10 that determines when the loop will exit. If the condition is true, the body of the loop is executed; otherwise the loop is terminated. 3) When the body of the loop is executed the control is transferred back to the for statement after evaluating the last statement in the loop. Now the control variable is incremented using a assignment statement such as i++ or i—

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<21> EG: For ( n=1 ; n<=10 ; n++) { System.out.println(“count=”+n) } The above program prints the numbers from 1 to 10.

Jump Statements (unconditional Statements)

Break In Java, the break statement has two uses. 1) terminates a statement sequence in a switch statement. 2) can be used to exit a loop. Example
public BreakExample { public static void main(String[] args) { for(int i = 0; i < 10; i++) { if(i == 5) { System.out.println("Terminating the loop..."); break; } System.out.println("Still in the loop"); } } }

In the above example the loop will continue until the loop variable “i” is equal to 5. Once i=5 the loop will terminate. Continue
Continue statements are very useful in some situations where we want to check a condition and if the condition is true then only the block of code sould be executed otherwise it should skip the code and force to continue with the loop without processing the remainder of the code.

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<22> Example
public class ContinueExample { public static void main(String[] args) { for(int i = 0; i < 5; i++) { if(i <= 2) { continue; } System.out.println(i + " is greater than 2"); } } }

Out put 3 is greater than 2 4 is greater than 2 Return Keyword Return statement simply returns from a method. That means that the execution control is returned back to the caller of the method. It is ideally the last statement that is executed in a method.
public ReturnExample { public static void main(String args[]) { boolean flag = true; System.out.println("The value of the flag has been set as true."); if(flag) return; System.out.println("This line will never be printed on the screen"); } }

As you can see, the final println( ) statement is not executed. As soon as return is executed, control passes back to the caller. One last point: In the preceding program, the if(flag) statement is necessary. Without it, the Java compiler would flag an "unreachable code" error, because the compiler would know that the last println( ) statement would never be executed. To prevent this error, the if statement is used here to trick the compiler for the sake of this demonstration.

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<23>

D1.7) Using If condition design a java program to check whether the given number is odd or even?

import java.io.*; class d1_7oddoreven { public static void main(String[]args) { int n=3; if(n%2==0) { System.out.println(n + " is an even number"); } else { System.out.println(n + " is an odd number"); } } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<24>

D1.8) Using if and Logical operators accept a character from the user and display whether it is a vowel or not?
import java.util.Scanner; import java.io.*; //Checks for inputted character is a vowel or not class d1_8 { public static void main(String[]args) { char a; Scanner myscanner= new Scanner(System.in); System.out.print("Enter a character : "); a=myscanner.findInLine(".").charAt(0);

if((a=='a')||(a=='e')||(a=='i')||(a=='o')||(a=='u')||(a=='A') ||(a=='E')||(a=='I')||(a=='O')||(a=='U') ) { System.out.println(a + " is a vowel"); } else { System.out.println(a + " is not a vowel"); } } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<25>

D1.9) Using comparison operator in Java accept an entry from the keyboard and find out whether it is an alphabet or Digit or Special Character?
import java.util.Scanner; import java.io.*; //Checks for inputted character is a vowel or not class d1_9 { public static void main(String[]args) { char a; char e; do { Scanner myscanner= new Scanner(System.in); System.out.print("Enter a any character : "); a=myscanner.findInLine(".").charAt(0); if((a>='a')&&(a<='z')||(a>='A')&&(a<='Z')) { System.out.println(a + " is a alphabet"); } else if((a>='0')&&(a<='9')) { System.out.println(a + " is a number"); } else { System.out.println(a + " is a Special Character"); } System.out.println("to exit press e.To continue press any key"); e=myscanner.findInLine(".").charAt(0); }while(e!='e'); } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<26>

D1.10) Using If else condition in Java accept a valid year from the user and check whether it is a leap year or not?
import java.util.Scanner; import java.io.*; class d1_10 { public static void main(String[]args) { Scanner myscanner= new Scanner(System.in); int year; System.out.print("Enter a year in numbers : "); year=myscanner.nextInt(); if(year%4==0) { System.out.println(year+" Is a leap year"); } else { System.out.println(year+ " is not a leap year"); }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<27>

D1.11) Using for loop in java, Design a java program to generate Fibonacci Series import java.io.*; class fibonacci { public static void main(String args[]) { int i, a=0,b=1,c; System.out.print(a +" , " +b); for(i=0;i<=8;i++) { c=a+b; a=b; b=c; System.out.print(" , " +c); } } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<28>

C1.1) Using If and While condition in Java design a Java program to check whether the inputted number is a Palindrome or not
import java.util.Scanner; import java.io.*; class c1_1 { public static void main(String[]args) { Scanner myscanner= new Scanner(System.in); int n,r=0,last,tn; System.out.print("Enter a number : "); n=myscanner.nextInt(); tn=n; while(n>0) { last=n%10; n=n/10; r=(r*10)+last; } if(tn==r) { System.out.println(tn+ " is a palindrome number"); } else { System.out.println(tn+ " is not a palindrome number"); } } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<29>

C1.2) Using constructor describe constructor with example program
class box { double width; double height; double length; box() { System.out.println("Constructor box"); width=10; height=5; length=10; } double volume() { return width*height*length; } } class c1_2 { public static void main(String[]args) { box a = new box(); double vol; vol=a.volume(); System.out.println("Volume = " +vol); } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<30>

B1.1) Using garbage collector describe garbage collector with example program
/** Example shows garbage collector in action Note that the finalize() method of object GC1 runs without being specifically called and that the id's of garbage collected objects are not always sequential. */ class testgc { public static void main(String[] args) { // Returns the runtime object associated with the current Java application. Runtime rt = Runtime.getRuntime(); // Returns the amount of free memory in the Java Virtual Machine. int i=1; //creating an object for gc1 constructor gc1 x = new gc1(i); System.out.println("Free Memory before call to gc(): " + rt.freeMemory()); //Runs the finalization method of any objects pending finalization. System.runFinalization(); // runs the garbage collector System.gc(); System.out.println(" Free Memory after call to gc(): " + rt.freeMemory()); } } class gc1 { String str; int id; gc1(int i) { // "this" keyword is used to call one constructor another to another. This must be the first line of the contructor: this.str = new String("abcdefghijklmnopqrstuvwxyz"); this.id = i; } protected void finalize() { System.out.println("gc1 object " + id + " has been finalized."); } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<31>

Amount of Free memory before the garbage collector is called

Amount of Free memory after the garbage collector is called

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<32>

B1.2) Using inheritance describe inheritance with example program
import java.io.*; class A { String i,j; void showij() { System.out.println(i); System.out.println(j); } }

class B extends A { String k; void showijk() { System.out.println(i); System.out.println(j); System.out.println(k); } } class b1_2 { public static void main(String[]args) { A superob = new A(); B subob = new B(); superob.i="hassan"; superob.j="mohamed"; System.out.println("Contents of A class "); superob.showij(); System.out.println("************************** *************"); subob.i="hassan"; subob.j="mohamed"; subob.k="rasheed"; System.out.println("Contents of B class :"); subob.showijk(); } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<33>

B1.3) Using Multilevel inheritance, describe multi-level inheritance with an example program.
class box { private double width; private double height; private double depth; //construct clone of an object box(box ob)//pass object to constructor { width=ob.width; height=ob.height; depth=ob.depth; } //constructor used when all dimensions are given box(double w,double h, double d) { width=w; height=h; depth=d; } //constructor used when no dimensions are given box() { width=-1; height=-1; depth=-1; } //constructor for cube box(double len) { width=height=depth=len; } // computer and return volume double volume() { return width*height*depth; } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<34>
class boxweight extends box { double weight; // construct clone of an object boxweight(boxweight ob) { // pass object to constructor super(ob); weight = ob.weight; } //constructor when all arguments are specified boxweight(double w, double h, double d, double m) { super(w,h,d);//call superclass constructor weight=m; } // default constructor boxweight() { super(); weight=-1; } // constructor used when cube is created boxweight(double len, double m) { super(len); weight=m; } } // Add shipping cost class shipment extends boxweight { double cost; //construct clone of an object; shipment(shipment ob) { super(ob); cost=ob.cost; }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<35>
// constructor when all parameters are specified. shipment(double w, double h, double d,double m, double c) { super(w,h,d,m); // call all superclass constructor cost=c; } //defaul constructor shipment() { super(); cost=-1; } //Constructor used when cube is created shipment(double len, double m,double c) { super(len,m); cost=c; } } class b1_3 { public static void main(String args[]) { shipment shipment1=new shipment(10,20,15,10,3.41); shipment shipment2 = new shipment(2,3,4,0.76,1.28); double vol; vol=shipment1.volume(); System.out.println("volume of shipment1 ="+vol); System.out.println("Weight of shipment="+shipment1.weight); System.out.println("Shipping cost :$"+shipment1.cost); System.out.println(); vol=shipment2.volume(); System.out.println("Volume of shipment2="+vol); System.out.println("weight of shipment2 ="+shipment2.weight); System.out.println("Shipping cos : $" + shipment2.cost); } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<36>

B1.4) Using overloading concept describe overloading methods in Java with an example program.
import java.io.*; class overload { void mark() { System.out.println("no arguments"); } void mark(int a) { System.out.println("value =" +a); } void mark(int a,int b) { System.out.println("value are :" + a +" , " +b); } } class b1_4 { public static void main(String[] args) { overload d = new overload(); d.mark(); d.mark(8); d.mark(8,2); } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<37>

A1.1) Using overriding concept describe overriding of methods in Java with an example program.
import java.io.*; class A { int i, j; A(int a, int b) { i = a; j = b; } When show( ) is invoked on an object of type B, // display i and j void show() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } the version of show( ) defined within B is used. That is, the version of show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass' version. This allows all instance variables to be displayed.

void show() { System.out.println("k: " + k); } } class demooverriding { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<38>

A1.2) Using super class constructor describe the fact of super keyword to call super class constructor in Java.
import java.io.*; class box { private double width; private double height; private double depth; //construct clone of an object box(box ob) { width=ob.width; height=ob.height; depth=ob.depth; } box(double w, double h, double d) { width=w; height=h; depth=d; } double volume() { return width*height*depth; } } // class boxweight now fully implements all constructors class boxweight extends box { double weight; // construct clone of an object boxweight(boxweight ob) { super(ob); weight=ob.weight; } // initialize width,height, depth using super()

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<39>
boxweight(double w, double h, double d, double m) { super(w,h,d);// call for super class constructor weight=m; } } class a1_2 { public static void main(String arg[]) { boxweight mybox1 = new boxweight(2,3,4,34.5); double vol; vol=mybox1.volume(); System.out.println("volume of mybox1 ="+vol); System.out.println("weight of mybox1 ="+mybox1.weight); } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552

<40>

A1.3) Using Array in Java, design a Java program to read two dimensional arrays and find the sum of the elements of the two arrays.
import java.io.*; import java.util.Scanner; class a1_3 { public static void main(String args[]) { int a[][] = new int[2][2]; int b[][] = new int[2][2]; int c[][] = new int[2][2]; int i,j; Scanner myscanner = new Scanner(System.in); System.out.println("Enter array A elements "); for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { a[i][j]=myscanner.nextInt(); } System.out.print("\n"); } System.out.println("Enter array B elements "); for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { b[i][j]=myscanner.nextInt(); } System.out.print("\n"); } for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { c[i][j]=a[i][j]+b[i][j]; } } System.out.println("Addition of Array A and B "); for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { System.out.print(c[i][j]); System.out.print("\t"); } System.out.print("\n"); } } }

Student Name: Mohamed Hassan

Batch No: 2k8/DSE/23

Student Id: MIDSE 552