0% found this document useful (0 votes)
16 views14 pages

Session17 19

The document covers Java concepts like Deque, Comparable interface, command line arguments, Properties file, PrintWriter, StringBuilder, Scanner class and StringTokenizer. Code examples are provided to demonstrate these concepts including creating and manipulating strings, reading from properties file and command line arguments, formatting output using PrintWriter and printf.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views14 pages

Session17 19

The document covers Java concepts like Deque, Comparable interface, command line arguments, Properties file, PrintWriter, StringBuilder, Scanner class and StringTokenizer. Code examples are provided to demonstrate these concepts including creating and manipulating strings, reading from properties file and command line arguments, formatting output using PrintWriter and printf.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 14

SESSION 17)

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

Slide 3):-
==============================

// Deque with STACK example

import java.util.*;
import java.io.*;
public class TestStack
{
public static void main(String[] args){

Deque<String> stack = new ArrayDeque<>();

stack.push("one");

stack.push("two");

stack.push("three");
int size = stack.size()-1;
while (size >= 0 ) {

System.out.println(stack.pop());

size--;

Slide 7):-
====================================
import java.io.*;
import java.util.*;

class ComparableStudent

implements Comparable<ComparableStudent> {

private String name; private long id = 0; private double gpa = 0.0;

public ComparableStudent(String name, long id, double gpa){


this.name = name;
this.id = id;
this.gpa = gpa;

}
public String getName(){ return this.name; }

public long getId() { return this.id ; }

public double gpa() { return this.gpa ; }

public String toString() {


return this.name+ " " + this.id + " " + this.gpa ;}

public int compareTo(ComparableStudent s){

int result = s.getName().compareTo(this.name); // descebing order of names.

if (result > 0) { return 1; }

else if (result < 0){ return -1; }

else { return 0; }

/*
public int compareTo(ComparableStudent s){

// sort the objects in desceding order based on id values.

if (s.getId() > this.id) { return 1; }

else if (s.getId() < this.id){ return -1; }

else { return 0; }

} */
}

public class TestComparable {

public static void main(String[] args){

Set<ComparableStudent> studentList = new TreeSet<>();

studentList.add(new ComparableStudent("Thomas", 1111, 3.8));

studentList.add(new ComparableStudent("Adams", 2222, 3.9));

studentList.add(new ComparableStudent("George", 3333, 3.4));

for(ComparableStudent student:studentList){
System.out.println(student);
}
}
}

Slide 13 ):-

=================================

public class TestArgs {

public static void main(String[] args)

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

{
System.out.println("args[" + i + "] is '" + args[i] + "'");

o/p:
-------------------------

java TestArgs "Ted Baxter" 45 100.25


args[0] is 'Ted Baxter'
args[1] is '45'
args[2] is '100.25'

Slide 15):-

Step 1):
============
CREATE A FILE ( ServerInfo.properties )

hostName=172.23.172.132
userName=scott
password=tiger

Step 2):-
==============

import java.io.*;

import java.util.*;

public class PropertiesDemo


{

public static void main(String[] args) {

Properties myProps = new Properties();

try

FileInputStream fis = new FileInputStream("ServerInfo.properties");

myProps.load(fis);

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());

// Print Values

System.out.println("Server: " + myProps.getProperty("hostName"));

System.out.println("User: " + myProps.getProperty("userName"));

System.out.println("Password: " + myProps.getProperty("password"));

Slide 16):'-
==================================
import java.io.*;

public class prt1 {

public static void main(String args[])


{
String userName1 = System.getProperty("userName");

String password1 = System.getProperty("password");

System.out.println(" username : "+ userName1);

System.out.println(" password : "+ password1);


}

compile :-
d:\vijay\javac prt1.java
execute :-
d:\vijay\java -DuserName=hr -Dpassword=hr prt1
Slide 17):-
==================================
import java.io.PrintWriter;

public class PrintWriterExample


{
public static void main(String[] args)
{

// PrintWriter will flush the output buffer to the underlying device ( here
console).

PrintWriter pw = new PrintWriter(System.out, true);


pw.println("This is some output.");
}
}

Slide 19):-
================================

public class PrintfExample


{
public static void main(String[] args)
{
PrintWriter pw = new PrintWriter(System.out, true);

double price = 24.99;

int quantity = 2;

String color = "Blue";

System.out.printf("We have %03d %s Polo shirts that cost $%3.2f.\n", quantity,


color, price);

System.out.format("We have %03d %s Polo shirts that cost $%3.2f.\n", quantity,


color, price);

String out = String.format("We have %03d %s Polo shirts that cost $%3.2f.",
quantity, color,

price);

System.out.println(out);

pw.printf("We have %03d %s Polo shirts that cost $%3.2f.\n", quantity, color,
price);

}
Slide 23 ):-
====================================

- To create a mutable String we can use StringBuilder

- This is not thread safe.

- This class is in java.lang package.

- Thread safe means the the methods are synchronized that is at a given point
of time only one thread can work on the object.

- Not Thread safe in this multiple threads can work on an object at a given
of time.

public class StringBuilder1


{
public static void main(String arg[])
{

StringBuilder sb=new StringBuilder(500);

System.out.println("First Time"+sb);

sb.append("I am adding a String");

System.out.println("Second Time "+sb);

//sb.append("Hello");
//sb.append("-Hai");

sb.append("Hello").append("-Hai");

System.out.println("Third Time :"+sb);

Slide 24):-
====================================
String
============

->String is a class in java which is in java.lang package.

->In java string literal is an object.

"Hello" -> is an object in java.

String str="Gagan";

"Gagan" is equal to new String("Gagan");


public class StringDemos
{
public static void main(String arg[])
{
String str="Hello Sunil";

//length() Method
System.out.println("String Length is:"+str.length());
System.out.println("String Length is:"+"Suresh".length());

//toUpperCase() method
String uppercase;
uppercase=str.toUpperCase();
System.out.println("Upper Case :"+uppercase);

//substring() method
String substr;
substr=str.substring(1);
System.out.println("Substring :"+substr);

String substr_beg_end;
substr_beg_end=str.substring(2,9);
System.out.println("SubString :"+substr_beg_end);

//replace() method

String replace="Harish Kumar";


String replaced=replace.replace('r', 'l');
System.out.println("After Replacing r to l:"+replaced);

//split() Method
String record="S1001,Vijay,Trainer,Cloud Campus";
String tokens[]=record.split(",");

for(int i=0;i<tokens.length;i++)
{
System.out.println(tokens[i]);
}
String str1=new String("Hello");
String str2=new String("Hello");

if(str1==str2)
System.out.println("Str1 and Str2 is equal");
else
System.out.println("Str1 and Str2 is not equal");

System.out.println("String1 HashCode:"+str1.hashCode());
System.out.println("String2 HashCode:"+str2.hashCode());

String str3="Sunita";
String str4="Sunita";

if(str3==str4)
System.out.println("Str3 and Str4 is equal");
else
System.out.println("Str3 and Str4 is not equal");

System.out.println("String3 HashCode:"+str3.hashCode());
System.out.println("String4 HashCode:"+str4.hashCode());
//equals() method
if(str1.equals(str2))
System.out.println("str1 and str2 are equal");
else
System.out.println("str1 and str2 are not equal");

Session 19)
----------------------------------------

Slide 2):-
===============================================

public class StringSplit {

public static void main(String[] args){

String shirts = "Blue Shirt, Red Shirt, Black Shirt, Maroon Shirt";

String[] results = shirts.split(","); // , is delimiter to separate strings

for(String shirtStr:results){

System.out.println(shirtStr);

}
}
}

Slide 3):-
==============================================

- This class is in java.util package.

- nextToken(),hasMoreTokens() are the methods which are in this class.

import java.util.StringTokenizer;
public class StringTokenizerDemo
{
public static void main(String arg[])
{

//creating a StringTokenizer Object

//There is a constructor which will take two parameter


//One Parameter the String with Dilimited Characters
//One Parameter which is the Dilimited Character

StringTokenizer token =new StringTokenizer("S1001,Vijay,Trainer",",");

//hasMoreTokens() and nextToken() are the methods in StringTokenizer Class


//hasMoreTokens() which returns boolean value
//nextToken() method which will return string value

while(token.hasMoreTokens())
{
String str=token.nextToken();
System.out.println("Token ::"+str);
}

Slide 4):-
===============================================

eg1):-
-------------
import java.io.*;
import java.util.*;

public class ScannerInput {


public static void main(String args[]) {

int m,p,c,total;
String name;

Scanner sc = new Scanner(System.in);

System.out.println("enter student maths subject marks");


m = sc.nextInt();

System.out.println("enter student physics subject marks");


p = sc.nextInt();

System.out.println("enter student Chemistry subject marks");


c = sc.nextInt();

System.out.println("enter student name");


name = sc.next();

System.out.println(" name = " + name +" m = "+ m + " p = "+ p + " c = "+ c );

eg 2):-
---------------------------
String Builder :-

StringBuilder and StringBuffer:

-> Preferred tools when strings are small size

-> More efficient than �+�

-> Set the capacity to the size you actually need

-> The StringBuilder class is not thread-safe.

-> StringBuilder is used to create a mutable String object.

-> The StringBuffer class is thread-safe.

import java.util.Scanner;
import java.io.*;
public class ScannerDemo {
public static void main(String[] args) {

Scanner s = null;

StringBuilder sb = new StringBuilder(64);

String line01 = "1.1, 2.2, 3.3";

float fsum = 0.0f;

s = new Scanner(line01).useDelimiter(", ");

try {

while (s.hasNextFloat()) {

float f = s.nextFloat();

fsum += f;

sb.append(f).append(" ");

System.out.println("Valuesfound:"+sb.toString());

System.out.println("FSum: " + fsum);


} catch (Exception e) {

System.out.println(e.getMessage());
}

}
}

Slide 6):-
===========================
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample
{
public static void main(String[] args)
{
String t = "It was the best of times";
Pattern pattern = Pattern.compile("the");
Matcher matcher = pattern.matcher(t);
if ( matcher.find())
{
System.out.println("Found match!");
}
}
}

Slide 9):-
==============================
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatching1


{

public static void main(String[] args)


{
String t = "It was the best of times bust bost";

Pattern pattern = Pattern.compile("b.st");

Matcher m=pattern.matcher(t);

while(m.find()) // find() returns true if a match is found.


{
//group is a method which will return you the matched
//string in the target string.

System.out.println("The Pattern String found"+m.group());


}

Slide 12):-

==============================

Finding the Digits matching in the String.


===========================================

Example1.java
================

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example1
{
public static void main(String arg[])
{

String t = "Jo told me 20 ways to San Jose in 15 minutes";


Pattern pattern = Pattern.compile("(\\d\\d)");
Matcher m=pattern.matcher(t);

while(m.find())
{
System.out.println(m.group());

Slide 15):-
======================================
Quantifier Example
=======================

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example2


{

public static void main(String arg[])


{

//String T1="long time ago there was a long river";

String T1 = "Longlonglong ago, in a galaxy far far away";

Pattern pattern = Pattern.compile("(long){2}");

Matcher m=pattern.matcher(T1);

while(m.find())
{
System.out.println(m.group());

String T2 = "Longlonglong ago, in a galaxy far far away";

Pattern pattern1 = Pattern.compile("gal.{3}");

Matcher m1=pattern1.matcher(T2);

if(m1.find())
{
System.out.println(m1.group(0));

}
}
}

Slide 17):-
========================================

// Greediness Example
// =====================

import java.util.regex.*;
public class Example3
{

public static void main(String arg[])


{

String T1 = "Longlonglong ago, in a galaxy far far away";

// no Greediness with the "?"

Pattern pattern = Pattern.compile("ago.*?far");

Matcher m=pattern.matcher(T1);

if(m.find())
{
System.out.println(m.group());

}
}

Slide 19):-
===================================
//Boundary Matches
//====================

import java.util.regex.*;
public class Example4
{
public static void main(String arg[])
{

String T1 = "it was the best of times or it was the worst of times";

Pattern pattern = Pattern.compile("^it.*?times");

Matcher m=pattern.matcher(T1);

if(m.find())
{
System.out.println(m.group());

}
}

Slide 23):-
=================================

// Apply ReplaceAll() in strings.


//==============================

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class ReplacingExample1

public static void main(String[] args){

String header = "<h1>This is an H1</h1>";

Pattern p1 = Pattern.compile("h1");

Matcher m1 = p1.matcher(header);

if (m1.find())
{
header = m1.replaceAll("p");

System.out.println("header : " + header);

You might also like