




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
Stringclass/CharacterStringBuffer/FileIntroductiontoAstringisaseriesofcharacterstreatedasasingleConstructingStringnewString=newStringmessage=newString("WelcometoJavaprovidesashorthandinitializerforcreatingaStringmessage="WelcometoString:forstringconstantsStringBuffer/StringBuilder:forstringvariablesIntroductionIntroductiontoJavacharchararray[]={?b?,?i?,?r?,?t?,?h?,??,?d?,?a?,bytebytearray[]={?n?,?e?,?w?,??,?y?,?e?,?a?,?r?};StringBufferbuffer;Strings,s1,s2,s3,s4,s5,s6,s7;publicvoidinit(){s=newString(“hello”);buffer=newStringBuffer();s1=new //anulls2=new //s3=newString(chararray); s4=newString(chararray,6,3); s5=newString(bytearray,0,4,4);//s6=newString(bytearray, //news7=new // StringsAreAStringobjectisimmutable;itscontentscannotbeStrings=s=AfterStrings=
After s=
:StringobjectforIntroductionIntroductiontoJavaStringobjectfors:Stringobjectfors:
Thisstringobjectisnowunreferenced
s:Stringobjectfors1==s1==sisfalses2==sistrues==s3istrueIntroductiontoJavacanonical Strings="WelcometoStrings1=newString("WelcometoJava");Strings2=ern();Strings3="WelcometoSystem.out.println("s1==sis"+(s1==s));System.out.println("s2==sis"+(s2==s));System.out.println("s==s3is"+(s==
::for"Welcometo:AstringobjectforRetrievingIndividualCharactersinapubliccharcharAt(int selectandreturnthecharataspecificposition(index:0..length-1)inthestring“welcometoJava”.charAt(0)(returns
12 WelcometoJaWelcometoJavaStringpublicStringconcat(String s1.concat(s2)concatenatess1ands2asanewobjecttobereturned,ands1ands2arenotIfs2.length==0thenreturntheoriginal==s1+s1+s2+s3+s4+s5sameasmessage.substring(0,message.substring(0,IntroductiontoJavasubstring:enabletocreateanewstringbycopingpartofanexistingobject(s)publicStringsubstring(intbeginIndex,intendIndex):returnasubstringcopyofthecharactersfrombeginIndextoendIndex-1.Strings1="WelcometoStrings2=s1.substring(0,11)+ 12 ComparingStringsLexicographicalcomparison:theintegerUnicodevaluesthatrepresenteachcharacterineachstringarecomparedpublicbooleanequals(Objects1.equals(s2)returnstrueIFs2isastringandhasthesamelengthandthesameUnicodecharactersasthecurrentstring(s1),otherwisereturnsfalse andprimitivedatatypes: bothprimitivedatatypevaluesareidentical/bothreferencesrefertothesameobjectinmemoryComparingStringspublicbooleanequalsIgnoreCase(StringIfthecaseoflettersisignored,twocharacters(c1,c2)areequalonlywhen:(a)c1==c2; publicintcompareTo(String0anegatives1islessthanapositives1isgreaterthanThereturnvalueisthedifferencebetweentheinteger example,h(104)-H(72)=ComparingStringspublicboolean(intstart,Strings2,intostart,int (booleanignCase,intstart,Strings2,intostart,intStringStringstr="Look,booleanb1,b2,b1=str.regionMatches(6,"Look",0, //b2=str.regionMatches(true,6,"Look",0,4);b3=str.regionMatches(true,6,"Look",0,5);publicbooleanstartsWith(Stringprefix,intpublicbooleanstartsWith(StringStringThecontentsofastringcannotbechangedoncethestringiscreated.Butyoucanconvertastringtoanewstringusingthefollowingmethods:FindingaCharacteroraSubstringinaindexOf:searchthefirstoccurrenceofacharacter/substringinastring(s)publicintindexOf(charch,intlastIndexOf:searchthelastoccurrenceofacharacter/substringinastring(s)publicintlastIndexOf(Stringstr,intJava".indexOf('W')returnsJava".indexOf('x')returns-Java".indexOf('o',5)returnsJava".indexOf("come")returnsJava".indexOf("Java",5)returnsJava".indexOf("java",5)returns-"WelcometoJava".lastIndexOf('a')returnsIntroductiontoJavaConversionIntroductiontoJavapublicchar[]s.toCharArray();createsanewcharacterarraycontainingacopyofthecharactersinsExample removeallappearancesofthecharacterinthePublicstaticStringsqueezeOut(Stringfrom,char{char[]chars=from.toCharArray();intlen=chars.length;for(inti=0;i<len;i++) if(chars[i]==toss){System.arraycopy(chars,i+1,chars,i,len--i; returnnewString(chars,0, IntroductiontoJavaConvertCharacterIntroductiontoJavaTheStringclassprovidesseveralstaticvalueOf()methodsforconvertingacharacter,anarrayofcharacters,andnumericvaluestostringsThesemethodshavethesamenamevalueOf()withdifferentargumenttypeschar,char[],double,long,int,andfloatForexample,toconvertadoublevaluetoastring,useString.valueOf(5.44).ThereturnvalueisstringIntroductiontoJavaIntroductiontoJavaObjective:Checkingwhetherastringisapalindrome:astringthatreadsthesameforwardandbackward publicstaticbooleanisPalindrome(String{//Theindexofthefirstcharacterintheintlow=//Theindexofthelastcharacterintheinthigh=s.length()-1;while(low<high){if(s.charAt(low)!=s.charAt(high))returnfalse;//Notapalindromehigh--;}returntrue;//ThestringisapalindromeWrapper
Noclassforbyteand[NumberType]MIN_VALUE,MAX_VALUE[Float,Doble]NEGATIVE_INFINITY,POSITIVE_INFINITYNaN(aninvalidfloatTheCharacter+Character(value:+charValue():+compareTo(anotherCharacter:Character):+equals(anotherCharacter:Character):+isDigit(ch:char):+isLetter(ch:char):+isLetterOrDigit(ch:char):+isLowerCase(ch:char):+isUpperCase(ch:char):+toLowerCase(ch:char):+toUpperCase(ch:char):
ConstructsacharacterobjectwithcharvalueReturnstrueifthischaracterequalstoanotherReturnstrueifthecharacterisanuppercaseletterCharactercharObject=newcharOpareTo(newCharacter('a'))//1charOpareTo(newCharacter('b'))//0charOpareTo(newCharacter('c'))//-1charOpareTo(newCharacter('d')//–2IntroductiontoJavaIntroductiontoJavaObjective:Counteachletterinastringignoringcase-sensitive //InvokethecountLettersmethodtocounteachint[]counts=…/**Counteachletterinthestringpublicstaticint[]countLetters(Strings){int[]counts=newint[26];for(inti=0;i<s.length();{if(Character.isLetter(s.charAt(i)))counts[s.charAt(i)-'a']++;}return}ObjectsoftheStringclass:read-StringBuffer/StringBuilder:modifiable,andusedtoimplement+and+=StringBuffervs.StringBuilderpublicCreateanullstring(theinitialcapacityofcharsispublicStringBuffer(intCreateanullbuffer,wherelengthistheNegativeArraySizeException,IfpublicStringBuffer(StringCreateabuffercontainingthecharactersofstr,andaninitialcapacitywhichisLengthandpublicintThenumberofcharacterscurrentlyinthepublicintThenumberofcharacterscanbestoredinthepublicvoidsetLength(intincrease/decreasethelengthofapublicvoidensureCapacity(intEnsurethecapacitytoaminimumofminCapacityStringBuffersmaybeautomaticallyextendedwhencharactersareappended.ButitisnotsoCapacitymethodsmaybeusedtoavoidextendingbuffersformany10overloadedappendmethods,allowingvariousdatatypevaluestobeaddedtotheendofastringbuffer,example:publicStringBufferappend(doublepublicStringBufferappend(ObjectpublicStringBufferappend(charstr[],intoffset,intpublicStringBufferappend(StringActually,StringBufferandappendareusedbycompilertoimplement+and+=forconcatenating”BC”+22isperformedasIntroductionIntroductiontoJava9overloadedinsertmethods,allowingvariousdatatypevaluestobeinsertedatanypositioninastringpublicStringBufferinsert(intoffset,booleanpublicStringBufferinsert(intoffset,charStringBufferbuf=newStringBuffer();Stringnow=newjava.util.Date().toString();buf.ensureCapacity(buf.length()+now.length()+2);buf.insert(0,now).insert(now.length(),":");IntroductionIntroductiontoJavaPublicstaticStringBufferremove(StringBufferbuf,intpos,intcnt){if(pos<0||cnt<0||pos+cnt>buf.length())thrownewintleftover==buf.length()–(pos+cnt)if(leftover==0){buf.setLength(pos);returnbuf;}char[]chrs=newchar[leftover];buf.getChars(pos+cnt,buf.length(),chrs,0);returnbuf;}IntroductiontoJavaExample:CheckingIntroductiontoJavaObjective:CheckingwhetherastringisapalindromeignoringNon-alphanumericCharacters:astringthatreadsthesameforwardandbackward.Assumethelettersarenotcase-sensitiveP.255-256/**ReturntrueifastringisapalindromepublicstaticbooleanisPalindrome(String{//Createanewstringbyeliminatingnon-alphanumericcharsStrings1=//CreateanewstringthatisthereversalofStrings2=//Compareifthereversalisthesameastheoriginalreturns2.equals(s1);Example:CheckingPalindromesIgnoringNon-alphanumeric/**Createanewstringbyeliminatingnon-alphanumericchars*/publicstaticStringfilter(Strings)//CreateastringStringBufferstrBuf=new//Examineeachcharinthestringtoskipalphanumericcharfor(inti=0;i<s.length();i++)if{strBuf.append(s.charAt(i));}//ReturnanewfilteredreturnstrBuf.toString();CheckingPalindromesIgnoringNon-alphanumeric/**Createanewstringbyreversingaspecifiedstring*/publicstaticStringreverse(Strings){StringBufferstrBuf=newStringBuffer(s);//UsethereversemethodforStringBufferreturn}Command-LineInthemainmethod,gettheargumentsfromargs[0],args[1],...,args[n],whichcorrespondstoarg0,arg1,...,argninthecommandline.classTestMainpublicstaticvoidmain(String[]args) }javaTestMainarg0arg1arg2...Example:javaTestMain“firstnum”aiphaExample:UsingCommand-LineObjective:Writeaprogramthatwillperformbinaryoperationsonintegers.Theprogramreceivesthreeparameters:anoperatorandtwo ifif(args.length!=3)System.out.println("Usage:javaCalculatoroperand1operatoroperand2");javaCalculator2+javaCalculator2-javaCalculator2/javaCalculator2“*”RegularRegularexpressions(regex's)aresetsofsymbolsandsyntacticelementsusedtomatchpatternsoftextRegularexpressionsareanextremelyusefultoolformanipulatingtext,heavilyusedintheautomaticgenerationofWebinthespecificationofprogrammingintext Sincejdk1.4,Javahasaregularexpression Matchermbooleanb,IntroductiontoIntroductiontoJavastaticvoidPatternp=null;//正則表達(dá)式Matchermnull操作的字符串booleanb=false;p=Ppile("a*b");m=p.matcher("baaaaab");b=m.matches();p=Ppile("a*b");m=p.matcher("aaaaab");b=m.matches();publicstaticvoidmain(Stringargus[]){test();}
Basic.Matchesanysingle.at=cat,bat,rat,*Matcheszeroormoreoccurrencesofthesingleprecedingcharacter.*at=everythingthatendswithat0*123=123,0123,00123…MatchesanysinglecharacteroftheonescontainedMatchesanysinglecharacterexceptfortheonescontained[cbr]at=cat,bat,[^bc]at=rat,sat…,butnotbat,<[^>]*>=^Beginningof^a=linestartswith$Endof^$=blankline(startswiththeendofline)\Escapesfollowingspecial.\/&[]* \.\\\/\&\[\][cbr]at\.=matchescat.,bat.andrat.only…Charactera,b,orc(simpleAnycharacterexcepta,b,orcathroughz,orAthroughZ,inclusiveathroughd,ormthroughp:[a-dm-p]d,e,orfathroughz,exceptforbandc:[ad-z]athroughz,andnotmthroughp:[a-lq-z]PredefinedCharacter.Anycharacter(mayormaynotmatchlineAdigit:[0-Anon-digit:[^0-Awhitespace [Anon-whitespacecharacter:Awordcharacter:[a-zA-Z_0-Anon-wordcharacter:X,onceornotatX,zeroormoreX,oneormoreX,exactlynX,atleastnX,atleastnbutnotmorethanmtimespattern:xxx-xx-xxxx,xisadigitalregex:[\\d]{3}-[\\d]{2}-[\\d]{4}pattern:(xxx)xxx-xxxx,xisadigital,thefirstnumberisJavapattern:pattern:MonthJune26,RegularExpressionsin021-87888822 IntroductiontoJava IntroductiontoJavaRegularExpressionsinpublicbooleanmatches(StringStringregex="\\w{1,}@\\w{1,}\56\\w{1,}";Stringstr1="zhangsan@";Stringstr2=li@si@;RegularExpressionsinpublicStringreplaceAll(Stringregex,Stringreplacement)publicStringreplaceFirst(Stringregex,Stringreplacement)System.out.println(“JavaSystem.out.println(“JavaJavaJava”,replaceAll(“v\\w”,Output:JawijawiSystem.out.println(“JavaJavaJava”,replaceFirst(“v\\w”,Output:JawiJavaIntroductiontoJavaIntroductiontoJavapublicString[]split(StringpublicString[]split(Stringregex,intlimit)string"boo:and:foo” {"boo","and","foo" {"b","",":and:f"} {"boo","and:foo" {"boo","and","foo" {"boo","and","foo" {"b","",":and:f","","" - {"b","",":and:f","","" {"b","",":and:f"TheFileTheFileclassprovidesseveralcommonmanipulationsthatareusefulwithfilenames.Itprovidesmethodstoseparatepathnamesintosubcomponents,andforqueryingthefilesystemaboutthefileapathnamereferstopublicFile(Stringpath):CreatesaFileobjecttomanipulatethespecifiedpath.ThismethodthrowsaNullPointerExceptionifthepathparameterisnull publicFile(StringdirName,Stringname)File(dirName+File.separator+name) File(fileDir.getPath(),name) Filef1=newFile(“/”);Filef2=newFilef3=new
TheFileget:retrieveinformationaboutcomponentsofaFileobject?sexists:returnstrueifthefileexistsinthefilecanRead:returnstrueifthefileexistsandcanbecanWrite:returnstrueifthefileexistsandcanbeisFile:returnstrueifthefileisanormalisDirectory:returnstrueifthefileisaisAbsolute:returnstrueifthepathisanabsolutepubliclonglastModified():returnsthelastmodificationTheFilepubliclonglength():returnsthefilelengthinpublicbooleanmkdir():Createsadirectory,returningtrueonsuccesspublicbooleanmkdirs():Createsalldirectoriesinthispath,returningtrueifallwerecreatedpublicbooleanrenameTo(Filenew_name):Renamesafile,returningtrueiftherenamesucceededpublicbooleandelete():DeletesthefileordirectorynamedinthisFileobject,returningtrueifthedeletionpublicString[]list():Listsallfilesinadirectoryexcepttheequivalentof“.”and“..”TheFilepublicString[]list(FilenameFilterfilter):Usesthespecifiedfiltertolistfilesinadirectoryequals:trueiftwofileobjectshavethesamepath,notiftheyrefertothesameunderlyingfilesystemobjectFilesarecreatedusingPrintWriter、objectsorRandomAccessFileobjects,notusingFileThecharacterFile.pathSeparatorCharandthestringFile.pathSeparatorrepresentthecharacterthatseparatesfileordirectorynamesinasearchpathimport
IntroductiontoJavapublicIntroductiontoJavapublicstaticvoidmain(Stri
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 成長(zhǎng)記錄袋小學(xué)生課件
- 2025年環(huán)保廁所項(xiàng)目合作計(jì)劃書(shū)
- 2025年重鉻酸鈉項(xiàng)目建議書(shū)
- 加強(qiáng)網(wǎng)絡(luò)信息安全保障條例
- 公司股份制實(shí)施方案
- 金融投資顧問(wèn)投資風(fēng)險(xiǎn)提示書(shū)
- 小王子電影故事解讀
- StA-IFN-1-生命科學(xué)試劑-MCE
- 石油庫(kù)區(qū)員工年終總結(jié)
- 2025年太陽(yáng)能熱發(fā)電系統(tǒng)項(xiàng)目合作計(jì)劃書(shū)
- TPU材料項(xiàng)目可行性研究報(bào)告寫(xiě)作參考范文
- 試用期考核合格證明表
- 常見(jiàn)八種疾病
- 膠粘劑基礎(chǔ)知識(shí)及產(chǎn)品詳解(課堂PPT)
- 鍋爐補(bǔ)給水陰陽(yáng)混床操作步序表
- 2005年第4季度北京住房租賃指導(dǎo)價(jià)格
- 醫(yī)療器械GMP計(jì)算機(jī)軟件確認(rèn)控制程序
- 蘇教版最新五年級(jí)數(shù)學(xué)上冊(cè)應(yīng)用題與解決問(wèn)題專項(xiàng)
- 髖關(guān)節(jié)置換術(shù)男性患者留置尿管最佳時(shí)機(jī)探析和對(duì)策
- [爆笑小品校園劇本7人]爆笑小品校園劇本
- 岸邊集裝箱起重機(jī)CMS系統(tǒng)
評(píng)論
0/150
提交評(píng)論