Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Refreshers - java long forgotten
New Posts  All Forums:Forum Nav:

Refreshers - java long forgotten

post #1 of 11
Thread Starter 
what does static mean? why do we use static before a class or a variable or a function?

I am currently trying to remember/review and refresh my memories of java that I once learned 7 years ago.
Looking at my old codes, I still remember most of their usage, just need some refreshers. I found out I made some amazing Java lesson plans written in English(omg it's English)!

Below will be those lesson plans that I will share to help some beginners out too

do while - http://www.overclock.net/coding-prog...l#post12952073
for loops - http://www.overclock.net/coding-prog...l#post12952102
while - http://www.overclock.net/coding-prog...l#post12952121

Strings -
Edited by tat098 - 3/31/11 at 6:26pm
post #2 of 11
Thread Starter 
do-while loop
Before I talk about do-while loops I need to talk about loops in general. Loops enable control of the flow of a program. They may allow a program to repeat the code with the loop according to a given condition. If the condition is true then the code is repeated, if it is false then the program continues to the line after the loop. Loops have 4 parts: initializer, condition, updater (increment), and statements that are in the loop.
The do-while loop can control a program by executing the code once and then repeating the given code if the conditon is true.
Ex of format:do
statement(s);/*code to be excuted – this code may be any allowed statement(s) you may have if-else or loop statements as well*/
}while(condition);//statement(s) are repeated if condition is true
The code is executed literally as: do the following statement(s) while the condition is true. Conditions within a loop are generally expected to change as the loop repeats itself.
This loop is different than a for loop or a while loop because the statement(s) are always executed at least once since the condition is not checked until after the first iteration of the loop. Every do-while loop must end with a semi-colon(.
Ex: //this loop is to ask user to input positive numbers
int num=0;//initializer
num=reader.readInt(“Please enter a positive number”); /*updater(increment)*/
System.out.println(“Please enter a positive number”);

Using a do-while loop display the numbers 3, 6, 12, 24, 48, 96, 192.
int num=3;
What are the four components of a do-while loop?
Initializer, condition, updater(increment), and statements that are in the loop
What’s the difference between do-while loops and other loops?
Do-while loops execute codes at least once unlike other loops.
post #3 of 11
Thread Starter 
for loop
The for loop can control a program by a program by executing code when a value compared to another is true.
Ex:for(initial value; condition; increment)
statement(s);//code to be executed – any allowed statements
The code executes as follows:
Initialize value as in the first section of the for loop parenthesis.
check condition in the second section.
Execute code if condition is true, go to line after loop if false.
Increment value according to instructions in the third section.
Go to step 2
For loops are generally used when the number of occurrences of an event is known.

There are always three sections within a for loop.
A variable may be declared inside the first section of the for loop, i is commonly used. If this is done then i only exists in the for loop (like a local variable only in a method).
The difference between for loop and while loop is that for loop creates a local variable inside the loop but the while loop declare the variable outside, that goes the same way for do-while loop. For loops are like while loops that only execute codes if only the condition is true but do-while loop on the other hand execute the codes at least once then checks if the condition is true.
A for loop does not need braces if there is only one statement to execute.
If the condition becomes false then the program continues to the next line following the closed brace.
Initial value must be declared either in program or inside of for loop.
Any of the three sections may be excluded, although this may cause problems.
An inifinite loop may be created by excluding all 3 values. (Problem)
Ex:for(;//semi-colons must be included
//since there is no condition to check then there is nothing to stop the loop}
Here the initial value is declared before the for loop. (No Problem)
Ex:int i=0

When does a for loop terminate execution?
The statement provides a looping mechanism that executes statements repeatedly for as long as some condition remains true.
Using a for loop, print numbers from 10-1.
for(int i=10;i>0;i--)
Using a for loop, print 0 5 15 35.
for(int i=0; i<50;i=2*i+5)
post #4 of 11
Thread Starter 
while loop
The while loop can control a program by checking a condition and then executing certain code if the condition is true. The code is then repeated until the condition becomes false.
Ex:while(condition) //no semi-colon(
statement(s);//code to be executed – same as above
/*after statement(s) are executed the program the returns to the while (condition) line*/
The code is executed literally as: while the condition is true execute the following code.
If the condition is initially false then the program skips the statement(s) and continues on to the code after the closing brace ( }) of the while loop.
The statement(s) may never be executed since the condition is checked before any of the statement(s) are executed which is like the for loop except that the initializer is outside of the loop. It is different than a do-while loop since it may never execute the code inside the loop.
Ex: //this loop displays a number down to zero
int number=reader.readInt(“Enter a number to start the count down”);

What happens if the condition of a while loop is false from the outset?
Write code segments to print the squares and cubes of the first 10 positive integers.
int num=1;
while(num>=1 && num<=10)
System.out.println(num + ”) ” + Math.pow(num,2) + “ “ + Math.pow(num,3));
Write code segments to input names and ages of people until a person’s age is 100.
KeyboardReader reader=new KeyboardReader();
int age;
String name;
age=reader.readInt(“Enter your age”);
name=reader.readLine(“Enter your name”);}
post #5 of 11
Thread Starter 
Most programming languages, including Java, provide a data structure called an array, which consists of an ordered collection of similar items. An array, as a whole, has a single name, and the items in an array are referred to in terms of their position within the array.
If we needed to declare 20 tests you probably would do it like this:
int test1, test2, test3, test4, test5, test6, test7, test8, test9, test10, test11, test12, test13, test14, test15, test16, test17, test18, test19, test20;
All this work is not necessary, we could do it all in 1 small non confusing way with arrays like this:
int[] tests = new tests[20];
To call on the first test you would call on tests[0], the second test you would call on test[1] and so on and up to the last test tests[19].

How would you call on all these tests, don’t tell me you have to type tests[0], tests[1]…?
You actually can do everything in a for loop, say I want to calculate the average of all these tests I would use:
int sum=0;
int avg;
for(int i=0; i<tests.length(); i++)
Sounds familiar? This is basically review except it’s a for loop with ARRAYS.

There can be arrays for strings too using the split() method to split a string into separate pieces.
Ex: String str= “I am GOD”;
String []strArray=str.split(“ ”);
What’s this? It simply means it’s splitting the spaces for str which now has 3 parts.
So does that mean I can call on “I” as the first part but what kind of code would I use to express “I”?
strArray[0] = “I”;
strArray[1] = “am”;
strArray[2] = “GOD”;
To display the original str I would concatenate like this:
System.out.println(strArray[0] + “ ” + strArray[1] + “ ” + strArray[2]);
5 short answer questions
How would you declare 20 names with arrays?
String[] names = new names[20];
How would you use a for loop to display the names from last to first on the list?
for(int i=0; i<names.length(); i++)
System.out.println(names[i] + “ ”);
What is an array?
An array consists of an ordered collection of similar items.
What is split() used for?
It is a method to split a string into separate pieces.
String str= ”You are stupid”;
String []strArray=str.split(“ “);
How would you call on “stupid”?

Sample Problem(small coding assignment)
Write a program that asks users for the tests he had taken this semester with all the subjects and stuff. Then find the average for each subject and also find the term average.
post #6 of 11
Thread Starter 
Parameters & Return Values
The string of characters that appears between the parentheses following the message is called a parameter. There are two types of parameter, formal and actual.
Formal parameters are listed in the method’s definition.
Ex: void play(int num)
The bolded codes are the formal parameters. You must declare each variable in the parameter where you start defining a method.
Values passed to a method when it is invoked are called arguments or actual parameters.
This line of code is usually called in the main method or other methods. 100 is the actual parameter and now represents num in the other example.

Methods with main data types (int, char, String, double, boolean) as signature must have return values, other types of signatures cannot have return values like “void”. Only codes above the return statement will be executed, all other codes below will be skipped. A method cannot have more than 2 return values and all return values must match the method’s signature.
Ex:boolean smart(int test1, int test2, int test3)
if(test1>90 && test2>90 && test3>90)return true;
return false;

5 short answer questions
What’s the error with the following code?
int score()
String name=reader.readLine();
return name;
name is a String which does not match the signature
What are the two types of parameter?
The two types of parameter are formal parameters and actual parameters.
Where are formal parameters found?
They can be found in the method’s definition.
What is another name for actual parameters?
Can a method have more than 2 return values?
No, a method can only have 1 and only 1 return value.
Sample Problem(small coding assignment)
Code a program that asks for your name, place you live in and age using all of the followings:
Actual Parameters
Formal Parameters
Return values
After you’ve asked for their name, place you live in and age, display them like the followings:
John Smith(name) is 15(age, if age is 1 or less put year instead of years) years old living in Manhattan(place)
Note: do not display the things I wrote in parentheses, they are for personal references only.
post #7 of 11
Thread Starter 
Strings are another type of data used in text processing. Strings are sequences of characters, such as “The cat sat on the mat.” The computer encodes each character in ASCII or Unicode and strings them together.

Strings are used in programs in a variety of ways. As already seen, they can be used as literals or assigned to variables. Now we will see that they can be combined in expressions using the concatenation operator, and they also can be sent messages.

The concatenation operator uses the plus symbol (+). Strings also can be concatenated to numbers. When this occurs, the number is automatically converted to a string before the concatenation operator is applied:
Ex:String name, place, description;
int age;
if(age is >1)
description=name + “ is “ + age + “years old” + “living in” + place;
description=name + “ is “ + age + “year old” + “living in” + place;
Precedence of Concatenation
The concatenation operator has the same precedence as addition, which can lead to unexpected results:
Ex:“number ” + 5 + 6 = “number 56”
“number ” + ( 5 + 6 ) = “number 11”
“number ” + 5 * 6 = “number 30”
5 + 6 + “ number” = “11 number”

Advanced Operations on Strings
We will learn about some commonly used string methods.


returns charEx: chr = myStr.charAt(4);
Returns the charater at the position anIndex. Remember that the first character is at position 0. An exception is thrown (i.e., an error is generated) if anIndex is out of range (i.e., does not indicate a valid position within myStr).

returns intEx: boolean = myStr.equals(“abc”);
Returns true if myStr equals aString; else returns false. Because of implementation peculiarities in Java, never test for equality like this: myStr==aString.
returns intEx: i = myStr.IndexOf(‘z’)Returns the index within myStr of the first occurrence of aCharacter of –1 if aCharacter is absent.
returns int Ex: i = myStr.length();
Returns the length of myStr.
substring(beginIndex, endIndex)
returns StringEx: str = myStr.substring(4, 8);
Returns a new string that is substring of myStr. The substring beings at location beginIndex and extends to location endIndex –1. An exception is thrown(i.e., an error is generated) if beginIndex is out of range (i.e., does not indicate a valid position within myStr).
returns StringEx: str = myStr.toLowerCase();
str is the same as myStr except that all letters have been converted to lowercase.
returns StringEx: str = myStr.toUpperCase();
str is the same as myStr except that all letters have been converted to uppercase.
returns StringEx: str = myStr.trim();
str is the same as myStr except that leading and trailing spaces, if any, are absent.
5 short answer questions
What is used to concatenate strings?
Plus symbol (+) is used to concatenate strings.
String str = ”abc ” + 11 + 3;
What is the value of str?
str = ”abc 113”;
String chr, words;
words = ”It is raining now”;
chr = words.charAt(5);
What is the value of chr?
chr = “ ”;
String str = “God bless America”;
What is the value of str.length();?
String str = “You’re stupid”;
What is the value of str.substring(4, 9);?
“re st”

Sample Problem(small coding assignment)
Code a program that asks the users for his favorite show, best friend’s name and favorite food.
Display his favorite show’s letter backwards, his best friend’s name last name first then first name, his favorite food’s length.
post #8 of 11
... We're not going to do your homework for you.
post #9 of 11
Thread Starter 
Using a 2 dimensional array of students 8 grades.

class StudentGrades()
** KeyboardReader reader=new KeyboardReader();
** int amount=reader.readInt(“Please enter number of
students. ”);
** Student[][]students=new Student[amount][8];
** int add, avg;
** int i, j;
** for (i=0;i< DIV>>** {
**** for (j=0;j<8;j++)
****** students[i][j]=new Student();
** }
a. Set grades to 0.
for (j=0;j<8;j++)
b. Display failing grades.
for (j=0;j<8;j++)
**if (students[j]<65)
c. Find student averages.
for (j=0;j<8;j++)
**while (j==7)
post #10 of 11
Thread Starter 
Originally Posted by Phaedrus2129 View Post
... We're not going to do your homework for you.
i dont expect you too lol, i am just posting old stuff back from 2004
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Refreshers - java long forgotten