java basics ana java qns

124

Upload: venu-mani-kumar

Post on 27-Nov-2015

49 views

Category:

Documents


12 download

DESCRIPTION

Java Basics ANA JAVA QNS

TRANSCRIPT

TITLE : Basic Java OBJECTIVES :

On completion of the course the participant will be able to:1. Write and run Java programs in the Java Virtual Machine.2. Use strings and arrays in Java.3. Apply good object-oriented programming techniques.4. Use access control to hide implementation details.5. Create a reusable class library using packages.6. Handle errors using exceptions.7. Use Thread class and Runnable interface for creating Multi-

threaded applications.8. Use API docs J2SE 1.4.x.9. Use Java Collections.11.Understand the Java security model.12.Document your programs using javadoc tool.13.Use AWT for creating GUI application programs and

applets

Course Objectives

PREREQUISITES : Programming experience in at least one procedural language. Preferably C, C++.

TARGET AUDIENCE : ELTP Trainees

METHODOLOGY : Usage of slides

Exercises to be solved in Lab Assignments and Quizzes

COURSE CONTENTS

Unit 1 : Object-oriented programming conceptsObject Oriented ParadigmClasses, Objects, variables & methodsAbstraction, encapsulation, inheritance, polymorphismInterfaces

Unit 2 : Fundamental concepts of Java programming languageHistory & characteristics of java.Primitive data types and objectsVariables (Instance and Class)Arrays and StringsControl StructuresMethods (Instance and Class)Packages & InterfacesA small sample application program

COURSE CONTENTS

Unit 3 : Exception handlingConcept of Exception HandlingException TypesUncaught ExceptionsClaiming, Throwing and Handling Exceptions (using try-catch blocks)Using the finally clause in the try-catch blockCreating User Exception

Unit 4 : MultithreadingConcept of MultithreadingWriting threads by extending the Thread Class Writing threads by implementing the Runnable interfaceLife cycle of thread statesThread priorities and thread groupsThread synchronization and resource conflicts

COURSE CONTENTS

Unit 5 : CollectionsMapsSetsTreesVectorsListsIterators & EnumerationsHash Tables, Hash Maps.

Unit 6 : IOs StreamsInputStreamsOutputStreamObject StreamsFile StreamsPipe StreamsBuffered StreamsFile Locking (nio package)

COURSE CONTENTS

Unit 7 : Util PackageString TokenizeDateCalendarIntroduction to java.util.jar & java.util.zip packages.

Unit 8 : Other Important ConceptsCompiler Options.javadoc tool.Security Over view.

COURSE CONTENTS

Unit 9 : IDEIntroduction to IDE.Using Templates.Creating Classes, Interfaces, Packages from IDE.Compiling & running a java program from the IDE.Debugging Techniques.Debugging Java Programs from IDE.

Unit 10 : AWT & AppletAWT Component, Container, Panel, Window, Frame, CanvasAWT ControlsMenusEventsListenersAdapter classes

COURSE CONTENTS

Day Wise

Day Session Topic

1 S1

S2

S3

S4

Object-oriented programming concepts

Fundamental concepts of Java programming language

Writing application programs using Java

Lab Session – Executing a simple Java Program

2 S1

S2

S3

S4

Exception handling

Lab Session – Exercises on Exception handling

Multithreading

Lab Session – Exercises on Multithreading

COURSE CONTENTS

Day Wise

Day Session Topic

3 S1

S2

S3

S4

Java Collections

Lab Session – Exercises on Java Collection

Java IOs

Lab Session – Exercises on Java IOs

4 S1

S2

S3

S4

Security Overview

Javadoc utility, Introduction IDE & debugging techniques

Lab Session – Exercises on Code Debugging

Lab Session – Exercises on Code Debugging

COURSE CONTENTS

Day Wise

Day Session Topic

5 S1

S2

S3

S4

S5

Introduction to AWT & Component Hierarchy)

Frames

Lab Session – Exercises on Frames

Events & Listeners

Lab Session – Exercises on java.awt.event Package

6 S1

S2

S3

S4

Menus

Lab Session – Exercises on Menus

Applets & Applet communications

Lab Session – Exercises on Applets

Day 1 OBJECTIVES :

On completion of this session the participant will be able to:

-Answer what is Java Programming Language.-get an overview of J2EE.-Understand the primary Goals of the Java Programming Language.-Explain the JVM Architecture. -Implement OOAD Methodology.-Understand the usage of String & String Buffer.-Implement java code security.

Session Objectives

Java 2 Platform

J2EE

anyhttp

server

BrowserBrowser

ContainersContainers

EJB ServerEJB Server

DataData

JDBCJDBC

EntityEntityBeanBean

HOMEHOME

REMOTEREMOTE

DeviceDevice

HTTPHTTP

JVMJVM

JDBCJDBC

HTML, XMLHTML, XML

any OS

ServletServletoror

JSPJSP RMI/IIOPRMI/IIOP

Session Session BeanBean

ContextContext

SecuritySecurity

TransactionsTransactions

ConcurrencyConcurrency

The Platform

Application ServerApplication Server

To

ols

To

ols

Man

agem

ent

Man

agem

ent

IntegrationIntegration

Content MgmtContent Mgmt

Wireless/MobileWireless/Mobile

DataData

CommerceCommerce

Cache / Proxy / FwallCache / Proxy / Fwall

CollaborationCollaboration

Where does J2EE Fit?

Application ServerApplication Server

To

ols

To

ols

Man

agem

ent

Man

agem

ent

IntegrationIntegration

Content MgmtContent Mgmt

Wireless/MobileWireless/Mobile

DataData

CommerceCommerce

Cache / Proxy / FwallCache / Proxy / Fwall

CollaborationCollaboration

J2EEJ2EE

J2EEJ2EE

J2EEJ2EE

Fundamental Concepts of Java Programming Language

What Is the Java Programming Language

• Java is• A Programming language

• A development environment

• A deployment environment

• Similar in syntax to C++; similar in semantics to Smalltalk

• Used for developing both applets and applications

Primary Goals of the Java Programming Language

• Provide an interpreted environment for

• Improved Speed of development

• Code portability

• Enable users to run more than one thread of activity

• Support dynamically changing programs during runtime

• Furnish better security

Primary Goals of the Java Programming Language

The following features fulfill these goals

• The Java virtual machine (JVM)

• Garbage collection

• Code security

The Java Virtual Machine

• Provides hardware platform specifications

• Reads compiled byte codes which are platform independent

• Is implemented as software

• Is implemented in a Java technology development tool or a Web browser

The Java Virtual Machine

• JVM provides definitions for the

• Instruction set (central processing until [CPU])

• Class file format

• Stack

• Garbage-collection

• Memory area

The Java Virtual Machine

• Bytecodes that maintain proper type discipline form the code

• The majority of type checking is done when the code is compiled

• Every SunTM approved implementation of the JVM must be able to run any compliant class file.

Garbage Collection• Allocated memory that is no longer needed should be

deallocated• In other languages, deallocation is the programmer’s

responsibility

Garbage collection• Checks for and frees memory no longer needed• Is done automatically• Can vary dramatically across JVM implementations

Java Runtime Environment

• Performs three main tasks• Loads code• Verifies code• Executes code

Java Runtime Environment

compile

.java

.class

NETWORK

Runtime

Class loader

J ITcode

generator

Hardware

Runtime

Interpreter

Byte codeverifier

• Loading code

• Verifying code

• Executing code

Object Oriented Programming Concepts

Class and Object

Understand what an object mean and what it contain

An Object

Everything is an object: If you want to model it and use it in your program.

Account 1

Green TapeRecorder

Account 2

Account 3

Account 4

Red TapeRecorder

Identity

ME My Twin

OneApple

OneApple

Reference and Object

My BPLRed TapeRecorder

BPL Tape Recorder

Red Tape Recorder

Parts of an Object

• Properties

• State

• Methods

• Constructors

• Access Rights

• Destructor

Properties and State

Account 1 Account 1 Account 1

Open Black Listed Closed

•Account no

•Name

•Balance

Methods and Access

Deposit

Withdraw

Interest

Constructor

ConstructorButtons, Motor

All other parts

Tape Recorder

A Destructor is invoked just before the object is deleted, as a last chance

Equality and SimilarityA

B

C

D

•A and B are equal. •B and C are similar•C and D are neither similar nor equal.•If they are equal they are the same object

Inheritance and Aggregation

Understand “is a” and “has a” relations

Inheritance - “is a”

Account

Savings Account Current Account

Savings Account will have everything from account, as does the Current Account

IS A

Aggregation - “has a”

Engine

Car

HAS A

Polymorphism

• Is a consequence of virtual functions

• Function to be called is decided at run time based on object

• This makes a function call behave differently with different objects

Abstract Class

Four LeggedAnimal

Cat Rat

Interface

Radio

Tape

Radio

Tape

Radio

Tape

Volume is common2-in-1

Java Language Specifications

Comments

• Three permissible styles of comment in a Java technology program are

// comment on one line

/* comment on one

or more lines */

/** documenting comment */

Semicolons, Blocks, and Whitespace

• A statement is a single-line of code terminated by a semicolon(;)

totals = a + b + c + d + e + f;

• A block is a collection of statements bounded by opening and closing braces

{x = y + 1;y = x + 1;

}

Semicolons, Blocks and Whitespace

• A block can be used in a class definition

public class Date {

int day;

int month;

int year;

}

• Block statements can be nested• Any amount of whitespace is allowed in a Java

program

Semicolons, Blocks and Whitespace

• A block can be used in a class definition

public class Date {

int day;

int month;

int year;

}

• Block statements can be nested• Any amount of whitespace is allowed in a Java

program

Identifiers• Are names given to a variable, class or method• Can start with a letter, underscore(_), or dollar sign($)• Are case sensitive and have no maximum length

Examplesidentifierusernameuser_name_sys_varl$change

Primitive Types

• The Java programming language defines eight primitive types• Logical boolean• Textual char• Integer byte, short, int and long

• Floating double and float

Logical - boolean

• The boolean data type has two literals, true and false

• For example the statement

boolean truth = true ;

declares the variable truth as boolean type and assigns it a value of true.

Textual - char and String

char• Represents a 16-bit Unicode character• Must have its literal enclosed in single quotes(‘ ‘)• Uses the following notations:

‘a‘

‘\t‘ A tab‘\u????’ A specific Unicode character (????)

is replaced with exactly four hexadecimal digits.

Textual - char and String

String• Is not a primitive data type; it is a class• Has its literal enclosed in double quotes (“ “)

“The quick brown fox jumped over the lazy dog.”

• Can be used as follows:String greeting = “Good Morning !! \n” ;

String err_msg = “Record Not Found !” ;

Integral - byte,short,int, and long

• Uses three forms - decimal, octal or hexadecimal

2 The decimal value is two.

077 The leading zero indicates an octal value

0xBAAC The leading 0x indicates a hexadecimal value

• Has a default int• Defines long, by using the letter “L” or “l”

Integral - byte,short,int, and long

• Each of the integral data types have the following range

-----------------------------------------------------------Integer Name or RangeLength Type-----------------------------------------------------------8 bits byte -27 …

27 –1

16 bits short -215 …

215 –1

32 bits int -231 …

231 –1

64 bits long -263 …

263 –1-----------------------------------------------------------

Floating Point - float and double

• Default is double• Floating point literal includes either a decimal

point or one of the following– E or e (add exponential value)– F or f (float)– D or d (double)

3.14 A simple floating-point value (a double)

6.02E23 A large floating-point value

2.718F A simple float size value

123.4E+306D A large double value with redundant D

Floating Point - float and double

• Floating point data types have the following ranges:-------------------------------------------Float length Name or Type-------------------------------------------32 bits float

64 bits double

-------------------------------------------

Java Coding Conventions

• Classes

class AccountBook

class ComplexVariable

• Interfaces

interface Account

• Methods

balanceAccount ()

addComplex ()

Java Coding Conventions

• Variables

currentCustomer

• ConstantsHEAD_COUNTMAXIMUM_SIZE

Understanding Objects• Reviewing the history of objects• Creating a new type, such as Date

public class Date { int day; int month; int year; }

• Declaring a variable Date myBirth, yourBirth

• Accessing membersmyBirth.day = 26;myBirth.month = 11;yourBirth.year = 1960;

Creating an Object

• Declaration of primitive types allocates memory space

• Declaration of nonprimitive types does not allocate memory space

• Declared variables are not the data itself, but references (or pointers) to the data

Creating an Object - Memory Allocation and Layout

• A declaration allocates storage only for a reference

MyDate today;

today = new MyDate() ;

today ????

Assignment of Reference Variables

• Consider the following code fragment:

int x = 7;

int y = x;

String s = “Hello”;

String t = s;

Hello

S

T

Writing applications programs using Java

Variables and Scope

Local variables are• Variables which are defined inside a method and

are called local, automatic, temporary, or stack variables.

• Created when the method is executed and destroyed when the method is exited.

• Variables that must be initialized before they are used or compile-time errors will occur.

Logical Expressions

• The Boolean operators supported are! - NOT & - AND

^ - XOR | - OR

• The Bitwise operators are~ - Complement & - AND

^ - XOR | - OR

Short-Circuit Logical Operators

• The operators are && (AND) and ||(OR)• Operators can be used as follows:

String unset = null;

if ((unset != null) && (unset.length() > 5)) {

// do something with unset

}

String Concatenation With +

• The + operator• Performs String concatenation• Produces a new String

• For example:String salutation = “Dr.”;

String name = “Pete “ + “Seymour”;String title = salutation + name;

• One argument must be a String object• Non-strings are converted to String objects

automatically

Right-Shift Operators >> and >>>

• Arithmetic or signed right shift (>>) is used as follows:

128 >> 1 equates to 128/21 = 64

256 >> 4 equates to 256/24 = 16

-256 >> 4 equates to -256/24 = -16

• The sign bit is copied during the shift.• Logical or unsigned right shift operator (>>>) is

• Used for bit patterns• Not copied during the shift

Left-Shift Operator (<<)

128 << 1 equates to 128*21 = 256

16 << 2 equates to 16*22 = 64

The = = Operator Versus equals () Method

• The equals () and = = methods determine if reference values refer to the same object.

• The equals () method is overridden in classes in order to return true if the contents and type of two separate objects match.

Casting• If information is lost in an assignment the

programmer must confirm the assignment with a typecast.

• The assignment between short and char requires an explicit cast.

long bigValue = 99L;

int squashed = (int) (bigValue);

long bigval = 6;// 6 is an int type, OK

int smallval = 99L;// 99L is a long, illegal

float z = 12.414F;// 12.414F is Float, OK

float zl = 12.414;// 12.414 is double, illegal

Promotion and Casting of Expressions

• Variables are automatically promoted to a longer form (such as int to long)

• Expression is assignment compatible if the variable type is at least as large (the same number of bits) as the expression type.

Branching Statements

The if, else statementsif (boolean expression) {

statement or block;}

if (condition is true) { statement or block;} else {

statement or block;}

Branching Statements

The switch StatementThe switch statement syntax is:

switch (expr1) {

case expr2:

statements;

break;

case expr3:

statements;

break;

default:

statements;

break;

}

Looping Statements

The for statement

for (init_expr; boolean testexpr; alter_expr) {

statement or block;

}

Looping Statements

The While loop

while (boolean) {

statement or block;

}

Looping Statements

The do/while statement

do {

statement or block;

}

while (boolean test)

Special Loop Flow Control

• break [label] ;• continue [label];• label: statement;//where statement must be any

// legal statement

Declaring Arrays

• Group data objects of the same type• Declare arrays of primitive or class types

char s[];

Point p[];

char [] s;

Point [] p;

• Create space for a reference• Remember an array is an object not memory

reserved for primitive types

Creating Arrays

Use the new keyword to create an array object

s = new char [20];p = new point [100];

p[0] = new point();p[1] = new point();... Example : ArrayDemo.java

Initializing Arrays

• An array element is initialized

• Create an array with initial valuesString names [] = {

“Georgianna”,

“Jen”,

“Simon”

};

Example : ArrayOfStringDemo.java

Multi-Dimensional Arrays

• Arrays of arrays

int twoDim [][] = new int [4][] ;

twoDim [0] = new int[5];

twoDim [1] = new int[5];

int twoDim [][] = new int [][4]; illegal

• Array of four arrays of five integers each

int twoDim [][] = new int[4][5];

Example : ArrayOfArraysDemo .java

Multi-Dimensional Arrays

• Non-rectangular arrays of arraystwoDim[0] = new int[2];

twoDim[1] = new int[4];

twoDim[2] = new int[6];

twoDim[3] = new int[8];

• Array of four arrays of five integers eachint twoDim[][] = new int[4][5];

Example : ArrayOfArraysDemo2 .java

Array Bounds

All array subscripts begin at 0

int list [] = new int [10];

for (int i = 0; i < list.length; i++)

system.out.println(list[i]);

Copying Arrays

• Cannot resize an array• Can use the same reference variable to refer

to an entirely new array

int elements [] = new int[6];

elements = new int[10];

Copying Arrays

The System.arraycopy () method

//original array

int elements[] = { 1,2,3,4,5,6 };

:

//new larger array

int hold[] = { 10,9,8,7,6,5,4,3,2,1 };

//copy all of the elements array to the hold

//array, starting with the 0th index

System.arraycopy (elements, 0, hold, 0,

elements.length);

Example : ArrayCopyDemo .java

StringsStrings are objects that are immutable

Using Strings :

String name=“Rajesh”;

String name = new String(“Rajesh);

String fullname = name + “Kumar”;

name = name + “Kumar”;

Important methods of string class :

charAt(), substring(), length(), toUpperCase(),

toLowerCase(), trim(), valueOf()

ConstructorsMethod used to initialize an objectMethod name same as the class nameJava provides the default constructor for a classWe can have overloaded constructors

class Employee {int no;String name;Employee() {

no=100;name=“Rajesh”;

}}

Class (static) Variables• Is shared among all instances of a class• Can be marked either as public or as private• Can be accessed from outside the class if marked as public

without an instance of the class.public class Count { private int serialNumber; private static int counter = 0; public Count () { counter++; serialNumber = counter; }}

Class (static) MethodsA static method can be invoked without any instance of the class to which it belongs

public class GeneralFunction { public static int addUp (int x, int y) { return x + y; }}public class UseGeneral { public void method () { int a = 9 int b = 10 int c = GeneralFunction.addUp(a, b); System.out.println(“addUp() gives “ + c); }}

Inheritance - ‘extends’ keyword

- The “is a” relationship is achieved through inheritance

- ‘extends’ keyword is used to inherit a classclass Employee{}class Manager extends Employee {}

- Constructors are not inherited - A subclass method can override the method of a super class.- Only multi-level inheritance is possible, multiple inheritance is achieved using interfaces.

Inheritance - Method Overloading and Overriding

class Employee {

void showDetails() { }

}

class Manager extends Employee {

void showDetails() { }

void showDetails(int no) { }

}

The final keyword

• A final class cannot be subclassed• A final method cannot be overridden• A final variable is a constant

Abstract Classes• A class which declares the existence of methods but not

the implementation is called an abstract class.• A class can be declared as abstract by marking it with

the abstract keyword.public abstract class Drawing { public abstract void drawDot {int x, int y); public void drawLine (int x1, int y1,

int x2, int y2) { // draw using the drawDot () method repeatedly. }}

• An abstract class can contain non-abstract methods and variables

Interfaces• An interface is a variation on the idea of an

abstract class.• In an interface, all the methods are abstract.• Multiple inheritance can be achieved by

implementing such interfaces• The syntax is

public interface Transparency {

public static final int OPAQUE = 1;

public static final int BITMASK = 2;

public static final int TRANSLUCENT = 3;

public int getTransparency();

}

Interfaces• Interfaces are useful for

• Declaring methods that one or more classes are expected to implement

• Determining an object’s programming interface without revealing the actual body of the class

• Capturing similarities between unrelated classes without forcing a class relationship

• Describing “function-like” objects that can be passed as parameters to methods invoked on other objects

Advanced Access Control

---------------------------------------------------------------------------------------------------

Modifier Same Class Same Package SubclassUniverse

---------------------------------------------------------------------------------------------------

public yes yes yes yes

protected yes yes yes

default (package) yes yes

private yes

---------------------------------------------------------------------------------------------------

StringString

• String( char[])

• String(char[], int Start, int No)

• String(byte[])

• String(byte[], int Start, int No)

• String(String)

Constructors :-

• Length( ) - Returns the number of characters

• charAt(int) - Returns char at the given index

• getChars(int St, int End, char[] Dest, int StDes)• toCharArray( ) - Returns character array

• getBytes(int St, int End, byte[] Dest, int StDes)• equals(String) - Compares two Strings,returns

boolean.

• equalsIgnoreCase( ) - For ignoring the case

Methods :-

Cont...Example : ControllingCase.java

• compareTo( ) - Returns integer

• startsWith(String) - Returns boolean,case sensitive

• endsWith(String)- Returns boolean,case sensitive

• trim( ) - Removes blank spaces on either sides

• replace(char Old, char New) - For replacing Old chars

• concat(String) - Creates a new String by adding

• subString(int) - Creates a String from int to the end

Methods :-

Cont...

• subString(int,int) - Creates a String from int to int(end)

• indexOf(Char) - Returns int,index of first occurence

• lastIndexOf(char) - Returns int,index of last occurence

• indexOf(String) - Returns int,index of first occurence

• lastIndexOf(String)- Returns int,index of last occurence

Methods :-

StringbufferStringbuffer

• Stringbuffer( ) - 16 bytes of buffer by default • String buffer(int) - For specifying the size• String buffer(String) - For specifying the size

Constructors :-

• Length( ) - Returns the number of characters

• capacity( ) - Returns capacity

• setLength (int len) - Sets the new length• charAt(int) - Returns character at the index

• getChars(int St, int End, char[] Dest, int StDes)

Methods :-

Cont...

• setCharAt(int, char) - Sets the char at the int• append(String)-Adds the string to the current string• insert(int, String) - Inserts the string at the index• toString( ) - Returns string• reverse( ) - Reverses the string

Methods :-

Cont...

Example : StringBufferVsStringDemo.java

Points to Note

• Use StringBuffer wear the string values constantly change. Because a new string object is created for every change of value for a String class.

A Sample Java Applicationpublic class First {

public static void main(String[] args) {int no=4;

System.out.println("Welcome to Java Programming");System.out.println("Number :"+no);

}}

Compiling and Executing :- javac First.java -- generates First.class file.- java First

Lab SessionQ. which of the following variable names are invalid, and why?

Minimum First.name n1+ n2 &name double 3rd_row n$ Row1 float Sum Total Row Total Column-total

Q. Shown below is a Floyd’s triangle.12 34 5 6…………………………………..79 ……………………91

Write a program to print this triangle? (FloydTriangle.java)

Solution

• class FloydTriangle {• public static void main(String []args) {• int j;• for(int i=1;i<6;i++) {• for(j=1;j<=i;j++)• System.out.print(j+"\t");• System.out.print("\n\n");• }• }• }

Lab Session

Write the segment of the program that creates the array as follows.

1 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1

Solution

Example : FloydTriangle.java

Lab SessionThe annual examination results of 5 students are tabulated as follows.write the main method in order to determine the followinga) Find out the total marks obtained by each student.b) The highest marks in each subject and roll no of the

student who secured it.

Use the following class to create the objects

class Student{int rollNo;String name;int sub1, sub2,sub3;}

Consider a college running 4 departments (MPC, BPC, HEC, CEC) the subject of each of the departments is given below.MPC

Lang 1Lang 2MathematicsPhysicsChemistry

BPCLang 1Lang 2BiologyPhysicsChemistry

CECLang 1Lang 2CommerceEconomicsCivics

HECLang 1Lang 2HistoryEconomicsCivics

Requirement : Capture the marks of a student of any given department.

Lab Session

Marks

Science MarksArts Marks

HEC Marks CEC Marks MPC Marks BPC Marks

MarksArts MarksScience Marks

Abstract Classes

Solution

HEC MarksCEC MarksMPC MarksBPC Marks

Final Classes

For More Examples See Examples/Basics

Language Basics Code Samples http://developer.java.sun.com/developer/

codesamples/basics.html

Java Coding Convensionshttp://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

Exercise: Programming through a story.

• Objective: This is a story based exercise. The exercise enables the participants to pause at different stages and review the work they had done and the changes that need to be carried out to meet new requirements, that crop up from time to time. The Objective is to develop an object oriented system, using Java. The participant is expected to visualize various approaches to solve a problem, evaluate the approaches and develop a solution using the best option. The participant is required to refer to the Java language specifications to study the facilities offered by the Java API.

Exercise (contd..)

• Note: The participant is required to look into the best practices of Java (PPT version), while doing the exercise.

Exercise (contd..)

• 1. A student joins the Satyam University. He sits at the workspace allotted to him. He runs the Hello.java program by keying in “java Hello” and he sees the welcome message

• 2. However, he wishes to be welcomed by name. He modifies the program.

• 3. experiments by overloading the main method.

Exercise (contd..)

• 4. In the next program [4], the student enters the marks he has scored in 5 subjects and the program outputs the average marks. Grading on a scale of A to D is done with the following range of values for the grade.

Exercise 4 (contd…)

Grade Average marks

A > 80 %

B >= 70 and < 80%

C >= 60 and < 70%

D < 60%

Exercise (contd..)

• 5. Before grading the students, the program checks whether the student is above a minimum age which is stipulated in another class.

• 6. The other class has facilities to set and get the minimum age. The other class should reside in a package called “stipulations”

Exercise (contd..)• 7. The SU has 4 departments. A student’s marks

sheet is based on the department to which the student belongs. The 4 departments along with the subjects offered by them are:

• Department Subjects offered MPC Maths, Physics, Chemistry, lang1, lang2BPC Biology, Physics, Chemistry, lang1, lang2

HEC History, Economics, Civics, lang1, lang2 CEC Commerce, Economics, Civics, lang1, lang2

A student belongs to one of the 4 types of students viz. MPCStudent/BPCStudent/HECStudent/CECStudent. Hence, a student object belonging to a particular class should have its class implement the corresponding MarksInterface

Exercise (contd..)

• 8. SU gets the input data for students in the below format:

• “#StudentNumber;StudentFirstName; StudentFirstName subjectName=Marks;…..”

• For the current exercise, the input data is treated as held in the form of a String object, rather than getting it from a file.

• The data has to be extracted from the String object, the student objects have to be created and stored in an array of Student objects. Initially, the extracted data is to be printed onto the console

Exercise (contd..)

9. And then stored into the array of Student objects

10.The next requirement is that the first and last names should be concatenated and displayed. One of the developers suggests that a StringBuffer class could be used. Weigh the pros and cons of using the StringBuffer and write a new class for carrying out the concatenation.

• The remainder part of the story exercises will be continued in the next session.

ThankQ…