You are on page 1of 75
JAVA PROGRAMMING MANUAL Prepared by ‘Mr. NAVEEN SAGAYASELVARAJ beta a CSC Computer Education Krishnagiri Ms. MANGAIYARKKARASI V Lecturer CSC Computer Education Gopichettipalayam CONTENT PAGE NO. INTRODUCTION PROGRAMMING CONSTRUCTS & CASTING AND TYPE CONVERSION ARRAYS STRING CLASS COSTRUCTOR: INHERITANCE AND INTERFACE 1/0 STREAM CLASSES: APPLETS AND SWINGS EVENT-HANDLING MULTITHREADING NETWORKING-1 NETWORKING-II OBJECTIVE: Basie Programming using class and objects, OVERVIEW: ‘Classes and Objects: The flandamenial programming wnit of the Jaya programming language isthe class. Classes provide ‘the structure for objects and the mechanisms to manufacture objects from a class definition. Classes define methods: collections of executable cade that are the focus of computation and that manipulate the data stored in objects. Methads provide the behavior af the objects ofa class. ‘Syntax: For Class definition: ‘class class_name ( Datatype variable_name; /Oata Memebers Retiewmype tod. wanye( pana ORs os i eMeiber.Funetion t } Pubic static void main(String arg{ |) ‘sin Method block ‘objectame.methednamet mewser fonction ofthe cess 7 * @author NaveenSagayaclyatkaj 4 ‘public class Pirst_Program t priv fit First nun = 5; piven second_nurh = 6; public void nd t int answers “answer = firs_numésecond_ num; ‘System.out.printg" Answer: "+answer): i public static void main(String andl) t First_Program objenew First Program(): ‘obiachi): cM [BUILD SUCCESSFUL (iota time: 1 second) Define a class sample with the following specification Pubic member funstion of class sample Display) Function to Display “Hello!! Worl” Deine a class student with the following specification Private members of class student Roll_no int Phy;che® mathsdouble Total double Average int ‘Cal_To1ai a function o caleulate Total with double rent type ‘Cal_AsgQ a funetion to caleulate Average with int retum type Public member function of class student ‘Takedata() _Funetion ta aévept values far Roll_66, Phy.che, maths, invoke Cal_total() to caleulate total and invoke Cal Avg() to calculate average. ‘Shovidatat) Function to display all the date members. Define a class BOOK with the following specifications : Private members of the class BOOK are BOOK NO imeger type PRICE double (pri TOTAL COsTO, Ae OR li itn FW omer ot copies where N is passed fo the function a argument. Public members of the class BOOK are INPUTO) function to esd BOOK_NO., PRICE PURCHASE() “function to ask the user te input the number of copies 1 be purchased. It invokes TOTAL_COST() and prants the total ‘cast to be paid by the user. OBJECTIVE: Programming using constructs, looping, stsing and type conversions, OVERVIEW: SELECTION CONTROL STRUCTURE: A sélection contro! structure, allows a program io select belween two or more altemative paths of + ifStalement: if statement is the most basi¢ selection control structure, ‘Symtas: ilfboolean expression) t Statement; itfboolsan pression) ‘ ‘Statement; ‘f{boolean expression) t's a multivay branching statement, [tis based on value on expression. Statement; Statement; ‘Statement; Looping statement causes a section of statements in the program to be executed a certain number of ‘times: The repetition remains until the eondition is true. IEthe condition false loop ends, and the control structuire passes to the next statement, © Enhanced For Loop: This type of for loop allows iterating through an array without creating an iterator. And do nit ‘need to maintain iidex of each element, ‘Syn Tonldeelarationexpression) ' Casting allow converting a variable of one datatype to another. ‘Tynes of conversion: |, Implicit conversione Automatic conversion take place of one datatype to another. ‘Example int to long automatic conversion. 2. Explicit conversion- We force to convert one datatype to another char ch = "A"; int Aseio(intjch; ‘Explicit eonversion take place Examnls: * @author NaveenSagayaselvaRaj ” public cass Second_ Program public static void main(String arg{}) t Systemoutpriauing"**Find whetber the given element is Alphabet ar a ‘Numberic*in'y, char ch="H’; int Asci=(intjeh; iM(Asci>~6S AA Asci<-80) | (Asci>=B7 A Asci<=122)) t ‘Systen.out printing is Alphabet"; 1 clu i{(Asci>adt && Ascic=57)) t ‘System out printing iva Numer ive * author NaveenSapayaselyaRaj i] public static void maitString ares) ‘ int, umn 1,6, ds ‘Searmer in = new Seanner(System in}: Systemout printin(“Enter the number of rwws of Moyes triangle you want"): n= in.nexttm() ‘System.out.printin("**Floydl'stiamghe®*"}; for(e=1ienew in 10}, int sum; ‘Scanner in=new Seanner(System.in): ‘System. out.printin¢"Enter 10 elements: "); fakin i=0:4<10i-+) t anay{if-in.netInt(); 1 Forint i010) Enter 10 elements 1234567890 [Sum of the clements of nn Array: 45 [BUILD SUCCESSFUL (total time: || seconds) ic * author NayecnSagayase nas} + public class Fifth_ Program { public static vote main(String arefib t {nt org_sre{ [mew inal 2]12): set Temata ahs ‘System.outyprinting"Enier the cei for 2X2 matrix:"); Fonfint fdbii<2si+) ! for(int jOj=2ij+*) ; ‘org_arei[i}-innextinit), ebeccasieds am POD) ‘ monet tea_arrfilGi rors, arr] ' i Forint i= Oii<251+-4) t font joajaie) i Systom.on printer) i System.out printing; rn: seeeeereeeeteanspose of Matrixtteeeee® ‘4, Write a Java program to find produet ofn elements in an aay b. Write a Java program to find addition of two matrices a. Write Java program te find whether the given element in the array are pesitive real mumiber or negative real number or zero 1b. Write a Java program to find a given matrix is diagonal matrix oF not a. Write a Java program for TIC TAC TOE game OBJECTIVE: Detailed study on string elass andl its methods OVERVIEW: Siting class: String is the most commonly used class in Java. String isa instance of the class string. They are reat object, Description Reelimis the chataeter atthe specified indsie int compareTo(Object 0) ‘Compares this String to another Objeet, Cornpares two strings Jexicographically: int compareTo(String anotherString) int CompareTolgnoreCase(String str) ‘Compares (Wo. sttings lexicagraphically, ignoring case di String concat(String str) ‘Concatenates the specified siting to the end of this string boolean contentEquals(StringBufier sb) “Returns: ue iP and only, iP this: String Static String copy ValueOr(ehar{} data) static Sting copy ValueCt{char(] data, int offset, int count) boolean endsWith(String suffix) Tests if this sting enuls With the specified sullix boolean equals(Object anObject) (Cniparss this trig to the epetified object boolean equals! gnoreCase( String Gompares this String to another String. anotherString) ignoring ease considerations. byte getfaytes() Encodes this String into a Sequence of bytes using the platform's default cbarset, storing ihe result into new byte array. byte[] getBytes(String charserName) Encodes this String into’ sequence’ of bytes using. the named charset, storing the result into a new byte array. void getChars(int steBegin, int seeEnd, [Copies Ghiarasters fromm this string! ant ths charf] dst, int dstBegin) destination character array. int hashCode), ‘Refumsia hash eade for this string: ‘nt indexOftint eh) RAR NE RREE ‘occurrence of the specified int indeNORGnt eh, int fronaladen) int indexORString str) int indexORString str, int fromfndex) String intem(), int lastindexOf{int ch) int lastlnidesOfGint ch, int fromlndex) int lastindexOf(String str) int lastIndexOf{String st, int fromindex) int Length() boolean matches(String regex) boulcan regionMatches(boolean ignoreCase, int toffset, Sting other, i offset, int len) boolean regionMatchestint foftset, String other, int ooffet, int Ten) ngereplace(char oldChar, char newChar) String replaceAll(String reyes, String replacement ) String replaceFirst(String rezex, String replacement) String{] spli(String rexex) String] spli(String regex, int limit) boolean startsWith(String prefix) boolean startsWith(String prefix, int tofiset), CharSequence subSequence(int besinindex. int endindex) RETRAS INE IRUE Within Wiis Sino NEBR ‘occurrence of the specified charmeter, starting the search atthe specified ides. Reetidens the index within this sirinorthe First ‘ecurrence of the specified substring, Reeters the index within this siringor the First ‘occurrence of the specified substring, starting at the specified index Retims a canonical Fepieseniation for the string object, Rear the index within this tring oF the last ‘oceturrence of the specified charicier Reetwins the index withincthis siting oF the last Occiimence of the specified’ character, ‘searching buckward start at the specified index Retums the index within this string Of the Fiehimost oecurrence of the specified substring, ‘Returns the fides within this string of the last ‘occurrence of the specified substring, searching backward starting at the specified index. Rees tHe Neo OF hs Sin? “Tells whether oF not this string matches the given regular expression: ‘Tests if hve String regions aie equal: ‘Tests if two string regions are equal Returns « new string resulting from replacing all occurrences of oldChar in this string with newChar Replaces each substring of this siring that matches the given regular expression vith the ‘biven replacement. Replaces the first substring of this string that matches the given regular expression with the riven Feplicemest. Splits this string around matches of the given regular expression. Splits this Sting arduind matches of the given regularexpression. “Tess iF this sirinw Sante With the Speed prefiy ‘Tests if this siring starts with the specified prefis beginnings specified index Retiims @ new character sequence that 16 a ‘Sample coding: i ** @author NoveenSagayaselvaRa} a public elass Sixth_Program { ()Find whether the string is plaindroime or not Publi state void main(String arg) { String tr ‘Searner in-new Seanner(System. ia): System.out.prnwing“Enter the string: "): stein next; ‘Revere the Sting String rew ="; int length=sr-tength}: Gout inOsictengthir*) t reyt=atr.charA (iengtsiel); } ills comparcFo(rey)--0) ' ‘System out prinkin(s a Paliadsome": 1 else t ‘Systermout printin(“ts a not Palindrome”); 1 ’ [BUILD SUCCESSFUL (total time: 7 seconds) a, Write a program to find length of the given string without using the string class's method Db. Write Java program to find number of lower case and number of upper ease letters in a string a. Write « Java program to find whether the given siring és palindrome or not without using string cliss’s methods b. Writes Java program to change upper case character to lower ease character ina string, vice versa, 4 Write Java program to Find whether the given string is palindrome or no if the charactersof the strings i interchanged Eg: UP Enter the string: tests O(P 1h wall became palindrome Programming using a spectal type of member function OVERVIEW: sh Constructor method is a special kind of method which are used to initialize objects. ‘Chamcteristic. of Constmetor: ‘Constructor name same as the class name It should be declared as public It shoulld not have any return type I invoked when an abject of class is ereated, i can't be called explicitly. i-can be overloaded ‘Tynes of Constructor, 1. Default constructor ~- Constructor without arguments 2. Parameterized constructor ~ Constructor with arguments ‘Default constructor: * @author NaveenSegayaselvaRa) O Public class Seventh Programs | Seventh_Progtatn() System.out printing” Cosstruetar method called." y public satie void main(Stringl] args) { Seventh Program abj = new Seventh, Program [Constructor methed called. BUILD SUCCESSFUL (total time: 0 scconds) * G@aiuibir NaveenSagayaselvaRa) ” public class Ejgth, Prognumm { Eigth_Program(int iam) { System. out println(" Number: “én; 4 ‘publi¢ Matic Void main(Stringf] anzs) | Eih_Program obj = new Eigth_ Prorat S0), BUILD SUCCESSFUL (total time: @ seconds) a. (Define a class called fruit with the following attributes: Name of the fruit 2. Single fruit or bunch fruit 3. Price Define a suitable constructor and display. Frat() method that displays values of all the attributes. ‘Write a program that ereates 2 objects of fruit elass and display thetr atributes, 14 SSRRENIL| Sebsassssassasessee: Programming using various types of inheritance concept OVERVIEW: Inheritance: Inheritance enable yau to reuse the functionality and capabilites of the existing class by extending a new class from existing class and adding new fture to it, in inheritance the class that inherits the data inictnber arid ehethods fom another elass is known as Subelass. The class from which the subclass inherits is ‘known as the super lass. ‘Types of Inheritance: LL Single Level Inheritance 2. Multilevel Inheritance ‘Single Level Inheritance: ‘Suman: ‘Single Level Inheritance lass super

You might also like