JAVA NUMBERS, CHARS AND STRINGS
|
|
|
- Gavin Washington
- 9 years ago
- Views:
Transcription
1 JAVA NUMBERS, CHARS AND STRINGS It turned out that all Workstation in the classroom are NOT set equally. This is why I wil demonstrate all examples using an on-line web tool Please consider using this tool as an alternative to your NetBeans. NUMBERS AS OBJECTS Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc. Example: int i = 5000; float gpa = 13.65; byte mask = 0xaf; However, in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes for each primitive data type. All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number: This wrapping is taken care of by the compiler, the process is called boxing. So when a primitive is used when an object is required, the compiler boxes the primitive type in its wrapper class. Similarly, the compiler unboxes the object to a primitive as well. The Number is part of the java.lang package. Example: class Integer For example, an object of type Integer contains a field whose type is int. Namely, it contains the following fields: static int MAX_VALUE -- This is a constant holding the maximum value an int can have,
2 static int MIN_VALUE -- This is a constant holding the minimum value an int can have, static int SIZE -- This is the number of bits used to represent an int value in two's complement binary form. static Class<Integer> TYPE -- This is the class instance representing the primitive type int. Also, it contains two constructors: Integer(int value) This constructs a newly allocated Integer object that represents the specified int value. Integer(String s) This constructs a newly allocated Integer object that represents the int value indicated by the String parameter. and a number of class methods like static int bitcount(int i) This method returns the number of one-bits in the two's complement binary representation of the specified int value. byte bytevalue() This method returns the value of this Integer as a byte. int compareto(integer anotherinteger) This method compares two Integer objects numerically. static Integer decode(string nm) This method decodes a String into an Integer. double doublevalue() This method returns the value of this Integer as a double. boolean equals(object obj) This method compares this object to the specified object. static Integer getinteger(string nm) This method determines the integer value of the system property with the specified name. int hashcode() This method returns a hash code for this Integer. static int highestonebit(int i) This method returns an int value with at most a single one-bit, in the position of the highest-order ("leftmost") one-bit in the specified int value. static int lowestonebit(int i) This method returns an int value with at most a single one-bit, in the position of the lowest-order ("rightmost") one-bit in the specified int value. static int numberofleadingzeros(int i) This method returns the number of zero bits preceding the highestorder ("leftmost") one-bit in the two's complement binary representation of the specified int value. static int parseint(string s) This method parses the string argument as a signed decimal integer. static int signum(int i) This method returns the signum function of the specified int value. static String tobinarystring(int i) This method returns a string representation of the integer argument as an unsigned integer in base 2. static String tohexstring(int i) This method returns a string representation of the integer argument as an unsigned integer in base 16.
3 static String tooctalstring(int i) This method returns a string representation of the integer argument as an unsigned integer in base 8. static String tostring(int i) This method returns a String object representing the specified integer. static String tostring(int i, int radix) This method returns a string representation of the first argument in the radix specified by the second argument. static Integer valueof(string s) This method returns an Integer object holding the value of the specified String. (etc.) Here is an example of boxing and unboxing: Integer x = 5; // boxes int to an Integer object x = x + 10; // unboxes the Integer to a int System.out.println(x); This would produce the following result: 15 When x is assigned integer values, the compiler boxes the integer because x is integer objects. Later, x is unboxed so that they can be added as integers. NUMBER METHODS Here is the list of the instance methods that all the subclasses of the Number class implement: xxxvalue() Converts the value of this Number object to the xxx data type and returns it. E.g.: byte bytevalue() short shortvalue() int intvalue() long longvalue() float floatvalue() double doublevalue() EXAMPLE Integer x = 5; // Returns byte primitive data type System.out.println( x.bytevalue() );
4 // Returns double primitive data type System.out.println(x.doubleValue()); // Returns long primitive data type System.out.println( x.longvalue() ); Output is as follows: compareto() Compares this Number object to the argument. Return value is: If the Integer is equal to the argument then 0 is returned. If the Integer is less than the argument then -1 is returned. If the Integer is greater than the argument then 1 is returned. Integer x = 5; System.out.println(x.compareTo(3)); System.out.println(x.compareTo(5)); System.out.println(x.compareTo(8)); equals() Determines whether this number object is equal to the argument. The methods returns True if the argument is not null and is an object of the same type and with the same numeric value. (There are some extra requirements for Double and Float objects that are described in the Java API documentation.)
5 Integer x = 5; Integer y = 10; Integer z =5; Short a = 5; System.out.println(x.equals(y)); System.out.println(x.equals(z)); System.out.println(x.equals(a)); valueof() false true false All the variants of this method are given below: static Integer valueof(int i) static Integer valueof(string s) static Integer valueof(string s, int radix) Where parameters are: i -- An int for which Integer representation would be returned. s -- A String for which Integer representation would be returned. radix -- This would be used to decide the value of returned Integer based on passed String. For these three representations, return values are: valueof(int i): This returns an Integer object holding the value of the specified primitive. valueof(string s): This returns an Integer object holding the value of the specified string representation. valueof(string s, int radix): This returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix. EXAMPLE Integer x =Integer.valueOf(9); Double c = Double.valueOf(5); Float a = Float.valueOf("80"); Integer b = Integer.valueOf("444",16);
6 System.out.println(x); System.out.println(c); System.out.println(a); System.out.println(b); tostring() The method is used to get a String object representing the value of the Number Object. If the method takes two arguments, then a String representation of the first argument in the radix specified by the second argument will be returned. Return values are: tostring(): This returns a String object representing the value of this Integer. tostring(int i): This returns a String object representing the specified integer. Integer x = 5; System.out.println(x.toString()); System.out.println(Integer.toString(12)); 5 12 parseint() This method is used to get the primitive data type of a certain String. Return values are: parseint(string s): This returns an integer (decimal only). parseint(int i): This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
7 int x =Integer.parseInt("9"); double c = Double.parseDouble("5"); int b = Integer.parseInt("444",16); System.out.println(x); System.out.println(c); System.out.println(b); abs() Returns the absolute value of the argument. ceil() Returns the smallest integer that is greater than or equal to the argument. Returned as a double. floor() Returns the largest integer that is less than or equal to the argument. Returned as a double. rint() Returns the integer that is closest in value to the argument. Returned as a double. round() Returns the closest long or int, as indicated by the method's return type, to the argument. double d = ; double e = ; float f = 100; float g = 90f; System.out.println(Math.round(d)); System.out.println(Math.round(e)); System.out.println(Math.round(f));
8 System.out.println(Math.round(g)); min() Returns the smaller of the two arguments. max() Returns the larger of the two arguments. exp() Returns the base of the natural logarithms, e, to the power of the argument. log() Returns the natural logarithm of the argument. pow() Returns the value of the first argument raised to the power of the second argument. sqrt() Returns the square root of the argument. sin() Returns the sine of the specified double value. cos() Returns the cosine of the specified double value. tan() Returns the tangent of the specified double value. asin() Returns the arcsine of the specified double value.
9 acos() Returns the arccosine of the specified double value. atan() Returns the arctangent of the specified double value. atan2() Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta. double x = 45.0; double y = 30.0; System.out.println( Math.atan2(x, y) ); todegrees() Converts the argument to degrees toradians() Converts the argument to radians. random() Returns a random number. CHARS AS OBJECTS Normally, when we work with characters, we use primitive data types char. char ch = 'a'; // Unicode for uppercase Greek omega character char unichar = '\u039a';
10 // an array of chars char[] chararray ={ 'a', 'b', 'c', 'd', 'e' ; However in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper class Character for primitive data type char. The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor: Character ch = new Character('a'); The Java compiler will also create a Character object for you under some circumstances. For example, if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes the other way. // Here following primitive char 'a' // is boxed into the Character object ch Character ch = 'a'; // Here primitive 'x' is boxed 1 for method test, // return is unboxed to char 'c' char c = test('x'); Escape Sequences: A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The newline character (\n) is used frequently in System.out.println() statements to advance to the next line after the string is printed. Following table shows the Java escape sequences: \t Inserts a tab in the text at this point. \b Inserts a backspace in the text at this point. \n Inserts a newline in the text at this point. \r Inserts a carriage return in the text at this point. \f Inserts a form feed in the text at this point. \' Inserts a single quote character in the text at this point. \" Inserts a double quote character in the text at this point. \\ Inserts a backslash character in the text at this point. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. If you want to put quotes within quotes, you must use the escape sequence, \", on the interior quotes: 1 ) i.e. converted into class
11 public class Test { public static void main(string args[]) { System.out.println("She said \"Hello!\" to me."); This would produce the following result: She said "Hello!" to me. CHARACTER METHODS Here is the list of the important instance methods that all the subclasses of the Character class implement: isletter() Determines whether the specified char value is a letter. isdigit() Determines whether the specified char value is a digit. iswhitespace() Determines whether the specified char value is white space. isuppercase() Determines whether the specified char value is uppercase. islowercase() Determines whether the specified char is lowercase. touppercase() Returns the uppercase form of the specified char value. tolowercase() Returns the lowercase form of the specified char value. tostring() Returns a String object representing the specified character valuethat is, a one-character string.
12 REGULAR EXPRESSIONS In computing, a regular expression (abbreviated regex or regexp) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations. A very simple use of a regular expression would be to locate the same word spelled two different ways in a text editor, for example seriali[sz]e. A wildcard match can also achieve this, but wildcard matches differ from regular expressions in that wildcards are limited to what they can pattern (having fewer metacharacters and a simple language-base), whereas regular expressions are not. STRING CLASS Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. Creating Strings: The most direct way to create a string is to write: String greeting = "Hello world!"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters. public class StringDemo{ char[] helloarray = { 'h', 'e', 'l', 'l', 'o', '.'; String hellostring = new String(helloArray); System.out.println( hellostring ); This would produce the following result: hello. Important! The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.
13 String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17: public class StringDemo { public static void main(string args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); This would produce the following result: String Length is : 17 Concatenating Strings The String class includes a method for concatenating two strings: string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in: "My name is ".concat("zara"); Strings are more commonly concatenated with the + operator, as in: which results in: "Hello," + " world" + "!" "Hello, world!" Let us look at the following example: public class StringDemo { public static void main(string args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); This would produce the following result:
14 Dot saw I was Tod Creating Format Strings You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of: you can write: System.out.printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatvar, intvar, stringvar); String fs; fs = String.format("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatvar, intvar, stringvar); System.out.println(fs); STRING METHODS Here is the list of some (not all!) methods supported by String class: char charat(int index) Returns the character at the specified index. public class Test { public static void main(string args[]) { String s = "Strings are immutable"; char result = s.charat(8); System.out.println(result); a int compareto(object o)
15 Compares this String to another Object. The return value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string. public class Test { public static void main(string args[]) { String str1 = "Strings are immutable"; String str2 = "Strings are immutable"; String str3 = "Integers are not immutable"; int result = str1.compareto( str2 ); System.out.println(result); result = str2.compareto( str3 ); System.out.println(result); result = str3.compareto( str1 ); System.out.println(result); int compareto(string anotherstring) Compares two strings lexicographically. int comparetoignorecase(string str) Compares two strings lexicographically, ignoring case differences. String concat(string str) Concatenates the specified string to the end of this string. boolean contentequals(stringbuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. static String copyvalueof(char[] data) Returns a String that represents the character sequence in the array specified. static String copyvalueof(char[] data, int offset, int count)
16 Returns a String that represents the character sequence in the array specified. boolean endswith(string suffix) Tests if this string ends with the specified suffix. boolean equals(object anobject) Compares this string to the specified object. boolean equalsignorecase(string anotherstring) Compares this String to another String, ignoring case considerations. byte getbytes() byte[] getbytes(string charsetname) Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. import java.io.*; String Str1 = new String("Welcome to Tutorialspoint.com"); try{ byte[] Str2 = Str1.getBytes(); System.out.println("Returned Value " + Str2 ); Str2 = Str1.getBytes( "UTF-8" ); System.out.println("Returned Value " + Str2 ); Str2 = Str1.getBytes( "ISO " ); System.out.println("Returned Value " + Str2 ); catch( UnsupportedEncodingException e){ System.out.println("Unsupported character set"); Returned Value [B@192d342 Returned Value [B@15ff48b Returned Value [B@1b90b39
17 void getchars(int srcbegin, int srcend, char[] dst, int dstbegin) Copies characters from this string into the destination character array. Here is the detail of parameters: srcbegin -- index of the first character in the string to copy. srcend -- index after the last character in the string to copy. dst -- the destination array. dstbegin -- the start offset in the destination array. It does not return any value but on error it throws IndexOutOfBoundsException. EXAMPLE 1 import java.io.*; String Str1 = new String("Welcome to Tutorialspoint.com"); char[] Str2 = new char[7]; try{ // this catches possible errors Str1.getChars(2, 9, Str2, 0); System.out.print("Copied Value = " ); System.out.println(Str2 ); catch( Exception ex){ //on error continues here System.out.println("Raised exception..."); Copied Value = lcome t EXAMPLE 2 Now, consider very similar case, but with errorneous parameter dstbegin: import java.io.*; String Str1 = new String("Welcome to Tutorialspoint.com"); char[] Str2 = new char[7]; try{ // this catches possible errors Str1.getChars(2, 9, Str2, 100); System.out.print("Copied Value = " ); System.out.println(Str2 );
18 catch( Exception ex){ //on error continues here System.out.println("Raised exception..."); Raised exception... int hashcode() Returns a hash code for this string. The hash code for a String object is computed as: s[0]*31^(n-1) + s[1]*31^(n-2) s[n-1] Using int arithmetic, where s[i] is the i-th character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) int indexof(int ch) int indexof(int ch, int fromindex) int indexof(string str) int indexof(string str, int fromindex) Returns the index within this string of the first occurrence of the specified substring. This method has following different variants: public int indexof(int ch): Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur. public int indexof(int ch, int fromindex): Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index or -1 if the character does not occur. int indexof(string str): Returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned. int indexof(string str, int fromindex): Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned. import java.io.*; public class Test { public static void main(string args[]) { String Str = new String("Welcome to Tutorialspoint.com"); String SubStr1 = new String("Tutorials"); String SubStr2 = new String("Sutorials"); System.out.print("Found Index :" );
19 System.out.println(Str.indexOf( 'o' )); System.out.print("Found Index :" ); System.out.println(Str.indexOf( 'o', 5 )); System.out.print("Found Index :" ); System.out.println( Str.indexOf( SubStr1 )); System.out.print("Found Index :" ); System.out.println( Str.indexOf( SubStr1, 15 )); System.out.print("Found Index :" ); System.out.println(Str.indexOf( SubStr2 )); Found Index :4 Found Index :9 Found Index :11 Found Index :-1 Found Index :-1 int lastindexof(int ch) int lastindexof(int ch, int fromindex) int lastindexof(string str) int lastindexof(string str, int fromindex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. int length() Returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string. boolean matches(string regex) Tells whether or not this string matches the given regular expression. boolean regionmatches(boolean ignorecase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal. Here is the detail of parameters: toffset -- the starting offset of the subregion in this string. other -- the string argument. ooffset -- the starting offset of the subregion in the string argument. len -- the number of characters to compare. ignorecase -- if true, ignore case when comparing characters.
20 Return value is true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignorecase argument. EXAMPLE import java.io.*; String Str1 = new String("Welcome to Tutorialspoint.com"); String Str2 = new String("Tutorials"); String Str3 = new String("TUTORIALS"); System.out.print("Return Value :" ); System.out.println(Str1.regionMatches(11, Str2, 0, 9)); System.out.print("Return Value :" ); System.out.println(Str1.regionMatches(11, Str3, 0, 9)); System.out.print("Return Value :" ); System.out.println(Str1.regionMatches(true, 11, Str3, 0, 9)); Return Value :true Return Value :false Return Value :true String replace(char oldchar, char newchar) Returns a new string resulting from replacing all occurrences of oldchar in this string with newchar. String replaceall(string regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement. String replacefirst(string regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement. String[] split(string regex) Splits this string around matches of the given regular expression. String[] split(string regex, int limit)
21 Splits this string around matches of the given regular expression. boolean startswith(string prefix) Tests if this string starts with the specified prefix. boolean startswith(string prefix, int toffset) Tests if this string starts with the specified prefix beginning a specified index. CharSequence subsequence(int beginindex, int endindex) Returns a new character sequence that is a subsequence of this sequence. String substring(int beginindex) Returns a new string that is a substring of this string. String substring(int beginindex, int endindex) Returns a new string that is a substring of this string. char[] tochararray() Converts this string to a new character array. String tolowercase() Converts all of the characters in this String to lower case using the rules of the default locale. String tolowercase(locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale. String tostring() This object (which is already a string!) is itself returned. String touppercase() Converts all of the characters in this String to upper case using the rules of the default locale. String touppercase(locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale. String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
22 static String valueof(primitive data type x) This method has followings variants, which depend on the passed parameters. This method returns the string representation of the passed argument. valueof(boolean b): Returns the string representation of the boolean argument. valueof(char c): Returns the string representation of the char argument. valueof(char[] data): Returns the string representation of the char array argument. valueof(char[] data, int offset, int count): Returns the string representation of a specific subarray of the char array argument. valueof(double d): Returns the string representation of the double argument. valueof(float f): Returns the string representation of the float argument. valueof(int i): Returns the string representation of the int argument. valueof(long l): Returns the string representation of the long argument. valueof(object obj): Returns the string representation of the Object argument. EXAMPLE import java.io.*; double d = ; boolean b = true; long l = ; char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' ; System.out.println("Return Value : " + String.valueOf(d) ); System.out.println("Return Value : " + String.valueOf(b) ); System.out.println("Return Value : " + String.valueOf(l) ); System.out.println("Return Value : " + String.valueOf(arr) ); Return Value : E8 Return Value : true Return Value : Return Value : abcdefg
JAVA TUTORIAL. Simply Easy Learning by tutorialspoint.com. tutorialspoint.com
Java Tutorial JAVA TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com ABOUT THE TUTORIAL Java Tutorial Java is a high-level programming language originally developed by Sun Microsystems
CS106A, Stanford Handout #38. Strings and Chars
CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars The char type (pronounced "car") represents a single character. A char literal value can be written in the code using single quotes
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]
Pemrograman Dasar. Basic Elements Of Java
Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle
Text Processing In Java: Characters and Strings
Text Processing In Java: Characters and Strings Wellesley College CS230 Lecture 03 Monday, February 5 Handout #10 (Revised Friday, February 9) Reading: Downey: Chapter 7 Problem Set: Assignment #1 due
java Features Version April 19, 2013 by Thorsten Kracht
java Features Version April 19, 2013 by Thorsten Kracht Contents 1 Introduction 2 1.1 Hello World................................................ 2 2 Variables, Types 3 3 Input/Output 4 3.1 Standard I/O................................................
Lecture 5: Java Fundamentals III
Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd
Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
Variables, Constants, and Data Types
Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight
Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.
1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays
public static void main(string[] args) { System.out.println("hello, world"); } }
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
Java Programming Fundamentals
Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few
CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.
http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral
Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.
Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input
java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner
java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources
CS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper
Introduction to Java. CS 3: Computer Programming in Java
Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods
Java CPD (I) Frans Coenen Department of Computer Science
Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials
UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming
UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything
AP Computer Science Java Subset
APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall
The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0
The following applies to all exams: Once exam vouchers are purchased you have up to one year from the date of purchase to use it. Each voucher is valid for one exam and may only be used at an Authorized
Overview. java.math.biginteger, java.math.bigdecimal. Definition: objects are everything but primitives The eight primitive data type in Java
Data Types The objects about which computer programs compute is data. We often think first of integers. Underneath it all, the primary unit of data a machine has is a chunks of bits the size of a word.
Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.
Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6 Handout 3 Strings and String Class. Input/Output with JOptionPane. Strings In Java strings are represented with a class type String. Examples:
Computer Programming I
Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,
Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:
Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of
Chapter 2 Introduction to Java programming
Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break
Quick Introduction to Java
Quick Introduction to Java Dr. Chris Bourke Department of Computer Science & Engineering University of Nebraska Lincoln Lincoln, NE 68588, USA Email: [email protected] 2015/10/30 20:02:28 Abstract These
Contents. 9-1 Copyright (c) 1999-2004 N. Afshartous
Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to
Introduction to Java Lecture Notes. Ryan Dougherty [email protected]
1 Introduction to Java Lecture Notes Ryan Dougherty [email protected] Table of Contents 1 Versions....................................................................... 2 2 Introduction...................................................................
First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
Chapter 2: Elements of Java
Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction
J a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C
Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in
Object-Oriented Programming in Java
CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio
Number Representation
Number Representation CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Topics to be Discussed How are numeric data
C++ Language Tutorial
cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain
Java Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
1 of 1 24/05/2013 10:23 AM
?Init=Y 1 of 1 24/05/2013 10:23 AM 1. Which of the following correctly defines a queue? a list of elements with a first in last out order. a list of elements with a first in first out order. (*) something
Package java.net. Interfaces. Classes. Exceptions. Package java.net Page 1 of 1. All Packages
Package java.net Page 1 of 1 Package java.net All Packages Interfaces ContentHandlerFactory FileMap SocketImplFactory URLStreamHandlerFactory Classes ContentHandler DatagramPacket DatagramSocket DatagramSocketImpl
Chapter 5 Functions. Introducing Functions
Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name
Introduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
.NET Standard DateTime Format Strings
.NET Standard DateTime Format Strings Specifier Name Description d Short date pattern Represents a custom DateTime format string defined by the current ShortDatePattern property. D Long date pattern Represents
Example of a Java program
Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);
Exercise 4 Learning Python language fundamentals
Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also
Week 1: Review of Java Programming Basics
Week 1: Review of Java Programming Basics Sources: Chapter 2 in Supplementary Book (Murach s Java Programming) Appendix A in Textbook (Carrano) Slide 1 Outline Objectives A simple Java Program Data-types
Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output
Chapter 2 Console Input and Output System.out.println for console output System.out is an object that is part of the Java language println is a method invoked dby the System.out object that can be used
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,
Expense Management. Configuration and Use of the Expense Management Module of Xpert.NET
Expense Management Configuration and Use of the Expense Management Module of Xpert.NET Table of Contents 1 Introduction 3 1.1 Purpose of the Document.............................. 3 1.2 Addressees of the
Java Basics: Data Types, Variables, and Loops
Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables
Ecma/TC39/2013/NN. 4 th Draft ECMA-XXX. 1 st Edition / July 2013. The JSON Data Interchange Format. Reference number ECMA-123:2009
Ecma/TC39/2013/NN 4 th Draft ECMA-XXX 1 st Edition / July 2013 The JSON Data Interchange Format Reference number ECMA-123:2009 Ecma International 2009 COPYRIGHT PROTECTED DOCUMENT Ecma International 2013
Primitive data types in Java
Unit 4 Primitive data types in Java Summary Representation of numbers in Java: the primitive numeric data types int, long, short, byte, float, double Set of values that can be represented, and operations
INPUT AND OUTPUT STREAMS
INPUT AND OUTPUT The Java Platform supports different kinds of information sources and information sinks. A program may get data from an information source which may be a file on disk, a network connection,
Explain the relationship between a class and an object. Which is general and which is specific?
A.1.1 What is the Java Virtual Machine? Is it hardware or software? How does its role differ from that of the Java compiler? The Java Virtual Machine (JVM) is software that simulates the execution of a
VB.NET - STRINGS. By calling a formatting method to convert a value or object to its string representation
http://www.tutorialspoint.com/vb.net/vb.net_strings.htm VB.NET - STRINGS Copyright tutorialspoint.com In VB.Net, you can use strings as array of characters, however, more common practice is to use the
Chapter 3. Input and output. 3.1 The System class
Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use
CS 111 Classes I 1. Software Organization View to this point:
CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects
Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:
Numeral Systems Which number is larger? 25 8 We need to distinguish between numbers and the symbols that represent them, called numerals. The number 25 is larger than 8, but the numeral 8 above is larger
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.
Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java
Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)
Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating
Programming Languages CIS 443
Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception
5 Arrays and Pointers
5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of
SOME EXCEL FORMULAS AND FUNCTIONS
SOME EXCEL FORMULAS AND FUNCTIONS About calculation operators Operators specify the type of calculation that you want to perform on the elements of a formula. Microsoft Excel includes four different types
Python Lists and Loops
WEEK THREE Python Lists and Loops You ve made it to Week 3, well done! Most programs need to keep track of a list (or collection) of things (e.g. names) at one time or another, and this week we ll show
Unit 6. Loop statements
Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now
grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print
grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print In the simplest terms, grep (global regular expression print) will search input
Eryq (Erik Dorfman) Zeegee Software Inc. [email protected]. A Crash Course in Java 1
A Crash Course in Java Eryq (Erik Dorfman) Zeegee Software Inc. [email protected] 1 Because without text, life would be nothing but 6E 75 6D 62 65 72 73 2 java.lang.string Not a primitive type, but it is
Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html
CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Farris Engineering Center 319 8/19/2015 Install
1.1 Your First Program
Why Programming? 1.1 Your First Program Why programming? Need to tell computer what you want it to do. Naive ideal. Natural language instructions. Please simulate the motion of N heavenly bodies, subject
JAVA IN A NUTSHELL O'REILLY. David Flanagan. Fifth Edition. Beijing Cambridge Farnham Köln Sebastopol Tokyo
JAVA 1i IN A NUTSHELL Fifth Edition David Flanagan O'REILLY Beijing Cambridge Farnham Köln Sebastopol Tokyo Table of Contents Preface xvii Part 1. Introducing Java 1. Introduction 1 What 1s Java? 1 The
AIMMS Function Reference - Arithmetic Functions
AIMMS Function Reference - Arithmetic Functions This file contains only one chapter of the book. For a free download of the complete book in pdf format, please visit www.aimms.com Aimms 3.13 Part I Function
COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005. Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19
Term Test #2 COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005 Family Name: Given Name(s): Student Number: Question Out of Mark A Total 16 B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 C-1 4
Web Programming Step by Step
Web Programming Step by Step Lecture 13 Introduction to JavaScript Reading: 7.1-7.4 Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp and Jessica Miller. Client-side
Chapter 2 Basics of Scanning and Conventional Programming in Java
Chapter 2 Basics of Scanning and Conventional Programming in Java In this chapter, we will introduce you to an initial set of Java features, the equivalent of which you should have seen in your CS-1 class;
CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java
CS1020 Data Structures and Algorithms I Lecture Note #1 Introduction to Java Objectives Java Basic Java features C Java Translate C programs in CS1010 into Java programs 2 References Chapter 1 Section
Chapter 4: Computer Codes
Slide 1/30 Learning Objectives In this chapter you will learn about: Computer data Computer codes: representation of data in binary Most commonly used computer codes Collating sequence 36 Slide 2/30 Data
JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.
1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,
A list of data types appears at the bottom of this document. String datetimestamp = new java.sql.timestamp(system.currenttimemillis()).
Data Types Introduction A data type is category of data in computer programming. There are many types so are clustered into four broad categories (numeric, alphanumeric (characters and strings), dates,
Introduction to Python
WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language
Object Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
JavaScript Introduction
JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML, for the web, for servers, PCs, laptops, tablets, phones, and more. JavaScript is a Scripting
Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab.
Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command
Basic Programming and PC Skills: Basic Programming and PC Skills:
Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of
6.170 Tutorial 3 - Ruby Basics
6.170 Tutorial 3 - Ruby Basics Prerequisites 1. Have Ruby installed on your computer a. If you use Mac/Linux, Ruby should already be preinstalled on your machine. b. If you have a Windows Machine, you
Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language
Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from
So far we have considered only numeric processing, i.e. processing of numeric data represented
Chapter 4 Processing Character Data So far we have considered only numeric processing, i.e. processing of numeric data represented as integer and oating point types. Humans also use computers to manipulate
Building Java Programs
Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, 4.3-4.4 self-check: Ch. 4 #12, 15 exercises: Ch. 4 #15, 16 videos: Ch. 3 #3 1 Objects and classes object: An entity that contains: data
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming 2.1 Introduction You will learn elementary programming using Java primitive data types and related subjects, such as variables, constants, operators, expressions, and input
Introduction to Python
Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment
Java Crash Course Part I
Java Crash Course Part I School of Business and Economics Institute of Information Systems HU-Berlin WS 2005 Sebastian Kolbe [email protected] Overview (Short) introduction to the environment Linux
Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program
Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2014 Jill Seaman
Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program
Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third
Python Loops and String Manipulation
WEEK TWO Python Loops and String Manipulation Last week, we showed you some basic Python programming and gave you some intriguing problems to solve. But it is hard to do anything really exciting until
File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)
File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The
CmpSci 187: Programming with Data Structures Spring 2015
CmpSci 187: Programming with Data Structures Spring 2015 Lecture #12 John Ridgway March 10, 2015 1 Implementations of Queues 1.1 Linked Queues A Linked Queue Implementing a queue with a linked list is
