150 terms

Java Syntax


Terms in this set (...)

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
readLine() in BufferedReader()
combination of InputStreamReader and BufferedReader
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class StreamReader {
public static void main(String[] args) throws java.io.IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

reading characters from input
char ch= br.readLine().charAt(0);
public static void main(String[] args) throws java.io.IOException, java.lang.NumberFormatException{
converting String to int
int num= Integer.parseInt(br.readLine());
converting String to double
Double d = Double.valueOf(br.readLine());
int[] intArray = new int[100];
array length
int arrayLength = intArray.length;
array initialization
int[] intArray = { 0, 3, 6, 9, 12, 15, 18, 21, 24, 27 };
selection sort
find the smallest each time and bring it to the beginning of array
insertion sort
sort the first n items and move forward
bubble sort
move forward, compare each two item and swap them if needed, then again come back to the beginning of array and repeat until sorted
selection sort
for(out=0; out<nElems-1; out++) // outer loop
min = out; // minimum
for(in=out+1; in<nElems; in++) // inner loop
if(a[in] < a[min] ) // if min greater,
min = in; // we have a new min
swap(out, min); // swap them
} // end for(out)
pushing an item into an stack
stackArray[++top] = j;
popping an item from stack
return stackArray[top--];
String length
int nameLength = courseName.length();
index of a character in a string
Finding number of occurrences of a word in a text
public int wordCount(String text, String word) {
int count = 0;
int pos = text.indexOf(word,0);
while (pos >= 0) {
pos = text.indexOf(word,pos+word.length());
return count;
converting a word to lower case
strikesOnly = countText.substring(9,18);
public boolean startsWith(String s)
public boolean endsWith(String s)
public boolean equals(String s)
public String replace(char oldChar, char newChar)
// Returns a new string resulting from replacing all
// occurrences of oldChar in this string with newChar.
public String trim()
boolean result2 = str1.equalsIgnoreCase(str2);
Reading String one character at a time
StringReader reader = new StringReader(string1);
int singleChar = reader.read();
Using this mechanism, the read() method of the
StringReader class returns one character at a time, as an
integer. Each time the read() method is called, the
next character of the string will be returned.
string tokenizer
StringTokenizer strTok = new StringTokenizer(test);
pushing words from StringTokenizer into Stack
while(strTok.hasMoreTokens()) {
splitting a String
String[] results = str.split(",");
case switch
case 'A':
System.out.println("You got an A!");
case 'B':
System.out.println("You got a B!");
System.out.println("You didn't get an A or B!");
alternative case switch with less code
case 'A':
case 'B':
case 'C':
System.out.println("You passed!");
case 'D':
System.out.println("You should retake this...");
Anything declared private is completely hidden from outside classes and subclasses
Accessible from within the same package and all subclasses
is automatically imported into every program you write
comparing two strings
convert a primitive type to an String
Whenever we use print or println, we are using the
toString() method
String concatenation
Because Strings are references to objects, we can
not use the "+" concatenation operator.
We need to use a String method
convert String to int
int anInt = Integer.parseInt(myStringVariable);
convert String to double
String stringValue = new String("174.82");
Double tempValue = Double.valueOf(stringValue);
double doubleValue = tempValue.doubleValue();
some useful String methods
Character.isLetter( c )
Checks to see if a character is a letter (A-Z, a-z)
Character.isWhitespace( c )
Character.isDigit( c )
Character.isLowerCase( c )
Character.isUpperCase( c )
Character.toUpperCase( c )
Character.toLowerCase( c )
iterating over StringTokenizer
while (tokens.hasMoreTokens() )
try catch phrase
try {
// code that can throw an exception
catch (Exception exceptionVariableName) {
// code to handle exception
extended try catch
try {
// code that can throw an exception
catch (exceptionName1 variable1Name) {
// code to handle exception1
catch (exceptionName2 variable2Name) {
// code to handle exception2
catch (exceptionName3 variable3Name) {
// code to handle exception3
reading from a file
Scanner infile = new Scanner(new FileReader("myGettysburgAddressText.txt"));
convert to double
theDouble = Double.parseDouble(stdin.readLine().trim());
reading char from input
theChar = (char) System.in.read();
String objects are immutable
—their character
contents cannot be changed after they are created
initializing a char array
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
Get entire set of characters in String
StringBuilder methods
- Method charAt()
• Return StringBuffer character at specified index
- Method setCharAt()
• Set StringBuffer character at specified index
- Method getChars()
• Return character array from StringBuffer
- Method reverse()
• Reverse StringBuffer contents
- Method append()
• Allow data values to be added to StringBuilder
Scanner+chatAt combo
Scanner scanner = new Scanner( System.in ); // create scanner
System.out.println( "Enter a character and press Enter" );
String input = scanner.next();
char c = input.charAt( 0 ); // get input character
create file object
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
while (in.hasNextLine())
String line = in.nextLine();
// Process line;
useDelimiter in Scanner
Scanner in = new Scanner(. . .);
TreeSet initialization
TreeSet<Integer>s = new TreeSet<Integer>( );
map initialization
Map myMap = new TreeMap( );
putting values in a Map
myMap.put("Mary", 15);
myMap.put("Bob", 20);
iterating over a map
Set es = myMap.entrySet( );
Iterator it = es.iterator( );
while(it.hasNext( ))
TreeMap initialization
Map<String, Integer>myMap = new TreeMap<String, Integer>( );
boolean blnExists = ht.containsKey("2");
Map methods
Clear() Remove all mappings
containsKey(k) Whether contains a mapping for k
containsValue(v) Whether contains a mapping to v
SetentrySet() Set of key-value pairs
get(k) The value associated with k
isEmpty() Whether it is empty
keySet() Set of keys
put(k,v) Associate v with k
remove(k) Remove the mapping for k
size() The number of pairs
values() The collection of values
HashTable initialization
Hashtable<String,String> table2 = new Hashtable<String,String>();
smallest and largest int
• MAX VALUE: The largest int
• MIN VALUE: The smallest int
throw new
throw new IllegalArgumentException("That's not positive!");
public static int parseInt(String s) throws NumberFormatException;
public static void main (String[] args) throws java.io.IOException {
new file
File newFile = new File("tweet.txt");
FileWriter fileWriter = new FileWriter(newFile);
write file
fileWriter.write("Mona Jalal");
FileReader fileReader = new FileReader(newFile);
BufferedReader file
BufferedReader bufferedReader = new BufferedReader(fileReader);
EOF file while loop
while ((line = bufferedReader.readLine()) != null) {
for (char c : expression.toCharArray( )) {
check to see if a character exits in a String
if (opening.indexOf(c) != −1)
collection iterator
Iterator<ElementType> iter = collection.iterator( );
define a Tree interface
public interface Tree<E> extends Iterable<E> {
NP Problems
verifiable in polynomial time
convert int to binary
Integer.toBinaryString(int i)
Double hashing
h(k, i) =(h1(k) +i·h2(k)) mod m where h1(k) and h2(k) are two ordinary hash functions.
probing hash function
h(k, i) = (h 0 (k) +i) mod m where h 0 (k) is ordinary hash function
Open hashing vs Chaining
Open Addressing: better cache performance
Chaining: less sensitive to hash functions and the load factor α
to grow or shrink table hash function must change
Find the size of a directory
du -h WACM
see the running processes of a user
ps -u jalal
top -U jalal
pstree jalal
status of task
'D' = uninterruptible sleep
'R' = running
'S' = sleeping
'T' = traced or stopped
'Z' = zombie
how to get "dynamic view of process"?
top command
set an environment variable
export VARIABLE=value in bash
setenv VARIABLE value in sh, csh, tcsh
alias newcmd="oldcmd options"
alias clobber="rm -f"
alias rm="rm -i"
kill -s SIG PID
"Hangup" signal
"Interrupt" signal (same as sent by Ctrl-c) "Sure kill" signal
"Nice kill" signal
kill -l
What is the range of ports or how many ports are there?
Port numbers can vary from 0 to 65535, so total we can get 65536 ports
What is a socket?
Socket is combination of software Port and IP address.
# nmap -O
-O tries to figure the target operating system
change priority
nice -n 5 process_name
renice -5 PID
run level
Runlevels define what tasks can be accomplished in the current state (or runlevel) of a Linux system. Every Linux system supports three basic runlevels, plus one or more runlevels for normal operation.
0 Shut down (or halt) the system
1 Single-user mode; usually aliased as s or S
6 Reboot the system
2 Multiuser mode without networking
3 Multiuser mode with networking
5 Multiuser mode with networking and the X Window System
switch to another run level?
telinit 5
● Will by default share memory
● Will share file descriptors
● Will share filesystem context
● Will share signal handling
● Will not by default share memory
● Most file descriptors are not shared
● Don't share filesystem context
● Don't share signal handling
self-balancing tree
a self-balancing (or height-balanced) binary search tree is any node-based binary search tree that automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary item insertions and deletions. Tree rotations are very common internal operations on self-balancing binary trees to keep perfect or near-to-perfect balance.
Height-balanced tree
A tree whose subtrees differ in height by no more than one and the subtrees are height-balanced, too. An empty tree is height-balanced.
disadvantages of hashtables
Hash tables become quite inefficient when there are many collisions. While extremely uneven hash distributions are extremely unlikely to arise by chance, a malicious adversary with knowledge of the hash function may be able to supply information to a hash that creates worst-case behavior by causing excessive collisions, resulting in very poor performance, e.g. a denial of service attack. In critical applications, universal hashing can be used; a data structure with better worst-case guarantees may be preferable
integer hash
hash(x) = x % TableSize
string hash
for( int i = 0; i < key.length( ); i++ )
hashVal = hashVal + key.charAt( i );
return hashVal % tableSize;
string hash another idea
public static int hash( String key, int tableSize ) {
int hashVal = 0;
for( int i = 0; i < key.length( ); i++ )
hashVal = 37 * hashVal + key.charAt( i );
hashVal %= tableSize;
if( hashVal < 0 )
hashVal += tableSize;
return hashVal;
load factors
alpha= number of entries/table size
problems with separate chaining
Requires allocation of new list nodes, which
introduces overhead.
Requires more code because it requires a linked list data structure in addition to the hash table itself.
problems with linear probing
Problem: Primary Clustering.
Full cells tend to cluster, with no free cells in between
Time required to find an empty cell can become very large if the table is almost full
Quadratic probing
primary cluster is not a problem anymore
Hash Tables with Quadratic Probing and Double Hashing can have failed inserts if the table is more than half full.
huffman tree
Choose the two trees with smallest weight and merge them.
greedy algorithm
runtime O(nlogn)
examples of divide and conquer
merge sort
quick sort
binary search
towers of hanoi
merge sort
T(N) = 2 T(N/2) + N
Euler path
An Euler Path is a path through an undirected
graph that visits every edge exactly once.
only 0 or two vertices can have odd vertices, starts with one odd vertice and ends in the other one
euler circuit
for an euler circuit to exist, all vertices should have even degrees
hamiltonian cycle
visits every vertex
no polynomial solution
bioconnected graph
A graph is biconnected if there is no single vertex v, such that removing v will disconnect the remaining graph.
G does not contain any articulation points.
naive approach to biconnected graph
remove each vertex, see if the graph is connected O(V^2+v*E)
1 Gigabyte
1 Megabyte
1 Kilobyte
1 Terabyte
1 Petabyte
for (Map.Entry<Character, Boolean> entry: charCount.entrySet()){
replace all characters with another character
System.out.println("htlllmk kl".replaceAll("l", ""));
convert String to its char array
char[] charArray= s.toCharArray();
StringBuilder sb= new StringBuilder();
\w - Matches any word character.
\W - Matches any nonword character.
\s - Matches any white-space character.
\S - Matches anything but white-space characters.
\d - Matches any digit.
\D - Matches anything except digits.
strArray to List
List<String> strList= Arrays.asList(strArray);
reversing a list
convert list to strArray
strArray= (String[])strList.toArray();
adding items to StringBuilder
convert String to int in java
public static int convertToInt(String s){

return Integer.parseInt(s);

convert int to String in Java
public static String intToStr(int num){

return String.valueOf(num);