banner



What Is A Data Type In Java

3.one   Using Data Types


A data type is a set of values and a fix of operations defined on those values. The primitive data types that yous have been using are supplemented in Java past extensive libraries of reference types that are tailored for a large variety of applications. In this section, nosotros consider reference types for string processing and epitome processing.

Strings.

You accept already been using a data type that is not primitive—the

Cord

data type, whose values are sequences of characters. We specify the behavior of a data blazon in an application programming interface (API). Here is a partial API for Coffee's String data blazon:

String API

The starting time entry, with the same name as the class and no return type, defines a special method known equally a constructor. The other entries define instance methods that tin accept arguments and return values.

using a reference data type
  • Declaring variables. You declare variables of a reference type in precisely the same mode that you lot declare variables of a primitive type. A declaration statement does not create annihilation; it merely says that nosotros volition use the variable proper name s to refer to a Cord object.
  • Creating objects. Each data-type value is stored in an object. When a client invokes a constructor, the Java arrangement creates (or instantiates) an individual object (or example). To invoke a constructor, employ the keyword new; followed by the class name; followed by the constructor'south arguments, enclosed in parentheses and separated by commas.
  • Invoking instance methods. The most important departure betwixt a variable of a reference blazon and a variable of a primitive type is that you can utilize reference-type variables to invoke the instance methods that implement data-type operations (in contrast to the built-in syntax involving operators such equally +* that we used with archaic types).

At present, nosotros consider various string-processing examples.

  • Data-type operations. The following examples illustrate various operations for the String information type.
    String operations
  • Code fragments. The post-obit lawmaking fragments illustrate the use of diverse string-processing methods.
    String code fragments
  • Genomics. Biologists utilise a elementary model to represent the building blocks of life, in which the letters A, C, G, and T represent the four bases in the DNA of living organisms. A gene is a substring that represents a functional unit of critical importance in understanding life processes. PotentialGene.java takes a DNA string as an statement and determines whether it corresponds to a potential factor based on the following criteria:
    • Information technology begins with the start codon ATG.
    • Its length is a multiple of 3.
    • Information technology ends with one of the finish codons TAG, TAA, or TGA.
    • It has no intervening stop codons.

Color.

Color values Java'due south Color information type

represents colour values using the RGB color model where a color is defined past three integers (each between 0 and 255) that represent the intensity of the ruby-red, green, and blue components of the color. Other colour values are obtained past mixing the carmine, blue and green components.

The Color information type has a constructor that takes 3 integer arguments. For example, you can write

Colour red      = new Color(255,   0,   0); Color bookBlue = new Colour(  9,  90, 166);                  

to create objects whose values represent pure red and the blueish used to print this book.

The post-obit table summarizes the methods in the Color API that we utilise in this book:

Color API

Hither are some example clients that utilize the

Colour

data type.

  • Albers squares. AlbersSquares.coffee displays the two colors entered in RGB representation on the control line in the format developed in the 1960s by Josef Albers that revolutionized the way that people think most color.
    Albers squares
  • Luminance. The quality of the images on mod displays such as LCD monitors, plasma TVs, and cell-phone screens depends on an understanding of a color property known as monochrome luminance, or effective brightness. Information technology is a linear combination of the 3 intensities: if a color's red, green and bluish values are r, g, and b, respectively then its luminance is divers by the equation
    $$Y = 0.299r + 0.587g + 0.114b$$
  • Grayscale. converting a color to grayscale The RGB color model has the property that when all iii color intensities are the same, the resulting color is on a grayscale that ranges from black (all 0s) to white (all 255s). A simple way to convert a color to grayscale is to supervene upon the colour with a new 1 whose cerise, dark-green, and bluish values equal its luminance.
  • Color compatibility. The luminance value is too crucial in determining whether ii colors are uniform, in the sense that printing text in one of the colors on a background in the other color will be readable. A widely used rule of thumb is that the difference between the luminance of the foreground and background colors should be at least 128.
    color compatibility

Luminance.java is a static method library that we can use to convert to grayscale and test whether two colors are compatible.

Image processing.

anatomy of a digital image A digital image is a rectangular grid of pixels (picture elements), where the colour of each pixel is individually defined. Digital images are sometimes referred to as raster or bitmapped images. In contrast, the types of images that we produce with

StdDraw

(which involved geometric objects) are referred to as vector images.

The Picture data type allows you lot to manipulate digital images. The gear up of values is a 2-dimensional matrix of Color values, and the operations are what you might expect: create an image (either blank or from a file), set up the value of a pixel to a given color, and extract the color of a given pixel. The following API summarizes the available operations:

Picture API

Most prototype-processing programs are filters that scan through all of the pixels in a source image and then perform some computation to decide the colour of each pixel in a target image.

  • Grayscale. Grayscale.coffee converts an image from color to grayscale.
  • Scale. Scale.coffee takes the name of an prototype file and 2 integers (width w and acme h) as command-line arguments, scales the film to due west-by-h, and displays both images.
  • Fade result. Fade.java takes an integer n and the names of the source and target images every bit command-line arguments and fades from the source image to the target paradigm in due north steps. It uses a linear interpolation strategy, where each pixel in image i is a weighted average of the corresponding pixels in the source and target images.

Input and output revisited.

In Section 1.5 you learned how to read and write numbers and text using standard input, output, and drawing. These restrict the states to working with just one input file, one output file, and 1 cartoon for any given program. With object-oriented programming, nosotros consider data types that allow us to work with multiple input streams, output streams, and drawings inside one program.

  • Input stream data type. In is an object-oriented version of StdIn that supports reading numbers and text from data from files and websites as well as the standard input stream.
    In API
  • Output stream data type. Out is an object-oriented version of StdOut that supports press text to a variety of output streams, including files and standard output.
    Out API
  • File concatenation. True cat.java reads several files specified as control-line arguments, concatenates them, and prints the result to a file.
  • Screen scraping. StockQuote.java takes the the symbol of New York Stock Exchange stock as a command-line argument and prints its current trading price. It uses a technique known as screen scraping, in which the goal is to extract some data from a web page with a program. To report the current stock price of Google (NYSE symbol = GOOG), it reads the Web folio http://finance.yahoo.com/quote/GOOG. Then, information technology identifies the relevant information using indexOf() and substring().
  • Extracting data. Split.java uses multiple output streams to split a CSV file into separate files, one for each comma-delimited field.
  • Drawing data blazon. Draw is an object-oriented version of StdDraw that supporting drawing to more than 1 sail in the same plan.

Properties of reference types.

Nosotros summarize some of the essential properties of reference types.

  • Aliasing. An consignment statement with a reference type creates a second copy of the reference. The assignment argument does not create a new object, just some other reference to an existing object. This state of affairs is known as aliasing: both variables refer to the same object. As an example, consider the following code fragment:
    Picture a = new Movie("mandrill.jpg"); Movie b = a; a.set(col, row, color1);   // a updated b.ready(col, row, color2);   // a updated over again                

    Afterward the second assignment statement, variables a and b refer to the same Flick object.

  • Laissez passer by value. When y'all call a method with arguments, the effect in Coffee is equally if each argument were to appear on the correct-hand side of an assignment statement with the corresponding argument name on the left-hand side. That is, Coffee passes a copy of the argument value from the caller to the method. If the statement value is a primitive type, Coffee passes a re-create of that value; if the argument value is an object reference, Java passes a copy of the object reference. This arrangement is known as pass by value.
  • Arrays are objects. In Java, arrays are objects. Equally with strings, special language support is provided for certain operations on arrays: declarations, initialization, and indexing. Every bit with any other object, when we laissez passer an array to a method or use an array variable on the right-hand side of an assignment argument, we are making a copy of the array reference, not a re-create of the array.
  • Arrays of objects. When we create an array of objects, nosotros do and so in two steps:
    • Create the array by using new and the square bracket syntax for array creation.
    • Create each object in the array, by using new to call a constructor.

    For case, the following code creates an array of ii Color objects:

    Color[] a = new Color[2]; a[0] = new Color(255, 255, 0); a[i] = new Color(160, 82, 45);                
  • Safety pointers. In Java, there is only i mode to create a reference (with new) and only 1 way to manipulate that reference (with an assignment argument). Java references are known as safe pointers, because Coffee tin can guarantee that each reference points to an object of the specified type (and non to an arbitrary retentivity address).
  • Orphaned objects. The power to assign unlike objects to a reference variable creates the possibility that a program may take created an object that it can no longer reference. Such an object is said to exist orphaned. Equally an example, consider the following lawmaking fragment:
    Color a, b; a = new Colour(160, 82, 45);  // sienna b = new Colour(255, 255, 0);  // yellow b = a;                
    After the final assignment statement, not just do a and b refer to the aforementioned Color object (sienna), but likewise there is no longer a reference to the Colour object that was created and usedto initialize b (yellow).
  • Garbage drove. 1 of Java'south about significant features is its ability to automatically manage retentiveness. The thought is to costless the programmer from the responsibility of managing retentiveness past keeping track of orphaned objects and returning the memory they use to a pool of free retentivity. Reclaiming retentivity in this style is known as garbage collection, and Java's safety pointer policy enables information technology to do this efficiently.

Exercises

  1. Write a function contrary() that takes a cord equally an argument and returns a string that contains the same sequence of characters as the argument cord but in reverse order.

    Solution: ReverseString.java.

  2. Write a programme FlipX.java that takes the name of an paradigm file as a control-line argument and flips the image horizontally.
  3. Write a program ColorSeparation.coffee that takes the proper noun of an image file as a control-line argument, and creates and shows 3 Pic objects, one that contains but the cerise components, i for green, and one for bluish.
    baboon red baboon green baboon blue
  4. Write a static method isValidDNA() that takes a string as its argument and returns true if and only if it is composed entirely of the characters A, T, C, and G.

    Solution:

    public static boolean isValidDNA(String southward) {     for (int i = 0; i < s.length(); i++) {         char c = southward.charAt(i);         if (c != 'A' && c != 'T' && c != 'C' && c != '1000')             return false;     }                
  5. Write a office complementWatsonCrick() that takes a Dna string every bit its arguments and returns its Watson–Crick complement: replace A with T, C with Grand, and vice versa.

    Solution:

    public static String complementWatsonCrick(String southward) {     due south = s.replaceAll("A", "t");     s = s.replaceAll("T", "a");     s = s.replaceAll("C", "g");     south = south.replaceAll("M", "c");     render s.toUpperCase(); }                
  6. What does the following code fragment impress?
    Cord string1 = "hello"; String string2 = string1; string1 = "globe"; Arrangement.out.println(string2);                

    Solution: hello.

  7. What does the following lawmaking fragment impress?
    String southward = "Hello Earth"; s.toUpperCase(); s.substring(6, eleven); StdOut.println(s);                

    Solution: Hullo, World. String objects are immutable.

  8. A string s is a round shift of a string t if it matches when the characters of one cord are circularly shifted past some number of positions. For example, ACTGACG is a round shift of TGACGAC, and vice versa. Detecting this status is important in the report of genomic sequences. Write a function isCircularShift() that checks whether ii given strings south and t are circular shifts of i another.

    Solution:

    public boolean isCircularShift(String s, String t) {     String s2 = s + southward;     return s2.contains(t); }                
  9. What does the following recursive function return?
    public static String mystery(String s) {     int n = due south.length();     if (n <= one) return south;     Cord a = s.substring(0, n/2);     String b = s.substring(n/2, N);     return mystery(b) + mystery(a); }                

    Solution: the reverse of its argument string.

  10. Suppose that a[] and b[] are both integer arrays consisting of millions of integers. What does the follow code do, and how long does it take?
    int[] temp = a; a = b; b = temp;                

    Solution: Information technology swaps the arrays, only it does so by copying object references, so that it is not necessary to copy millions of values.

  11. Depict the effect of the following function.
    public void swap(Colour a, Colour b) {     Colour temp = a;     a = b;     b = temp; }                

    Solution: Information technology has no effect because Java passes object references by value.

Creative Exercises

  1. Kamasutra cipher. Write a filter KamasutraCipher.java that takes two strings as control-line statement (the cardinal strings), and then reads strings (separated by whitespace) from standard input, substitutes for each letter as specified by the key strings, and prints the result to standard output. This operation is the basis for one of the earliest known cryptographic systems. The status on the key strings is that they must be of equal length and that whatsoever letter in standard input must announced in exactly i of them. For example, if the two keys are THEQUICKBROWN and FXJMPSVLAZYDG, and then we make the table
    T H E Q U I C M B R O West N F X J Thou P S Five L A Z Y D G                
    which tells u.s.a. that we should substitute F for T, T for F, H for X, X for H, and and so along when filtering standard input to standard output. The message is encoded past replacing each letter with its pair. For instance, the bulletin See AT 11 is encoded as QJJF BF JKJCJG. The person receiving the message can use the same keys to go the message back.
  2. Colour report. Write a plan ColorStudy.java that displays the color study shown at right, which gives Albers squares respective to each of the 256 levels of blueish (bluish-to-white in row-major society) and grayness (black-to-white in column-major guild) that were used to impress this book.
    color study
  3. Tile. Write a program Tile.java that takes the name of an image file and 2 integers m and north equally command-line arguments and creates an 1000-by-due north tiling of the prototype.

    2-by-3 baboon

  4. Rotation filter. Write a program Rotation.java that takes 2 command-line arguments (the name of an image file and a real number \(\theta\)) and rotates the image \(\theta\)) degrees counterclockwise. To rotate, copy the color of each pixel \((s_i, s_j)\) in the source paradigm to a target pixel \((t_i, t_j)\) whose coordinates are given by the following formulas:
    $$ \begin{align} t_i \;&=\; (s_i - c_j) \cos \theta - (s_j - c_j) \sin \theta + c_j \\[1ex] t_j \;&=\; (s_i - c_j) \sin \theta + (s_j - c_j) \cos \theta + c_j \cease{align} $$
    where \((c_i, c_j)\) is the center of the paradigm.
  5. Swirl filter. Creating a swirl outcome is like to rotation, except that the angle changes as a office of distance to the center of the image. Use the same formulas as in the previous exercise, but compute \(\theta\) as a office of \((s_i, s_j)\), specifically \(\pi/256\) times the distance to the center.
  6. Wave filter. Write a filter Wave.coffee like those in the previous 2 exercises that creates a wave upshot, by copying the color of each pixel \((s_i, s_j)\) in the source epitome to a target pixel \((t_i, t_j)\), where
    $$ \begin{marshal} t_i \;&=\; s_i \\[1ex] t_j \;&=\; s_j + xx \sin(ii \pi s_j / 64) \end{align} $$
    Add lawmaking to accept the amplitude (20 in the accompanying figure) and the frequency (64 in the accompanying figure) every bit control-line arguments.
  7. Glass filter. Write a program Drinking glass.coffee that takes the proper noun of an image file as a command-line argument and applies a glass filter: prepare each pixel p to the color of a random neighboring pixel (whose pixel coordinates both differ from p'south coordinates by at most 5).
    digital zoom
  8. Digital zoom. Write a program Zoom.java that takes the name of an image file and three numbers south, 10, and y as command-line arguments, and shows an output image that zooms in on a portion of the input image. The numbers are all between 0 and one, with due south to be interpreted every bit a scale cistron and (x, y) as the relative coordinates of the betoken that is to be at the center of the output image. Use this program to zoom in on a relative or pet in some digital photo on your estimator.

Web Exercises (String Processing)

  1. Write a function that takes equally input a cord and returns the number of occurrences of the letter e.
  2. Give a one line Java code fragment to replace all periods in a cord with commas. Answer: s = south.supersede('.', ',').

    Don't use southward = s.replaceAll(".", ","). The replaceAll() method uses regular expressions where "."has a special significant.

  3. Replace all tabs with 4 spaces. Answer: s = s.replace("\t", "    ").
  4. Write a program that takes a command line input string s, reads strings from standard input, and prints the number of times due south appears. Hint: apply don't forget to use equals instead of == with references.
  5. Write a program that reads in the name of a month (three letter abridgement) as a control-line argument and prints the number of days in that month in a non leap year.
                        public static void principal(String[] args) {     String[] months = {         "Jan", "February", "Mar", "Apr", "May", "Jun",          "Jul", "Aug", "Sep", "Oct", "November", "Dec"     };     int[] days = {         31, 28, 31, 30, 31, 30,         31, 31, xxx, 31, thirty, 31     };     Cord name = args[0];     for (int i = 0; i < months.length; i++)        if (proper noun.equalsIgnoreCase(months[i]))           System.out.println(name + " has " + days[i] + " days"); }                
  6. Write a program Squeeze.coffee that takes as input a string and removes side by side spaces, leaving at most one space in-a-row.
  7. Which one or more of the post-obit converts all of the strings in the array a to upper case?
    for (int i = 0; i < a.length; i++) {    String s = a[i];    southward = s.toUpperCase(); }  for (int i = 0; i < a.length; i++) {    a[i].toUpperCase(); }  for (int i = 0; i < a.length; i++) {    a[i] = a[i].toUpperCase(); }                
    Answer: just the last 1.
  8. Describe the string that the following part returns, given a positive integer n?
    public static Cord mystery(int n) {    String s = "";    while (north > 0) {        if (n % ii == 1) s = south + s + "x";        else            s = due south + s;        n = n / 2;    }    return s; }                

    Solution The string of length northward consisting only of the graphic symbol ten.

  9. Write a function that takes a string s and an integer north and returns a new string t of length exactly due north that consists of due south (truncated if its length is greater than n) followed by a sequence of '-' characters (if the length of s is less than n).
  10. What does the following recursive office return, given two strings due south and t of the aforementioned length?
    public static String mystery(String due south, String t) {    int n = s.length();    if (n <= 1) render s + t;    String a = mystery(s.substring(0, north/two), t.substring(0, due north/2));    Cord b = mystery(south.substring(n/ii, north), t.substring(due north/2, northward));    return a + b; }                

    Solution: Perfect shuffle of the characters of s and t.

  11. Write a program that reads in a cord and prints the commencement character that appears exactly once in the cord. Ex: ABCDBADDAB -> C.
  12. Given a cord, create a new cord with all the consecutive duplicates removed. Ex: ABBCCCCCBBAB -> ABCBAB.
  13. Write a function that takes two string arguments due south and t, and returns the alphabetize of the start character in s that appears in ts (or -1 if no character in s appears in t).
  14. Given a string s, determine whether it represents the proper name of a web page. Assume that whatsoever cord starting with http:// is a web page.

    Solution: if (southward.startsWith("http://")).

  15. Given a string southward that represents the name of a spider web folio, intermission it up into pieces, where each piece is separated by a period, e.g., http://www.cs.princeton.edu should exist broken upwards into www, cs, princeton, and edu, with the http:// part removed. Use either the separate() or indexOf() methods.
  16. Given a string due south that represents the proper name of a file, write a lawmaking fragment to determine its file extension. The file extension is the substring post-obit the terminal period. For example, the file type of monalisa.jpg is jpg, and the file type of mona.lisa.png is png.

    Library solution: this solution is used in Motion picture.java to salvage an image to the file of the advisable type.

    Cord extension = south.substring(s.lastIndexOf('.') + 1);                
  17. Given a cord s that represents the proper noun of a file, write a code fragment to determine its directory portion. This is the prefix that ends with the concluding / grapheme (the directory delimiter); if in that location is no such /, so it is the empty string. For example, the directory portion of /Users/wayne/monalisa.jpg is /Users/wayne/.
  18. Given a cord south that represents the name of a file, write a code fragment to determine its base name (filename minus any directories). For /Users/wayne/monalisa.jpg, it is monalisa.jpg.
  19. Write a program that reads in text from standard input and prints it back out, replacing all single quotation marks with double quotation marks.
  20. Write a programme Paste.java that takes an capricious number of control line inputs and concatenates the corresponding lines of each file, and writes the results to standard output. (Typically each line in given file has the aforementioned length.) Counterpart of the plan Cat.java.
  21. What does the program LatinSquare.java print when N = 5?
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int i = 0; i < Due north; i++) {    for (int j = 0; j < N; j++) {       char c = alphabet.charAt((i + j) % N);       System.out.print(c + " ");    }    System.out.println(); }                

    A Latin square of guild N is an N-past-N array consisting of N different symbols, such that each symbol appears exactly in one case in each row and column. Latin squares are useful in statistical pattern and cryptography.

  22. What does the following lawmaking fragment impress?
    String s = "Hello Globe"; s.toUpperCase(); due south.substring(vi, 11); Arrangement.out.println(s);                

    Answer: Hello Globe. The methods toUpperCase and substring return the resulting strings, just the programme ignores these so due south is never inverse. To go it to impress WORLD, use s = s.toUpperCase() and south = southward.substring(6, 11).

  23. What happens when you lot execute the following code fragment?
    String s = null; int length = s.length();                

    Answer: you get a NullPointerException since s is nix and y'all are attempting to dereference it.

  24. What are the values of x and y later the two consignment statements below?
    int x = '-'-'-'; int y = '/'/'/';                
  25. What does the following statement do where c if of type char?
    System.out.println((c >= 'a' && c <= 'z') ||                    (c >= 'A' && c <= 'Z'));                
    Answer: prints true if c is an majuscule or lowercase alphabetic character, and false otherwise.
  26. Write an expression that tests whether or not a character represents one of the digits '0' through 'nine' without using whatever library functions.
    boolean isDigit = ('0' <= c && c <= 'nine');                
  27. Write a program WidthChecker.java that takes a control line parameter N, reads text from standard input, and prints to standard output all lines that are longer than N characters (including spaces).
  28. Write a program Hex2Decimal.java that converts from a hexadecimal string (using A-F for the digits 11-15) to decimal.
  29. wget. Write a programme Wget.coffee that takes the name of a URL as a control-line argument and saves the referenced file using the same filename.
  30. Capitalize. Write a programme Capitalize.java that reads in text from standard input and capitalizes each word (make get-go letter of the alphabet uppercase and make the remaining messages lowercase).
  31. Shannon'southward entropy experiment. Recreate Shannon's experiment on the entropy of the English linguistic communication past listing a number of messages in a judgement and prompting the user for the next symbol. Shannon concluded that there is approximately 1.1 bits of info per letter of the alphabet in the alphabet.
  32. Scrambled text. Some cerebral psychologists believe that people recognize words based on their shape.
    to a rscheearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht frist and lsat ltteer is at the rghit pclae. The rset can exist a toatl mses and you tin can sitll raed it wouthit porbelm. Tihs is bcuseae we do not raed ervey lteter past itslef but the wrod as a wlohe.
    Write a program that reads in text from standard input and prints the text dorsum out, but shuffles the internal letters in each word. Write and use a office scramble() that takes as input a cord and returns some other string with the internal letters in random order. Apply the shuffling algorithm in Shuffle.coffee for the shuffling part.
  33. Date format conversion. Write a program to read in a data of the form 2003-05-25 and convert it to 5/25/03.
  34. Frequency analysis of English text. Write a plan LetterFrequency.coffee that reads in text from standard input (due east.g., Moby Dick) and summate the fraction of times each of the 26 lowercase letters appears. Ignore uppercase messages, punctuation, whitespace, etc. in your assay. Use CharStdIn.java from Department 2.iv to read process the text file.
  35. Print longest word(s). Repeat the previous exercise, but print out all of the longest words if at that place is a necktie, say up to a maximum of x words. Use an assortment of strings to shop the current longest words.
  36. Test if ii files are equal. Write a program that takes the name of 2 text files as command line inputs and checks if their contents are identical.
  37. Parsing control-line options. Unix command line programs typically back up flags which configure the behavior of a program to produce different output, eastward.thousand., "wc -c". Write a program that takes any number of flags from the command line and runs whichever options the user specifies. To check options, employ something like if (south.equals("-v")).
  38. Capitalization. Write a programme Capitalizer.coffee that reads in text strings from standard input and modifies each one so that the first letter of the alphabet in each give-and-take is uppercase and all other messages are lowercase.
  39. Railfence transposition cipher. Write a program RailFenceEncoder.java that reads in text from standard input and prints the characters in the odd positions, followed by the even positions. For example, if the original message is "Attack at Dawn", then y'all should print out "Atc tDwtaka an". This is a crude grade of cryptography.
  40. Railfence transposition null. Write a plan RailFenceDecoder.java that reads in a message encoded using the railfence transposition zero and prints the original message by reversing the encryption procedure.
  41. Scytale cipher. The scytale cipher is one of the starting time cryptographic devices used for military purposes. (Come across The Code Book, p. 8 for a nice film.) It was used by the Spartans in the fifth century BCE. To scramble the text, y'all print out every kth character starting at the get-go, then every kth character starting at the second graphic symbol, and so forth. Write a pair of programs ScytaleEncoder.java and ScytaleDecoder.java that implement this encryption scheme.
  42. Impress longest give-and-take. Read a listing of words from standard input, and print out the longest word. Apply the length method.
  43. Subsequence. Given two strings s and t, write a program Subsequence.java that determines whether southward is a subsequence of t. That is, the letters of s should appear in the same lodge in t, but not necessarily contiguously. For example accag is a subsequence of taagcccaaccgg.
  44. Bible codes. Some religious zealots believe that the Torah contains hidden phrases that announced past reading every kth letter, and that such blueprint tin can exist used to notice the Ark of the Covenant, cure cancer, and predict the future. Results not based on scientific method and results accept been debunked by mathematicians and attributed to illicit data manipulation. Using the same methodology one can observe statistically similar patterns in a Hebrew translation of State of war and Peace.
  45. Word chain checker. Write a programme that reads in a list of words from the control line and prints true if they form a give-and-take chain and false otherwise. In a word chain, adjacent words must differ in exactly one letter, e.g., HEAL, Head, DEAD, DEED, DEER, BEER.
  46. Haiku detector. Write a program that reads in text from standard input and checks whether information technology forms a haiku. A haiku consists of three lines containing the right number of syllables (5, 7, and v, respectively). For the purpose of this trouble, define a syllable to be whatever contiguous sequence of consecutive vowels (a, east, i, o, u, or y). According to this rule, haiku has two syllables and purpose has three syllables. Of course, the 2d example is wrong since the e in purpose is silent.
  47. ISBN numbers. Write a program to cheque whether an ISBN number is valid. Think check digit. An ISBN number tin besides take hyphens inserted at arbitrary places.
  48. Longest mutual prefix. Write a function that takes ii input string s and t, and returns the longest common prefix of both strings. For instance, if southward = ACCTGAACTCCCCCC and t = ACCTAGGACCCCCC, then the longest common prefix is ACCT. Exist conscientious if due south and t outset with different letters, or if 1 is a prefix of the other.
  49. Longest complemented palindrome. In DNA sequence analysis, a complemented palindrome is a string equal to its reverse complement. Adenine (A) and Thymine (T) are complements, as are Cytosine (C) and Guanine (Yard). For example, ACGGT is a complement palindrome. Such sequences human activity equally transcription-binding sites and are associated with cistron distension and genetic instability. Given a text input of N characters, discover the longest complemented palindrome that is a substring of the text. For example, if the text is GACACGGTTTTA then the longest complemented palindrome is ACGGT. Hint: consider each letter of the alphabet as the middle of a possible palindrome of odd length, so consider each pair of letters as the eye of a possible palindrome of even length.
  50. Highest density C+G region. Given a DNA string s of A, C, T, G and a parameter L, observe a substring of s that contains the highest ratio of C + G characters amidst all substrings that take at to the lowest degree L characters.
  51. Substring of a round shifts. Write a function that takes 2 strings s and t, and returns true if southward is a substring of a circular string t, and false otherwise. For instance gactt is a substring of the circular string tgacgact.
  52. Deoxyribonucleic acid to protein. A protein is a large molecule (polymer) consisting of a sequence of amino acids (monomers). Some examples of proteins are: hemoglobin, hormones, antibodies, and ferritin. There are 20 different amino acids that occur in nature. Each amino acid is specified by iii DNA base pairs (A, C, Thou, or T). Write a plan to read in a poly peptide (specified by its base of operations pairs) and converts information technology into a sequence of amino acids. Use the post-obit table. For example, the amino acid Isoleucine (I) is encode by ATA, ATC, or ATT.

    Rosetta stone of life.

    TTT Phe    TCT Ser    TAT Tyr    TGT Cys TTC Phe    TCC Ser    TAC Tyr    TGC Cys TTA Leu    TCA Ser    TAA ter    TGA ter TTG Leu    TCG Ser    TAG ter    TGG Trp  CTT Leu    CCT Pro    Cat His    CGT Arg CTC Leu    CCC Pro    CAC His    CGC Arg CTA Leu    CCA Pro    CAA Gln    CGA Arg CTG Leu    CCG Pro    CAG Gln    CGG Arg  ATT Ile    Deed Thr    AAT Asn    AGT Ser ATC Ile    ACC Thr    AAC Asn    AGC Ser ATA Ile    ACA Thr    AAA Lys    AGA Arg ATG Met    ACG Thr    AAG Lys    AGG Arg  GTT Val    GCT Ala    GAT Asp    GGT Gly GTC Val    GCC Ala    GAC Asp    GGC Gly GTA Val    GCA Ala    GAA Glu    GGA Gly GTG Val    GCG Ala    GAG Glu    GGG Gly                
    Amino acrid Abbrev Abbrev Amino acrid Abbrev Abbrev
    Alanine ala A Lleucine leu 50
    Arginine arg R Lysine lys K
    Asparagine asn N Methionine met M
    Aspartic Acid asp D Phenylalanine phe F
    Cysteine cys C Proline pro P
    Glutamic Acrid glu E Serine ser S
    Glutamine gln Q Threonine thr T
    Glycine gly G Tryptophan trp W
    Histidine his H Tyrosine tyr Y
    Isoleucine ile I Valine val V
  53. Counter. Write a program that reads in a decimal string from the command line (eastward.g., 56789) and starts counting from that number (e.g., 56790, 56791, 56792). Do not assume that the input is a 32 or 64 bit integer, but rather an arbitrary precision integer. Implement the integer using a Cord (not an array).
  54. Arbitrary precision integer arithmetic. Write a plan that takes two decimal strings as inputs, and prints their sum. Use a cord to represent the integer.
  55. Boggle. The game of Boggle is played on a 4-by-four grid of characters. There are 16 dice, each with half-dozen letters on the them. Create a 4-by-4 grid, where each die appears in one of the cells at random, and each dice displays one of the 6 characters at random.
    FORIXB MOQABJ GURILW SETUPL CMPDAE ACITAO SLCRAE ROMASH NODESW HEFIYE ONUDTK TEVIGN ANEDVZ PINESH ABILYT GKYLEU                
  56. Generating cryptograms. A cryptogram is obtained by scrambling English language text by replacing each letter with some other letter. Write a program to generate a random permutation of the 26 letters and use this to map letters. Give case: Don't scramble punctuation or whitespace.
  57. Scrabble. Write a program to determine the longest legal Scrabble discussion that can be played? To be legal, the word must exist in The Official Tournament and Club Wordlist (TWL98), which consists of all 168,083 words between 2 and 15 letters in TWL98. The number of tiles representing each letter are given in the table below. In addition, at that place are two blanks which can exist used to represent any alphabetic character.
    a b c d  east f g h i j thou l m north o p q r s t u v w x y z - ix 2 2 4 12 2 3 2 9 1 1 4 2 6 viii two ane 6 four 6 iv 2 two 1 2 i 2                
  58. Soundex. The soundex algorithm is a method of encoding last names based on the way information technology sounds rather than the style information technology is spelled. Names that audio the same (e.g., SMITH and SMYTH) would accept the aforementioned soundex encoding. The soundex algorithm was originally invented to simplify demography taking. It is besides used by genealogists to cope with names with alternate spellings and by airline receptionists to avoid embarrassment when later trying to pronounce a customer'due south name.

    Write a program Soundex.java that reads in two lowercase strings every bit parameters, computes their soundex, and determines if they are equivalent. The algorithm works as follows:

    1. Keep the first letter of the string, but remove all vowels and the letters 'h', 'w', and 'y'.
    2. Assign digits to the remaining letter using the following rules:
      1:  B, F, P, 5 2:  C, Chiliad, J, M, Q, S, X, Z 3:  D, T 4:  50 5:  Yard, N 6:  R                    
    3. If two or more consecutive digits are the same, delete all of the duplicates.
    4. Convert the string to four characters: the start character is the start letter of the original string, the remaining three characters are the first three digits in the string. Pad the string with abaft 0's if at that place are not enough digits; truncate information technology if there are besides many digits.
  59. Longest give-and-take. Given a dictionary of words and a starting give-and-take due south, find the longest word that can be formed, starting at s, and inserting ane alphabetic character at a time such that each intermediate word is also in the dictionary. For example, if the starting discussion is cal, and so the following is a sequence of valid words coal, coral, choral, chorale. Reference.
  60. Phone words. Write a program PhoneWords.java that takes a seven digit string of digits as a command line input, reads in a list of words from standard input (e.g., the lexicon), and prints all 7-letter words (or three-letter words followed by iv-letter of the alphabet words) in the dictionary that can be formed using the standard phone rules, e.g., 266-7883 corresponds to compute.
    0:  No corresponding messages i:  No respective letters 2:  A B C 3:  D E F 4:  Thou H I 5:  J G L 6:  One thousand N O 7:  P Q R South eight:  T U 5 9:  West X Y Z                
  61. Rot13. Rot13 is a very unproblematic encryption scheme used on some Internet newsgroups to muffle potentially offensive postings. It works by cyclically shifting each lowercase or uppercase letter 13 positions. So, the alphabetic character 'a' is replaced by 'northward' and the letter 'n' is replaced by 'a'. For instance, the string "Encryption" is encoded as "Rapelcgvba." Write a program ROT13.coffee that reads in a String as a control line parameter and encodes it using Rot13.
  62. Longest Rot13 word. Write a program that reads in a dictionary of words into an assortment and determines the longest pair of words such that each is the Rot13 of the other, eastward.g., bumpily and unfiber.
  63. Thue-Morse weave. Recall the Thue-Morse sequence from Exercises in Section 2.iii. Write a program ThueMorse.java that reads in a command line input N and plots the N-by-N Thue-Morse weave in turtle graphics. Plot jail cell (i, j) black if the ith and jth bits in the Thue-Morse cord are different. Below are the Thue-Morse patterns for N = four, 8, and 16.

    Because of the mesmerizing non-regularity, for large N, your eyes may have a difficult time staying focused.

  64. Repetition words. Write a programme Repetition.java to read in a list of dictionary words and print out all words for which each letter of the alphabet appears exactly twice, e.g., intestines, antiperspirantes, appeases, arraigning, hotshots, arraigning, teammate, and so forth.
  65. Text twist. Write a program TextTwist.java that reads in a word from the command line and a lexicon of words from standard input, and prints all words of at least four letters that can exist formed past rearranging a subset of the letters in the input word. This forms the cadre of the game Text Twist. Hint: create a profile of the input word by counting the number of times each of the 26 messages appears. And then, for each dictionary word, create a like contour and check if each letter appears at least every bit many times in the input word as in the dictionary give-and-take.
  66. Word frequencies. Write a plan (or several programs and employ piping) that reads in a text file and prints a list of the words in decreasing order of frequency. Consider breaking it up into 5 pieces and utilise piping: read in text and print the words i per line in lowercase, sort to bring identical words together, remove duplicates and print count, sort by count.
  67. VIN numbers. A VIN number is a 17-character cord that uniquely identifies a motor vehicle. It also encodes the manufacturer and attributes of the vehicle. To guard against accidentally entering an wrong VIN number, the VIN number incorporates a check digit (the 9th character). Each letter and number is assigned a value between 0 and 9. The check digit is chosen and so to be the weighted sum of the values mod 11, using the symbol X if the remainder is 10.
    A B C D E F Thousand H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 half dozen seven 8 - 1 2 3 4 5 - seven - 9 ii 3 4 5 vi vii 8 ix  1st 2nd 3rd fourth fifth 6th 7th 8th 9th 10  xi  12  13  14  15  sixteen  17  8   seven   half dozen   5   iv   3   two  10   0   9   8   vii   6   5   four   3   two                

    For case the cheque digit of the fractional VIN number 1FA-CP45E-?-LF192944 is X because the weighted sum is 373 and 373 modern 11 is x.

                      one   F   A   C   P   four   5   E   X   Fifty   F   i   9   2   ix   4   4  1   vi   i   3   seven   4   5   five   -   3   vi   1   9   2   nine   4   4  viii   vii   six   v   4   iii   2  x   -   9   8   7   6   5   iv   3   2 ------------------------------------------------------------------  8  42   6  xv  28  12  10  50   -  27  48   7  54  ten  36  12   viii                

    Write a program VIN.java that takes a command line cord and determines whether or not it is a valid VIN number. Allow the input to be entered with upper or lower case, and allow dashes to be inserted. Exercise thorough error checking, e.grand., that the string is the right length, that no illegal characters are used (I, O, Q), etc.

  68. Music CDs. Screen-scrape MusicBrainz to identify data about music CDs.
  69. Sus scrofa Latin. Hog Latin is a fun surreptitious language for young children. To convert a word to Pig Latin:
    • If it begins with a vowel, append "hay" to the end. At the beginning of a give-and-take, treat y as a vowel unless it is followed past a vowel.
    • If it begins with a sequence of consonants, move the consonants to the end, then suspend "ay". Treat a u following a q equally a consonant.

    For example, "input" becomes "input-hay", "standard" becomes "andard-stay", "quit" becomes "it-quay". Write a plan PigLatinCoder.java that reads in a sequence of words from standard input and prints them to standard output in Grunter Latin. Write a program PigLatinDecoder.java that reads in a sequence of words encoded in Pig Latin from standard input and prints the original words out in.

  70. Rotating pulsate problem. Applications to pseudo-random number generators, computational biological science, coding theory. Consider a rotating pulsate (depict picture of circle divided into sixteen segments, each of one of two types - 0 and ane). Nosotros want that any sequence of 4 sequent segments to uniquely identify the quadrant of the drum. That is, every 4 sequent segments should represent one of the 16 binary numbers from 0000 to 1111. Is this possible? A de Bruijn sequence of guild north is a shortest (circular) string such that every sequence of n bits appears as a substring at least in one case. For example, 0000111101100101 is a de Bruijn sequence of order 4, and all 2^4 possible 4-bit sequence (0000, 0001, ..., 1111) occur exactly once. Write a program DeBruijn.java that reads in a command line parameter n and prints an order n de Bruijn sequence. Algorithm: outset with n 0's. Append a 1 if the north-tuple that would be formed has not already appeared in the sequence; append a 0 otherwise. Hint: apply the methods Cord.indexOf and String.substring.
  71. Ehrenfecucht-Mycielski sequence. The Ehrenfecucht-Mycielski sequence in a binary sequence that starts with "010". Given the kickoff n bits b0, b1, ..., bn-ane, bn is adamant past finding the longest suffix bj, bj+one, ..., bn-1 that occurs previously in the sequence (if it occurs multiple times, take the last such occurrence). Then, bn is the opposite of the bit that followed the match. 0100110101110001000011110110010100100111010001100000101101111100. Hint: Use the substring() and lastIndexOf() methods.

Spider web Exercises (Image Processing)

  1. Painter's and printer's color triangles. Create the following two images. The primary hues of the painter'southward triangle are red, green, and blue; the primary hues of the printer's triangle are magenta, cyan, and yellowish.
  2. Two-stroke apparent motion. Create the optical illusion of two-stroke credible motion or four-stroke
  3. De Valois' checkerboard. Create the optical illusion of De Valois' checkerboard or 1 of the other optical illusions from the Shapiro Perception Lab.
  4. Color spectrum. Write a program Spectrum.java that draws all ii^24 possible colors, by drawing for each red value a 256-by-256 array of color fries (i for each dark-green and blue value).
  5. Vertical flip. Write a program FlipY.coffee that reads in an paradigm and flips it vertically.
  6. Moving picture dimensions. Write a programme Dimension.java that accept the name of an image file as a command line input and prints its dimension (width-by-height).
  7. Anti-aliasing. Anti-aliasing is a method of removing artifacts from representing a shine curve with a discrete number of pixels. A very rough style of doing this (which as well blurs the image) is to convert an N-past-N grid of pixels into an (North-1)-by-(N-ane) by making each pixel be the average of four cells in the original image every bit below. Write a program AntiAlias that reads in an integer N, then an N-by-Due north assortment of integers, and prints the anti-aliased version. Reference.
  8. Thresholding. Write a plan Threshold.coffee that reads in a grayscale version of a black-and-white picture, creates and plots a histogram of 256 grayscale intensities, and determines the threshold value for which pixels are black, and which are white.
  9. Mirror prototype. Read in a W-past-H film and produce a 2W-by-H movie which concatenates the original Due west-past-H pic with the mirror epitome of the W-by-H motion picture. Repeat by mirror around the y-axis. Or create a W-past-H moving picture, but mirror around the center, deleting half the film.
  10. Linear filters. A box filter or mean filter replaces the color of pixel (x, y) by the average of its ix neighboring pixels (including itself). The matrix [1 1 1; ane 1 1; 1 1 1] / 9 is called the convolution kernel. The kernel is the gear up of pixels to be averaged together. Program MeanFilter.java implements a mean filter using the Picture data type.
  11. Mistiness filter. Use low-laissez passer 3-by-3 uniform filter [i/thirteen 1/13 1/13; ane/thirteen 5/thirteen 1/xiii; 1/13, 1/xiii, 1/13].
  12. Emboss filter. Use prewitt masks [-1 0 1; -ane 1 1; -one 0 1] (east) or [1 0 -1; ii 0 -ii; 1 0 -ane], [-1 -i 0; -one ane one; 0 1 1] (s-east),
  13. Sharpen filter. Psychophysical experiments suggest that a photograph with crisper edges is more aesthetically pleasing than verbal photographic reproduction. Use a high-laissez passer iii-by-3 filter. Light pixels near dark pixels are made lighter; dark pixels near light pixels are fabricated darker. Laplace kernel. Attempts to capture region where second derivative is naught. [-1 -1 -1; -1 8 -one; -ane -1 -one]
  14. Oil painting filter. Prepare pixel (i, j) to the color of the most frequent value amongst pixels with Manhattan altitude W of (i, j) in the original epitome.
  15. Luminance and chrominance. Decompose a picture show using the YIQ color space: Y (luma) = 0.299 r + 0.587 thou + 0.114 b, I (in-phase) = 0.596 r - 0.274 g - 0.322 b, and Q (quadrature) = 0.211 r - 0.523 thou + 0.312 b. Plot all 3 images. The YIQ color space is used by NTSC color Tv set organization.
  16. Brighten. Write a plan Brighter.java that takes a command line argument which is the name of a JPG or PNG file, displays it in a window, and display a 2d version which is a brighter copy. Use the Color method brighter(), which return a brighter version of the invoking colour.
  17. Edge detection. Goal: form mathematical model of some feature of the image. To accomplish this, we want to notice edges or lines. An edge is a area of a flick with a strong contrast in intensity from 1 pixel to the adjacent. Edge detection is a fundamental trouble in image processing and estimator vision. The Sobel method is a popular edge detection technique. We assume that the image is grayscale. (If not, we can catechumen past taking the boilerplate of the blood-red, green, and bluish intensities.) For each pixel (i, j) we calculate the edge strength by calculating two 3-past-3 convolution masks. This involves taking the grayscale values of the 9 pixels in the 3-by-3 neighborhood centered on (i, j), multiplying them by the corresponding weight in the 3-past-3 mask, and summing up the products.
    -i 0 +1      +one +two +1 -2 0 +2       0  0  0 -one 0 +i      -one -two -1                
    This produces ii values Gx and Gy. In the output moving picture, nosotros color the pixel (i, j) co-ordinate to the grayscale value 255 - Sqrt(Gx*Gx + Gy*Gy). There are various ways to handle the boundary. For simplicity, we ignore this special case and colour the boundary pixels black. Program EdgeDetector.java takes the proper noun of an prototype as a command line input and applies the Sobel edge detection algorithm to that image.

What Is A Data Type In Java,

Source: https://introcs.cs.princeton.edu/31datatype

Posted by: brownthabould.blogspot.com

0 Response to "What Is A Data Type In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel