diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cda6e70 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +pcex-python-code/ +readingmirror-data-files/ +chap*/ +*.csv +pcex/ +parsons/ +quizpet/ +py-files +temp_code/ +*.json +*.pyc +*/__pycache__/* +__pycache__ \ No newline at end of file diff --git a/Dockerfile.fastapi b/Dockerfile.fastapi new file mode 100644 index 0000000..0b272f1 --- /dev/null +++ b/Dockerfile.fastapi @@ -0,0 +1,11 @@ +FROM python:3.9.22 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --progress-bar off --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./ /code/ + +CMD ["fastapi", "run", "main_api.py", "--port", "13456"] diff --git a/Dockerfile.streamlit b/Dockerfile.streamlit new file mode 100644 index 0000000..0a49ae5 --- /dev/null +++ b/Dockerfile.streamlit @@ -0,0 +1,13 @@ +FROM python:3.9-slim + +WORKDIR /code + +COPY ./ /code + +RUN pip install --progress-bar off --no-cache-dir --upgrade -r /code/requirements.txt + +EXPOSE 13457 + +HEALTHCHECK CMD curl --fail http://localhost:13457/_stcore/health + +ENTRYPOINT ["streamlit", "run", "streamlit_main.py", "--server.port=13457", "--server.address=0.0.0.0"] \ No newline at end of file diff --git a/README.md b/README.md index 0f13b75..f5ef02f 100644 --- a/README.md +++ b/README.md @@ -3,3 +3,37 @@ This Acos server tool parses Python 3 code and returns the found concepts by traversing the AST of the code. + + +## Requires +Python==3.9.22 + +## To run frontend +python3.9 -m streamlit run streamlit_main.py + +## To run API +python3.9 -m uvicorn main_api:app --reload-include="main_api.py" --reload-exclude="*/py-files/*" + +## Deployment on PAWSComp + +``` +sudo su +source setup_docker.sh +exit +``` + +Then to test + +``` +source test_docker.sh +``` + +Expected output: +``` +[{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Import","aggregate_context_name":"Import","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0},{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Alias","aggregate_context_name":"Alias","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0}] +[{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Import","aggregate_context_name":"Import","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0},{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Numeric-or-string-or-collection-assignment","aggregate_context_name":"Numeric-or-string-or-collection-assignment","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0},{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Int","aggregate_context_name":"Int","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0},{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Alias","aggregate_context_name":"Alias","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0}] +[{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Numeric-or-string-or-collection-assignment","aggregate_context_name":"Numeric-or-string-or-collection-assignment","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0}] +[{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Numeric-or-string-or-collection-assignment","aggregate_context_name":"Numeric-or-string-or-collection-assignment","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0},{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Slice","aggregate_context_name":"Slice","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"**contributesK**":0},{"aggregate_id":{},"um2_activity_id":{},"aggregate_content_name":"tmp1","um2_concept_id":{},"aggregate_component_name":"Int","aggregate_context_name":"Int","aggregate_domain":"py","um2_aggregate_weight":1,"aggregate_active":1,"um2_direction":0,"aggregate_source_method":"Arun Parser v0.3","um2_concept_description":"Arun Parser v0.3","importance":0,"contributesK":0}] + +ok +``` diff --git a/concepts_parser.py b/concepts_parser.py new file mode 100644 index 0000000..3923060 --- /dev/null +++ b/concepts_parser.py @@ -0,0 +1,200 @@ +# ***************************************************************************** +# Python AST parser for the ADL project +# Version 0.1.0, Teemu Sirkia + +# Reads a given Python program and creates a JSON object +# describing line-by-line which language elements exist +# in the code. +# +# For the list of the available nodes, see: +# https://docs.python.org/3/library/ast.html#abstract-grammar +# ***************************************************************************** + +import os +from os import path +from tqdm import tqdm +import pandas as pd +from utils import * +from datetime import datetime +from version import __version__ + + +def main(local=True,filename='./py-files/chap2/sec_2_7.py',mode='simple'): + #TODO 5 -- create table of concepts -- matching tags -- present example integration from concept to textbook + #TODO 1 -- expressions with parentheses -- simple / complex expression -- section 2.7 + #TODO 2 -- operator overload -- section 2.9 -- instead of Add -- Consider StrAdd + #TODO 3 -- input function -- section 2.10 + #TODO 4 -- comments + + code,codelines,mode = read_input_files(local,filename,mode) + + nodes = {'lines' : {}} + + try: + + tree = ast.parse(code) + # tokens = lexer_tokens(code) + + startNode = {'name': 'root', 'children': []} + + # Traverse all the nodes in the AST + + if mode == 'complex': + for node in ast.iter_child_nodes(tree): + complexTraverse(node, 0, nodes) + elif mode == 'hierarchical': + for node in ast.iter_child_nodes(tree): + hierarchicalTraverse(node, 0, startNode) + elif mode in ('simple', 'concepts','ast_walk'): + for node in ast.iter_child_nodes(tree): + simpleTraverse(node, 0, nodes) + else: + print('Parsing failed!\n\nError occurred: Unknown parsing mode', file=sys.stderr) + sys.exit(1) + + # Convert sets to lists before JSON transformation + if mode == 'simple' or mode == 'complex': + for line in nodes['lines']: + nodes['lines'][line] = list(nodes['lines'][line]) + elif mode == 'hierarchical': + nodes = startNode + elif mode == 'concepts': + concepts = set() + for line in nodes['lines']: + for concept in list(nodes['lines'][line]): + concepts.add(concept) + nodes = list(concepts) + elif mode == 'ast_walk': + + concepts = set() + + for node in ast.walk(tree): + print(node.__dict__) + + if not(local): + print(json.dumps(nodes)) + + if local: + return merge_lines_nodes(nodes)#.union(tokens) + + except Exception as e: + print('Parsing failed!\n\nError occurred: ' + str(e), file=sys.stderr) + # print(re.split(r'[<,\s,>,\']',str(type(e)))[3], f'line no {e.args[1][1]}') + if not(local): sys.exit(1) + +def post_process_parser(response,fname='tmp1.py',activity_id = pd.NA): + concept_ids = json.load(open('./static/um2_python_concept_ids.json','r')) + section_concepts = [] + for concept in list(response): + # format as per aggregate.kc_content_component + # concept id from um2.ent_concept + um2.rel_concept_activity for python only + # activity id provided by teh user + section_concepts.append( + { + 'aggregate_id' : pd.NA, + 'um2_activity_id': activity_id, + 'aggregate_content_name': path.splitext(fname)[0], + 'um2_concept_id' : concept_ids[concept] if concept in concept_ids else pd.NA, + 'aggregate_component_name':concept, + 'aggregate_context_name': concept, + 'aggregate_domain':'py', + 'um2_aggregate_weight': 1, + 'aggregate_active': 1, + 'um2_direction': 0, + 'aggregate_source_method': f'Arun Parser v{__version__}', + 'um2_concept_description': f'Arun Parser v{__version__}', + 'importance':0, + 'contributesK':0 + # 'date_added': datetime.today().strftime('%Y-%m-%d %H:%M:%S') + } + ) + return section_concepts + + +if __name__ == '__main__': + local = True + ## TODO handle case for non local (such as server api setup) + if local: + PYTHON_TEXTBOOK_EXAMPLE_LIST = ['parsons','quizpet']#['pcex','py-files','pcex','pcex-python-code','quizpet','parsons'] + SMART_CONTENT_LIST = ['pcex','quizpet','pcex-python-code','parsons'] + + for PYTHON_TEXTBOOK_EXAMPLES in PYTHON_TEXTBOOK_EXAMPLE_LIST: + print("processing",PYTHON_TEXTBOOK_EXAMPLES) + section_concepts = {} + if PYTHON_TEXTBOOK_EXAMPLES in SMART_CONTENT_LIST: + section_concepts ['content_name']= [] + if PYTHON_TEXTBOOK_EXAMPLES == 'py-files': + section_concepts['content_id'] = [] + section_concepts ['section_id']= [] + + section_concepts['concept'] = [] + + for root,curr_dir,files in os.walk(f'./{PYTHON_TEXTBOOK_EXAMPLES}/'): + for fname in tqdm(files): + if path.splitext(fname)[1] == '.py': + try: + codelines,response = main(local,path.join(root,fname)) + # print(response) + if PYTHON_TEXTBOOK_EXAMPLES == 'py-files': + section_concepts['content_id'].append(section_concepts['content_id'][-1]+1 if len(section_concepts['content_id']) >0 else 143) + section_concepts['section_id'].append(path.splitext(fname)[0]) + if PYTHON_TEXTBOOK_EXAMPLES in SMART_CONTENT_LIST: + section_concepts['content_name'].append(path.splitext(fname)[0]) + section_concepts['concept'].append('_'.join(list(response))) + # print(section_concepts) + + except Exception: + print(root,fname) + # print(response['lines']) + # print(codelines) + + smart_concepts_sections = pd.DataFrame.from_dict(section_concepts)#.sort_values(by='section_id') + # smart_concepts_sections.loc[:,'date_updated'] = pd.to_datetime('today') + # smart_concepts_sections = smart_concepts_sections.explode('concept') + + # if PYTHON_TEXTBOOK_EXAMPLES == 'py-files': + # db = pd.read_csv('./readingmirror-data-files/smart_learning_content_section.csv') + + # if PYTHON_TEXTBOOK_EXAMPLES in SMART_CONTENT_LIST: + # db = pd.read_csv(f'./readingmirror-data-files/smart_learning_content_concepts.csv') + timestamp = pd.to_datetime('today').strftime('%Y%m%d%H%M%S') + + if PYTHON_TEXTBOOK_EXAMPLES == 'py-files': + smart_concepts_sections.loc[:,'resource_id'] = 'pfe' + smart_concepts_sections.loc[:,'is_active'] = 1 + smart_concepts_sections.loc[:,'date_added'] = '2024-06-23 19:40:02' + smart_concepts_sections.to_csv('./smart_learning_content_section.csv',index=False) + + if PYTHON_TEXTBOOK_EXAMPLES in SMART_CONTENT_LIST: + smart_concepts_sections.loc[:,'domain']='py' + smart_concepts_sections.loc[:,'weight']=1 + smart_concepts_sections.loc[:,'active']=1 + smart_concepts_sections.loc[:,'source_method']='parser' + smart_concepts_sections.loc[:,'importance']=1 + smart_concepts_sections.loc[:,'contributesK']=1 + smart_concepts_sections.loc[:,'component_name'] = smart_concepts_sections.loc[:,'concept'] + smart_concepts_sections.loc[:,'context_name'] = smart_concepts_sections.loc[:,'concept'] + smart_concepts_sections[[x for x in smart_concepts_sections.columns if not(x == 'concept')]].to_csv(f'./smart_learning_content_concepts_{PYTHON_TEXTBOOK_EXAMPLES}_{timestamp}.csv',index=False) + + + + # type: ignore + + +## TODO something from outcomes nothing beyong +## TODO why is it being allocated this way -- indexing mistake ? +## TODO all the worksexamples -- get the py + + + + + +### Parser gives all the concepts -- new section / new concepts +### update the database for chatper sections +### update the smartcontent database +### filter in a separate -- no from future (before or present) +### filter smart contne database -- no from future (before or present) + + + + diff --git a/file_creator.py b/file_creator.py new file mode 100644 index 0000000..c6a81b2 --- /dev/null +++ b/file_creator.py @@ -0,0 +1,32 @@ +import pandas as pd +from tqdm import tqdm + +line_numbers = [] +with open('./parsons/parsons_codes.txt','r') as f: + counter = 0 + for line in f.readlines(): + counter += 1 + if line.startswith('ps_'): + line_numbers.append(counter) + +with open('./parsons/parsons_codes.txt','r') as f: + lines = f.readlines() + for ind in tqdm(range(0,len(line_numbers))): + line_number = line_numbers[ind]-1 + code_filename = lines[line_number] + code = lines[line_number+2:line_numbers[ind+1]-2] if ind+1 < len(line_numbers) else lines[line_number+2:] + + with open(f'./parsons/{code_filename.strip()}.py','w+') as f: + for line in code: + f.write(line) + + + +quizpet_codes = pd.read_csv('./quizpet/quizpet_codes.csv') + + +for row, ind in tqdm(quizpet_codes.iterrows()): + code = ind['code'] + code_filename = ind['rdfID'] + with open(f'./quizpet/{code_filename}.py','w+') as f: + f.write(code) \ No newline at end of file diff --git a/main_api.py b/main_api.py new file mode 100644 index 0000000..dd755d9 --- /dev/null +++ b/main_api.py @@ -0,0 +1,62 @@ +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel +from concepts_parser import main, post_process_parser +import os +from version import __version__ + +app = FastAPI() + +class CodeString(BaseModel): + """ + Custom type for code strings. + This can be extended with validation if needed. + """ + aggregate_id :int = 11111 ## Leave this blank if for insert query, otherwise provide id column in aggregate_kc_content_component + um2_activity_id:int = 11111 ## Leave this blank if for insert query, otherwise provide id column in um2_ent_activity, + aggregate_content_name:str = 'tmp' ### if use content_name as stored in um2_ent_activity, + code_str:str + # um2_concept_id : int ## this will be generated from backend + # aggregate_component_name:str + # aggregate_context_name: str + # aggregate_domain:str = 'py' ## defaults to python + # um2_aggregate_weight:int = 1 + # aggregate_active:int = 1 + # um2_direction: int = 0 + # aggregate_source_method:str = f'Arun Parser v{__version__}' + # um2_concept_description:str = f'Arun Parser v{__version__}' + # importance:int = 0 + # contributesK:int = 0 + +@app.get("/test_api") +async def test_api(): + return {"message": "API is working!"} + + +@app.post("/extract_concepts") +async def extract_concepts(code_json: CodeString): + print(code_json) + + if code_json is None: + raise HTTPException(status_code=400, detail="Code string cannot be empty") + try: + code_str = code_json.code_str.strip() + # Create a temporary directory for the code file + if not os.path.exists('./py-files'): + os.mkdir('py-files') + + # Write the code to a temporary file + with open('./py-files/tmp1.py', 'w+') as f: + f.write(code_str) + + # Extract concepts from the code + response = main(filename='py-files/tmp1.py') + + # Clean up the temporary files + os.remove('./py-files/tmp1.py') + os.rmdir('./py-files') + + response_df = post_process_parser(response,code_json.aggregate_content_name,code_json.um2_activity_id) + return response_df + + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) diff --git a/merge_concepts.Rmd b/merge_concepts.Rmd new file mode 100644 index 0000000..e360241 --- /dev/null +++ b/merge_concepts.Rmd @@ -0,0 +1,45 @@ +--- +title: "merge_contents" +output: html_document +date: "2024-08-06" +--- + +```{r} +library(tidyverse) +``` + + +```{r} +textbook <- read.csv('smart_learning_content_section.csv') + +textbook <- textbook[c('section_id','concept')] + +textbook +``` + + +```{r} +quizpet <- read.csv('smart_learning_content_concepts_quizpet.csv') + +quizpet <- quizpet[c('content_name','component_name')] + +quizpet$concept <- quizpet$component_name +quizpet <- quizpet[c('content_name','concept')] + +quizpet +``` + + +```{r} +content_name_urls <- read.csv('./readingmirror-data-files/smart_learning_content.csv') + +content_name_urls <- content_name_urls[c('content_name','display_name','url')] + + +content_name_urls +``` + + + + + diff --git a/merge_concepts.ipynb b/merge_concepts.ipynb new file mode 100644 index 0000000..376a845 --- /dev/null +++ b/merge_concepts.ipynb @@ -0,0 +1,3414 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 311, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd\n", + "import json" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Load Smart Content" + ] + }, + { + "cell_type": "code", + "execution_count": 312, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_nameconcept
0q_py_while_loop2Assign_print_While_Add_Lt_Int
1q_py_nested_if1Assign_print_If_Gt_Tuple_Lt_Int
2q_py_comparison_logic1Assign_print_Lt_Int_NotEq
3q_py_output2_Assign_Str_Float_print_Attribute_Int
4q_py_add_two_lists1_Assign_print_Attribute_List_Add_For_Int
.........
102q_py_dlinkedlist3_FunctionDef_print_AugAssign_If_While_Eq_NotEq...
103q_py_recursion_pascal_AugAssign_Assign_FunctionDef_Sub_print_arg_If...
104q_py_demoquestion2_v2Sub_FunctionDef_arg_If_Gt_And_GtE_Bool_Int_Return
105q_py_obj_account1_AugAssign_Assign_FunctionDef_Sub_print_ClassD...
106q_py_dict_square_AugAssign_Assign_FunctionDef_Str_print_arg_Di...
\n", + "

107 rows × 2 columns

\n", + "
" + ], + "text/plain": [ + " content_name concept\n", + "0 q_py_while_loop2 Assign_print_While_Add_Lt_Int\n", + "1 q_py_nested_if1 Assign_print_If_Gt_Tuple_Lt_Int\n", + "2 q_py_comparison_logic1 Assign_print_Lt_Int_NotEq\n", + "3 q_py_output2 _Assign_Str_Float_print_Attribute_Int\n", + "4 q_py_add_two_lists1 _Assign_print_Attribute_List_Add_For_Int\n", + ".. ... ...\n", + "102 q_py_dlinkedlist3 _FunctionDef_print_AugAssign_If_While_Eq_NotEq...\n", + "103 q_py_recursion_pascal _AugAssign_Assign_FunctionDef_Sub_print_arg_If...\n", + "104 q_py_demoquestion2_v2 Sub_FunctionDef_arg_If_Gt_And_GtE_Bool_Int_Return\n", + "105 q_py_obj_account1 _AugAssign_Assign_FunctionDef_Sub_print_ClassD...\n", + "106 q_py_dict_square _AugAssign_Assign_FunctionDef_Str_print_arg_Di...\n", + "\n", + "[107 rows x 2 columns]" + ] + }, + "execution_count": 312, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "quizpet = pd.read_csv('smart_learning_content_concepts_quizpet.csv')\n", + "\n", + "quizpet.loc[:,'concept'] = quizpet.loc[:,'component_name']\n", + "quizpet = quizpet[['content_name','concept']]\n", + "\n", + "quizpet" + ] + }, + { + "cell_type": "code", + "execution_count": 313, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_nameconcept
0py_str_repeat2_AugAssign_Assign_FunctionDef_Str_print_arg_In...
1py_concat_char_two_str1_FunctionDef_Str_print_arg_Slice_Add_Int_Return
2py_adjacent_duplicates_USub_Assign_Str_print_input_If_While_Eq_Int_N...
3py_search_list_total_count_AugAssign_Assign_FunctionDef_Str_Float_print_...
4py_adjacent_greater_Assign_Str_print_input_If_Gt_And_While_Int_NotEq
.........
118py_score_dict1_Assign_FunctionDef_Str_print_arg_If_Attribute...
119py_loan2_Assign_FunctionDef_Sub_Str_print_ClassDef_arg...
120py_repeated_sequence1_Assign_Str_print_input_Int_Add_For
121py_fahrenheit_to_celsius_Assign_Sub_Str_print_input_Div_Int_Mult
122py_score_dict2_AugAssign_Assign_FunctionDef_Str_print_arg_If...
\n", + "

123 rows × 2 columns

\n", + "
" + ], + "text/plain": [ + " content_name \\\n", + "0 py_str_repeat2 \n", + "1 py_concat_char_two_str1 \n", + "2 py_adjacent_duplicates \n", + "3 py_search_list_total_count \n", + "4 py_adjacent_greater \n", + ".. ... \n", + "118 py_score_dict1 \n", + "119 py_loan2 \n", + "120 py_repeated_sequence1 \n", + "121 py_fahrenheit_to_celsius \n", + "122 py_score_dict2 \n", + "\n", + " concept \n", + "0 _AugAssign_Assign_FunctionDef_Str_print_arg_In... \n", + "1 _FunctionDef_Str_print_arg_Slice_Add_Int_Return \n", + "2 _USub_Assign_Str_print_input_If_While_Eq_Int_N... \n", + "3 _AugAssign_Assign_FunctionDef_Str_Float_print_... \n", + "4 _Assign_Str_print_input_If_Gt_And_While_Int_NotEq \n", + ".. ... \n", + "118 _Assign_FunctionDef_Str_print_arg_If_Attribute... \n", + "119 _Assign_FunctionDef_Sub_Str_print_ClassDef_arg... \n", + "120 _Assign_Str_print_input_Int_Add_For \n", + "121 _Assign_Sub_Str_print_input_Div_Int_Mult \n", + "122 _AugAssign_Assign_FunctionDef_Str_print_arg_If... \n", + "\n", + "[123 rows x 2 columns]" + ] + }, + "execution_count": 313, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pcex = pd.read_csv('smart_learning_content_concepts_pcex.csv')\n", + "\n", + "pcex.loc[:,'concept'] = pcex.loc[:,'component_name']\n", + "pcex = pcex[['content_name','concept']]\n", + "\n", + "pcex" + ] + }, + { + "cell_type": "code", + "execution_count": 314, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_nameconcept
0ps_python_comparisonsInt_Assign_Gt_print
1ps_python_divisible_by2_Assign_Mod_Str_print_If_And_Eq_Add_For_Int
2ps_python_iteration_multiplicationAssign_Str_print_While_Lt_Int_Mult
3ps_python_recursive_factorial_FunctionDef_Sub_arg_If_Lt_Int_Return_Mult
4ps_python_divisible_by3_Assign_Mod_Str_print_Attribute_If_And_List_Eq...
.........
89ps_python_list_reverse6_Assign_Sub_print_List_For_Int_Mult
90ps_python_additionInt_Assign_Add_print
91ps_simple_function_FunctionDef_Str_print
92ps_python_list_of_remainders1_Assign_FunctionDef_Mod_print_arg_If_Attribute...
93ps_python_sum_of_two1FunctionDef_arg_If_And_Eq_Bool_Add_Return
\n", + "

94 rows × 2 columns

\n", + "
" + ], + "text/plain": [ + " content_name \\\n", + "0 ps_python_comparisons \n", + "1 ps_python_divisible_by2 \n", + "2 ps_python_iteration_multiplication \n", + "3 ps_python_recursive_factorial \n", + "4 ps_python_divisible_by3 \n", + ".. ... \n", + "89 ps_python_list_reverse6 \n", + "90 ps_python_addition \n", + "91 ps_simple_function \n", + "92 ps_python_list_of_remainders1 \n", + "93 ps_python_sum_of_two1 \n", + "\n", + " concept \n", + "0 Int_Assign_Gt_print \n", + "1 _Assign_Mod_Str_print_If_And_Eq_Add_For_Int \n", + "2 Assign_Str_print_While_Lt_Int_Mult \n", + "3 _FunctionDef_Sub_arg_If_Lt_Int_Return_Mult \n", + "4 _Assign_Mod_Str_print_Attribute_If_And_List_Eq... \n", + ".. ... \n", + "89 _Assign_Sub_print_List_For_Int_Mult \n", + "90 Int_Assign_Add_print \n", + "91 _FunctionDef_Str_print \n", + "92 _Assign_FunctionDef_Mod_print_arg_If_Attribute... \n", + "93 FunctionDef_arg_If_And_Eq_Bool_Add_Return \n", + "\n", + "[94 rows x 2 columns]" + ] + }, + "execution_count": 314, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "parsons = pd.read_csv('smart_learning_content_concepts_parsons.csv')\n", + "\n", + "parsons.loc[:,'concept'] = parsons.loc[:,'component_name']\n", + "parsons = parsons[['content_name','concept']]\n", + "\n", + "parsons" + ] + }, + { + "cell_type": "code", + "execution_count": 334, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_nameconcept
13ps_python_list_to_dict_Assign_dict_Str_print_Attribute_List_Tuple
\n", + "
" + ], + "text/plain": [ + " content_name concept\n", + "13 ps_python_list_to_dict _Assign_dict_Str_print_Attribute_List_Tuple" + ] + }, + "execution_count": 334, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "parsons[parsons.content_name == 'ps_python_list_to_dict']" + ] + }, + { + "cell_type": "code", + "execution_count": 335, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_nameconcept
0py_input_Assign_Str_print_input_While_GtE_Int
1py_list_fill_Assign_print_Attribute_List_Add_For_Int_Mult
2py_char_dict_AugAssign_Assign_FunctionDef_Str_print_arg_If...
3py_str_repeat_chars_AugAssign_Assign_FunctionDef_Str_print_arg_In...
4objects_classes_tv_FunctionDef_print_AugAssign_If_Gt_LtE_Lt_Bool...
.........
66py_single_linked_list_FunctionDef_print_AugAssign_If_Gt_While_Eq_No...
67py_bmi_calculator_Assign_Str_print_input_Div_Pow_Int_Mult
68py_file_input_stat_AugAssign_Assign_FunctionDef_Str_Try_print_ar...
69py_sorting_insertion_sort_AugAssign_Assign_FunctionDef_Sub_USub_print_a...
70py_digitsAssign_Mod_print_Gt_While_Int_FloorDiv
\n", + "

71 rows × 2 columns

\n", + "
" + ], + "text/plain": [ + " content_name \\\n", + "0 py_input \n", + "1 py_list_fill \n", + "2 py_char_dict \n", + "3 py_str_repeat_chars \n", + "4 objects_classes_tv \n", + ".. ... \n", + "66 py_single_linked_list \n", + "67 py_bmi_calculator \n", + "68 py_file_input_stat \n", + "69 py_sorting_insertion_sort \n", + "70 py_digits \n", + "\n", + " concept \n", + "0 _Assign_Str_print_input_While_GtE_Int \n", + "1 _Assign_print_Attribute_List_Add_For_Int_Mult \n", + "2 _AugAssign_Assign_FunctionDef_Str_print_arg_If... \n", + "3 _AugAssign_Assign_FunctionDef_Str_print_arg_In... \n", + "4 _FunctionDef_print_AugAssign_If_Gt_LtE_Lt_Bool... \n", + ".. ... \n", + "66 _FunctionDef_print_AugAssign_If_Gt_While_Eq_No... \n", + "67 _Assign_Str_print_input_Div_Pow_Int_Mult \n", + "68 _AugAssign_Assign_FunctionDef_Str_Try_print_ar... \n", + "69 _AugAssign_Assign_FunctionDef_Sub_USub_print_a... \n", + "70 Assign_Mod_print_Gt_While_Int_FloorDiv \n", + "\n", + "[71 rows x 2 columns]" + ] + }, + "execution_count": 335, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "examples = pd.read_csv('smart_learning_content_concepts_pcex-python-code.csv')\n", + "\n", + "examples.loc[:,'concept'] = examples.loc[:,'component_name']\n", + "examples = examples[['content_name','concept']]\n", + "\n", + "examples" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# merge files of smart content" + ] + }, + { + "cell_type": "code", + "execution_count": 343, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_namecontent_typedisplay_nameurl
0ps_helloparsonsHellohttps://acos.cs.vt.edu/html/jsparsons/jsparson...
1ps_simple_functionparsonsSimple Functionhttps://acos.cs.vt.edu/html/jsparsons/jsparson...
2ps_simple_paramsparsonsSimple Paramshttps://acos.cs.vt.edu/html/jsparsons/jsparson...
3ps_return_bigger_or_noneparsonsReturn Bigger or Nonehttps://acos.cs.vt.edu/html/jsparsons/jsparson...
4ps_python_additionparsonsAdditionhttps://acos.cs.vt.edu/html/jsparsons/jsparson...
...............
676pfe-6-9readingmirrorpfe-6-9http://adapt2.sis.pitt.edu/ereader/reader/7/pf...
677pfe-11readingmirrorpfe-11http://adapt2.sis.pitt.edu/ereader/reader/7/pf...
678pfe-14readingmirrorpfe-14http://adapt2.sis.pitt.edu/ereader/reader/7/pf...
679pfe-1-8readingmirrorpfe-1-8http://adapt2.sis.pitt.edu/ereader/reader/7/pf...
680q_r_graph_theoryRGraph Theoryhttps://computing-explanation.netlify.app/grap...
\n", + "

681 rows × 4 columns

\n", + "
" + ], + "text/plain": [ + " content_name content_type display_name \\\n", + "0 ps_hello parsons Hello \n", + "1 ps_simple_function parsons Simple Function \n", + "2 ps_simple_params parsons Simple Params \n", + "3 ps_return_bigger_or_none parsons Return Bigger or None \n", + "4 ps_python_addition parsons Addition \n", + ".. ... ... ... \n", + "676 pfe-6-9 readingmirror pfe-6-9 \n", + "677 pfe-11 readingmirror pfe-11 \n", + "678 pfe-14 readingmirror pfe-14 \n", + "679 pfe-1-8 readingmirror pfe-1-8 \n", + "680 q_r_graph_theory R Graph Theory \n", + "\n", + " url \n", + "0 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "1 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "2 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "3 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "4 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + ".. ... \n", + "676 http://adapt2.sis.pitt.edu/ereader/reader/7/pf... \n", + "677 http://adapt2.sis.pitt.edu/ereader/reader/7/pf... \n", + "678 http://adapt2.sis.pitt.edu/ereader/reader/7/pf... \n", + "679 http://adapt2.sis.pitt.edu/ereader/reader/7/pf... \n", + "680 https://computing-explanation.netlify.app/grap... \n", + "\n", + "[681 rows x 4 columns]" + ] + }, + "execution_count": 343, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "content_name_urls = pd.read_csv('./readingmirror-data-files/smart_learning_content.csv')\n", + "\n", + "content_name_urls = content_name_urls[['content_name','content_type','display_name','url']]\n", + "\n", + "content_name_urls" + ] + }, + { + "cell_type": "code", + "execution_count": 338, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_nameconcept
0q_py_while_loop2Assign_print_While_Add_Lt_Int
1q_py_nested_if1Assign_print_If_Gt_Tuple_Lt_Int
2q_py_comparison_logic1Assign_print_Lt_Int_NotEq
3q_py_output2_Assign_Str_Float_print_Attribute_Int
4q_py_add_two_lists1_Assign_print_Attribute_List_Add_For_Int
.........
66py_single_linked_list_FunctionDef_print_AugAssign_If_Gt_While_Eq_No...
67py_bmi_calculator_Assign_Str_print_input_Div_Pow_Int_Mult
68py_file_input_stat_AugAssign_Assign_FunctionDef_Str_Try_print_ar...
69py_sorting_insertion_sort_AugAssign_Assign_FunctionDef_Sub_USub_print_a...
70py_digitsAssign_Mod_print_Gt_While_Int_FloorDiv
\n", + "

395 rows × 2 columns

\n", + "
" + ], + "text/plain": [ + " content_name \\\n", + "0 q_py_while_loop2 \n", + "1 q_py_nested_if1 \n", + "2 q_py_comparison_logic1 \n", + "3 q_py_output2 \n", + "4 q_py_add_two_lists1 \n", + ".. ... \n", + "66 py_single_linked_list \n", + "67 py_bmi_calculator \n", + "68 py_file_input_stat \n", + "69 py_sorting_insertion_sort \n", + "70 py_digits \n", + "\n", + " concept \n", + "0 Assign_print_While_Add_Lt_Int \n", + "1 Assign_print_If_Gt_Tuple_Lt_Int \n", + "2 Assign_print_Lt_Int_NotEq \n", + "3 _Assign_Str_Float_print_Attribute_Int \n", + "4 _Assign_print_Attribute_List_Add_For_Int \n", + ".. ... \n", + "66 _FunctionDef_print_AugAssign_If_Gt_While_Eq_No... \n", + "67 _Assign_Str_print_input_Div_Pow_Int_Mult \n", + "68 _AugAssign_Assign_FunctionDef_Str_Try_print_ar... \n", + "69 _AugAssign_Assign_FunctionDef_Sub_USub_print_a... \n", + "70 Assign_Mod_print_Gt_While_Int_FloorDiv \n", + "\n", + "[395 rows x 2 columns]" + ] + }, + "execution_count": 338, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pd.concat([quizpet,pcex,parsons,examples],axis=0)" + ] + }, + { + "cell_type": "code", + "execution_count": 318, + "metadata": {}, + "outputs": [], + "source": [ + "content_name_urls.merge(quizpet,how='inner',on='content_name').to_csv('./out_merged_files/content_name_concept_urls_quizpet.csv', index=False)#.merge(textbook, how='inner',on='concept')" + ] + }, + { + "cell_type": "code", + "execution_count": 319, + "metadata": {}, + "outputs": [], + "source": [ + "content_name_urls.merge(pcex,how='inner',on='content_name').to_csv('./out_merged_files/content_name_concept_urls_pcex.csv',index=False)#.merge(textbook, how='inner',on='concept')" + ] + }, + { + "cell_type": "code", + "execution_count": 320, + "metadata": {}, + "outputs": [], + "source": [ + "content_name_urls.merge(parsons,how='inner',on='content_name').to_csv('./out_merged_files/content_name_concept_urls_parsons.csv',index=False)#.merge(textbook, how='inner',on='concept')" + ] + }, + { + "cell_type": "code", + "execution_count": 321, + "metadata": {}, + "outputs": [], + "source": [ + "content_name_urls.merge(examples,how='inner',on='content_name').to_csv('./out_merged_files/content_name_concept_urls_examples.csv',index=False)#.merge(textbook, how='inner',on='concept')" + ] + }, + { + "cell_type": "code", + "execution_count": 344, + "metadata": {}, + "outputs": [], + "source": [ + "content_name_urls.merge(pd.concat([quizpet,pcex,parsons,examples],axis=0),how='inner',on='content_name').to_csv('./out_merged_files/content_name_concept_urls.csv',index=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# textbook sections write" + ] + }, + { + "cell_type": "code", + "execution_count": 345, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
section_idpage_numconcept
0Section 6.670Assign_Str_print_If_Eq_Add_For_Int
1Section 6.1175Assign_Mod_Str_Tuple_Int
2Section 6.570Assign_Str_print_Slice_Int_Add
3Section 6.971_Assign_Str_print_Attribute_Int
4Section 6.368_Assign_Str_print_While_Add_Lt_For_Int
\n", + "
" + ], + "text/plain": [ + " section_id page_num concept\n", + "0 Section 6.6 70 Assign_Str_print_If_Eq_Add_For_Int\n", + "1 Section 6.11 75 Assign_Mod_Str_Tuple_Int\n", + "2 Section 6.5 70 Assign_Str_print_Slice_Int_Add\n", + "3 Section 6.9 71 _Assign_Str_print_Attribute_Int\n", + "4 Section 6.3 68 _Assign_Str_print_While_Add_Lt_For_Int" + ] + }, + "execution_count": 345, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "textbook = pd.read_csv('smart_learning_content_section.csv')\n", + "\n", + "page_ids = json.load(open('./section_page_numbers.json','r'))\n", + "\n", + "textbook.loc[:,'section_id'] = textbook.loc[:,'section_id'].apply(lambda x: f\"Section {'.'.join(x.split('-')[1:])}\")\n", + "# print(textbook.loc[:,'section_id'])\n", + "\n", + "textbook.loc[:,'page_id'] = textbook.apply(lambda x: page_ids[x['section_id']],axis=1)\n", + "\n", + "textbook = textbook[['section_id','page_id','concept']]\n", + "\n", + "textbook = textbook.rename(columns={\n", + " \"page_id\":\"page_num\"\n", + "})\n", + "\n", + "textbook.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 346, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
indexsection_idpage_numconceptconcept_upto
020Section 2.119_Str_Float_print_Int_Str_Float_print_Int
119Section 2.220_Assign_Str_Float_print_Int_Assign_Str_Float_print_Int
216Section 2.522Assign_Sub_Div_Add_Pow_Int_MultAssign_Sub_Div_Add_Pow_Int_Mult
321Section 2.623Int_Assign_AddInt_Assign_Add
417Section 2.723Sub_Div_Add_Pow_Int_MultSub_Div_Add_Pow_Int_Mult
513Section 2.824Assign_Mod_print_Int_FloorDivAssign_Mod_print_Int_FloorDiv
618Section 2.925Assign_Str_print_Add_Int_MultAssign_Str_print_Add_Int_Mult
714Section 2.1026_Assign_Str_print_input_Int_Add_Assign_Str_print_input_Int_Add
812Section 2.1126Div_Int_Assign_MultDiv_Int_Assign_Mult
915Section 2.1228Assign_Float_print_For_MultAssign_Float_print_For_Mult
1035Section 3.131_Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq_Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq
1128Section 3.232Gt_And_Lt_Bool_IntGt_And_Lt_Bool_Int
1236Section 3.333Assign_Str_print_If_Gt_Pass_Lt_IntAssign_Str_print_If_Gt_Pass_Lt_Int
1329Section 3.434Mod_Str_print_If_Eq_IntMod_Str_print_If_Eq_Int
1431Section 3.535Str_print_If_Gt_Eq_LtStr_print_If_Gt_Eq_Lt
1534Section 3.636Str_print_If_And_Eq_Lt_IntStr_print_If_And_Eq_Lt_Int
1632Section 3.737_Assign_Sub_Str_Float_print_Try_input_ExceptHa..._Assign_Sub_Str_Float_print_Try_input_ExceptHa...
1730Section 3.838Assign_Gt_And_Div_GtE_Int_NotEqAssign_Gt_And_Div_GtE_Int_NotEq
1833Section 3.939Int_AssignInt_Assign
1939Section 4.143_Int_Int
2042Section 4.244_Str_Str
2144Section 4.344_USub_Str_Float_Int_USub_Str_Float_Int
2245Section 4.445_Assign_Float_print_Attribute_Div_Import_Int_a..._Assign_Float_print_Attribute_Div_Import_Int_a...
2340Section 4.546_Assign_print_Attribute_List_Import_Int_For_alias_Assign_print_Attribute_List_Import_Int_For_alias
2437Section 4.647_FunctionDef_Str_print_FunctionDef_Str_print
2541Section 4.748NaNNaN
2643Section 4.1051_Assign_FunctionDef_Str_print_Nonetype_Attribu..._Assign_FunctionDef_Str_print_Nonetype_Attribu...
2738Section 4.1454FunctionDef_Str_printFunctionDef_Str_print
2822Section 5.157Int_Assign_AddInt_Assign_Add
2925Section 5.258Assign_Sub_Str_print_Gt_While_IntAssign_Sub_Str_print_Gt_While_Int
3023Section 5.459Assign_Str_print_Break_input_If_Continue_While...Assign_Str_print_Break_input_If_Continue_While...
3127Section 5.359Assign_Str_print_Break_input_If_While_Eq_Bool_IntAssign_Str_print_Break_input_If_While_Eq_Bool_Int
3226Section 5.560Assign_Str_print_List_ForAssign_Str_print_List_For
3324Section 5.661Assign_Is_FunctionDef_Str_print_Nonetype_arg_I...Assign_Is_FunctionDef_Str_print_Nonetype_arg_I...
348Section 6.167Int_Assign_Str_printInt_Assign_Str_print
354Section 6.368_Assign_Str_print_While_Add_Lt_For_Int_Assign_Str_print_While_Add_Lt_For_Int
3610Section 6.268_Assign_Sub_Str_print_Int_Assign_Sub_Str_print_Int
377Section 6.469Assign_Str_print_Slice_IntAssign_Str_print_Slice_Int
382Section 6.570Assign_Str_print_Slice_Int_AddAssign_Str_print_Slice_Int_Add
390Section 6.670Assign_Str_print_If_Eq_Add_For_IntAssign_Str_print_If_Eq_Add_For_Int
406Section 6.771In_StrIn_Str
413Section 6.971_Assign_Str_print_Attribute_Int_Assign_Str_print_Attribute_Int
429Section 6.871Assign_Str_print_If_Gt_Eq_Lt_AddAssign_Str_print_If_Gt_Eq_Lt_Add
435Section 6.1074_Assign_Str_print_Attribute_Slice_Int_Add_Assign_Str_print_Attribute_Slice_Int_Add
441Section 6.1175Assign_Mod_Str_Tuple_IntAssign_Mod_Str_Tuple_Int
4511Section 6.1276_Assign_Str_print_Break_input_If_Attribute_Gt_..._Assign_Str_print_Break_input_If_Attribute_Gt_...
\n", + "
" + ], + "text/plain": [ + " index section_id page_num \\\n", + "0 20 Section 2.1 19 \n", + "1 19 Section 2.2 20 \n", + "2 16 Section 2.5 22 \n", + "3 21 Section 2.6 23 \n", + "4 17 Section 2.7 23 \n", + "5 13 Section 2.8 24 \n", + "6 18 Section 2.9 25 \n", + "7 14 Section 2.10 26 \n", + "8 12 Section 2.11 26 \n", + "9 15 Section 2.12 28 \n", + "10 35 Section 3.1 31 \n", + "11 28 Section 3.2 32 \n", + "12 36 Section 3.3 33 \n", + "13 29 Section 3.4 34 \n", + "14 31 Section 3.5 35 \n", + "15 34 Section 3.6 36 \n", + "16 32 Section 3.7 37 \n", + "17 30 Section 3.8 38 \n", + "18 33 Section 3.9 39 \n", + "19 39 Section 4.1 43 \n", + "20 42 Section 4.2 44 \n", + "21 44 Section 4.3 44 \n", + "22 45 Section 4.4 45 \n", + "23 40 Section 4.5 46 \n", + "24 37 Section 4.6 47 \n", + "25 41 Section 4.7 48 \n", + "26 43 Section 4.10 51 \n", + "27 38 Section 4.14 54 \n", + "28 22 Section 5.1 57 \n", + "29 25 Section 5.2 58 \n", + "30 23 Section 5.4 59 \n", + "31 27 Section 5.3 59 \n", + "32 26 Section 5.5 60 \n", + "33 24 Section 5.6 61 \n", + "34 8 Section 6.1 67 \n", + "35 4 Section 6.3 68 \n", + "36 10 Section 6.2 68 \n", + "37 7 Section 6.4 69 \n", + "38 2 Section 6.5 70 \n", + "39 0 Section 6.6 70 \n", + "40 6 Section 6.7 71 \n", + "41 3 Section 6.9 71 \n", + "42 9 Section 6.8 71 \n", + "43 5 Section 6.10 74 \n", + "44 1 Section 6.11 75 \n", + "45 11 Section 6.12 76 \n", + "\n", + " concept \\\n", + "0 _Str_Float_print_Int \n", + "1 _Assign_Str_Float_print_Int \n", + "2 Assign_Sub_Div_Add_Pow_Int_Mult \n", + "3 Int_Assign_Add \n", + "4 Sub_Div_Add_Pow_Int_Mult \n", + "5 Assign_Mod_print_Int_FloorDiv \n", + "6 Assign_Str_print_Add_Int_Mult \n", + "7 _Assign_Str_print_input_Int_Add \n", + "8 Div_Int_Assign_Mult \n", + "9 Assign_Float_print_For_Mult \n", + "10 _Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq \n", + "11 Gt_And_Lt_Bool_Int \n", + "12 Assign_Str_print_If_Gt_Pass_Lt_Int \n", + "13 Mod_Str_print_If_Eq_Int \n", + "14 Str_print_If_Gt_Eq_Lt \n", + "15 Str_print_If_And_Eq_Lt_Int \n", + "16 _Assign_Sub_Str_Float_print_Try_input_ExceptHa... \n", + "17 Assign_Gt_And_Div_GtE_Int_NotEq \n", + "18 Int_Assign \n", + "19 _Int \n", + "20 _Str \n", + "21 _USub_Str_Float_Int \n", + "22 _Assign_Float_print_Attribute_Div_Import_Int_a... \n", + "23 _Assign_print_Attribute_List_Import_Int_For_alias \n", + "24 _FunctionDef_Str_print \n", + "25 NaN \n", + "26 _Assign_FunctionDef_Str_print_Nonetype_Attribu... \n", + "27 FunctionDef_Str_print \n", + "28 Int_Assign_Add \n", + "29 Assign_Sub_Str_print_Gt_While_Int \n", + "30 Assign_Str_print_Break_input_If_Continue_While... \n", + "31 Assign_Str_print_Break_input_If_While_Eq_Bool_Int \n", + "32 Assign_Str_print_List_For \n", + "33 Assign_Is_FunctionDef_Str_print_Nonetype_arg_I... \n", + "34 Int_Assign_Str_print \n", + "35 _Assign_Str_print_While_Add_Lt_For_Int \n", + "36 _Assign_Sub_Str_print_Int \n", + "37 Assign_Str_print_Slice_Int \n", + "38 Assign_Str_print_Slice_Int_Add \n", + "39 Assign_Str_print_If_Eq_Add_For_Int \n", + "40 In_Str \n", + "41 _Assign_Str_print_Attribute_Int \n", + "42 Assign_Str_print_If_Gt_Eq_Lt_Add \n", + "43 _Assign_Str_print_Attribute_Slice_Int_Add \n", + "44 Assign_Mod_Str_Tuple_Int \n", + "45 _Assign_Str_print_Break_input_If_Attribute_Gt_... \n", + "\n", + " concept_upto \n", + "0 _Str_Float_print_Int \n", + "1 _Assign_Str_Float_print_Int \n", + "2 Assign_Sub_Div_Add_Pow_Int_Mult \n", + "3 Int_Assign_Add \n", + "4 Sub_Div_Add_Pow_Int_Mult \n", + "5 Assign_Mod_print_Int_FloorDiv \n", + "6 Assign_Str_print_Add_Int_Mult \n", + "7 _Assign_Str_print_input_Int_Add \n", + "8 Div_Int_Assign_Mult \n", + "9 Assign_Float_print_For_Mult \n", + "10 _Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq \n", + "11 Gt_And_Lt_Bool_Int \n", + "12 Assign_Str_print_If_Gt_Pass_Lt_Int \n", + "13 Mod_Str_print_If_Eq_Int \n", + "14 Str_print_If_Gt_Eq_Lt \n", + "15 Str_print_If_And_Eq_Lt_Int \n", + "16 _Assign_Sub_Str_Float_print_Try_input_ExceptHa... \n", + "17 Assign_Gt_And_Div_GtE_Int_NotEq \n", + "18 Int_Assign \n", + "19 _Int \n", + "20 _Str \n", + "21 _USub_Str_Float_Int \n", + "22 _Assign_Float_print_Attribute_Div_Import_Int_a... \n", + "23 _Assign_print_Attribute_List_Import_Int_For_alias \n", + "24 _FunctionDef_Str_print \n", + "25 NaN \n", + "26 _Assign_FunctionDef_Str_print_Nonetype_Attribu... \n", + "27 FunctionDef_Str_print \n", + "28 Int_Assign_Add \n", + "29 Assign_Sub_Str_print_Gt_While_Int \n", + "30 Assign_Str_print_Break_input_If_Continue_While... \n", + "31 Assign_Str_print_Break_input_If_While_Eq_Bool_Int \n", + "32 Assign_Str_print_List_For \n", + "33 Assign_Is_FunctionDef_Str_print_Nonetype_arg_I... \n", + "34 Int_Assign_Str_print \n", + "35 _Assign_Str_print_While_Add_Lt_For_Int \n", + "36 _Assign_Sub_Str_print_Int \n", + "37 Assign_Str_print_Slice_Int \n", + "38 Assign_Str_print_Slice_Int_Add \n", + "39 Assign_Str_print_If_Eq_Add_For_Int \n", + "40 In_Str \n", + "41 _Assign_Str_print_Attribute_Int \n", + "42 Assign_Str_print_If_Gt_Eq_Lt_Add \n", + "43 _Assign_Str_print_Attribute_Slice_Int_Add \n", + "44 Assign_Mod_Str_Tuple_Int \n", + "45 _Assign_Str_print_Break_input_If_Attribute_Gt_... " + ] + }, + "execution_count": 346, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "textbook = textbook.sort_values(by='page_num').reset_index()\n", + "textbook.loc[:,'concept_upto'] = textbook.loc[:,'concept']\n", + "textbook.to_csv('./out_merged_files/textbook_concepts_upto.csv',index=False)\n", + "textbook" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# load merge files of smart content" + ] + }, + { + "cell_type": "code", + "execution_count": 347, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_namecontent_typedisplay_nameurlconcept
0ps_helloparsonsHellohttps://acos.cs.vt.edu/html/jsparsons/jsparson...Str_print
1ps_simple_functionparsonsSimple Functionhttps://acos.cs.vt.edu/html/jsparsons/jsparson..._FunctionDef_Str_print
2ps_simple_paramsparsonsSimple Paramshttps://acos.cs.vt.edu/html/jsparsons/jsparson..._FunctionDef_print_arg_Int_Add_Return
3ps_return_bigger_or_noneparsonsReturn Bigger or Nonehttps://acos.cs.vt.edu/html/jsparsons/jsparson...FunctionDef_Nonetype_arg_If_Gt_Eq_Lt_Return
4ps_python_additionparsonsAdditionhttps://acos.cs.vt.edu/html/jsparsons/jsparson...Int_Assign_Add_print
..................
337ps_python_linked_list_sizequestionConstruct a function that checks the sizhttps://acos.cs.vt.edu/html/jsparsons/jsparson...Assign_FunctionDef_Attribute_arg_While_Add_Int...
338ps_python_merge_sortquestionConstruct a function that sorts a numerihttps://acos.cs.vt.edu/html/jsparsons/jsparson..._Assign_FunctionDef_arg_If_LtE_Slice_Int_Retur...
339ps_python_quick_sortingquestionPracticing quick sort algorithmhttps://acos.cs.vt.edu/html/jsparsons/jsparson..._Assign_FunctionDef_Sub_arg_If_Add_Lt_Int_Return
340ps_python_tree_inorder_traversalquestionConstruct an inorder traversal functionhttps://acos.cs.vt.edu/html/jsparsons/jsparson..._Assign_FunctionDef_arg_If_Attribute_List_Add_...
341ps_python_tree_preorder_traversalquestionConstruct a preorder traversal functionhttps://acos.cs.vt.edu/html/jsparsons/jsparson..._Assign_FunctionDef_arg_If_Attribute_List_Add_...
\n", + "

342 rows × 5 columns

\n", + "
" + ], + "text/plain": [ + " content_name content_type \\\n", + "0 ps_hello parsons \n", + "1 ps_simple_function parsons \n", + "2 ps_simple_params parsons \n", + "3 ps_return_bigger_or_none parsons \n", + "4 ps_python_addition parsons \n", + ".. ... ... \n", + "337 ps_python_linked_list_size question \n", + "338 ps_python_merge_sort question \n", + "339 ps_python_quick_sorting question \n", + "340 ps_python_tree_inorder_traversal question \n", + "341 ps_python_tree_preorder_traversal question \n", + "\n", + " display_name \\\n", + "0 Hello \n", + "1 Simple Function \n", + "2 Simple Params \n", + "3 Return Bigger or None \n", + "4 Addition \n", + ".. ... \n", + "337 Construct a function that checks the siz \n", + "338 Construct a function that sorts a numeri \n", + "339 Practicing quick sort algorithm \n", + "340 Construct an inorder traversal function \n", + "341 Construct a preorder traversal function \n", + "\n", + " url \\\n", + "0 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "1 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "2 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "3 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "4 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + ".. ... \n", + "337 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "338 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "339 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "340 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "341 https://acos.cs.vt.edu/html/jsparsons/jsparson... \n", + "\n", + " concept \n", + "0 Str_print \n", + "1 _FunctionDef_Str_print \n", + "2 _FunctionDef_print_arg_Int_Add_Return \n", + "3 FunctionDef_Nonetype_arg_If_Gt_Eq_Lt_Return \n", + "4 Int_Assign_Add_print \n", + ".. ... \n", + "337 Assign_FunctionDef_Attribute_arg_While_Add_Int... \n", + "338 _Assign_FunctionDef_arg_If_LtE_Slice_Int_Retur... \n", + "339 _Assign_FunctionDef_Sub_arg_If_Add_Lt_Int_Return \n", + "340 _Assign_FunctionDef_arg_If_Attribute_List_Add_... \n", + "341 _Assign_FunctionDef_arg_If_Attribute_List_Add_... \n", + "\n", + "[342 rows x 5 columns]" + ] + }, + "execution_count": 347, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "content_name_urls = pd.read_csv('./out_merged_files/content_name_concept_urls.csv')\n", + "content_name_urls" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# load textbook upto" + ] + }, + { + "cell_type": "code", + "execution_count": 348, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
indexsection_idpage_numconceptconcept_upto
020Section 2.119_Str_Float_print_Int_Str_Float_print_Int
119Section 2.220_Assign_Str_Float_print_Int_Assign_Str_Float_print_Int
216Section 2.522Assign_Sub_Div_Add_Pow_Int_MultAssign_Sub_Div_Add_Pow_Int_Mult
321Section 2.623Int_Assign_AddInt_Assign_Add
417Section 2.723Sub_Div_Add_Pow_Int_MultSub_Div_Add_Pow_Int_Mult
513Section 2.824Assign_Mod_print_Int_FloorDivAssign_Mod_print_Int_FloorDiv
618Section 2.925Assign_Str_print_Add_Int_MultAssign_Str_print_Add_Int_Mult
714Section 2.1026_Assign_Str_print_input_Int_Add_Assign_Str_print_input_Int_Add
812Section 2.1126Div_Int_Assign_MultDiv_Int_Assign_Mult
915Section 2.1228Assign_Float_print_For_MultAssign_Float_print_For_Mult
1035Section 3.131_Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq_Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq
1128Section 3.232Gt_And_Lt_Bool_IntGt_And_Lt_Bool_Int
1236Section 3.333Assign_Str_print_If_Gt_Pass_Lt_IntAssign_Str_print_If_Gt_Pass_Lt_Int
1329Section 3.434Mod_Str_print_If_Eq_IntMod_Str_print_If_Eq_Int
1431Section 3.535Str_print_If_Gt_Eq_LtStr_print_If_Gt_Eq_Lt
1534Section 3.636Str_print_If_And_Eq_Lt_IntStr_print_If_And_Eq_Lt_Int
1632Section 3.737_Assign_Sub_Str_Float_print_Try_input_ExceptHa..._Assign_Sub_Str_Float_print_Try_input_ExceptHa...
1730Section 3.838Assign_Gt_And_Div_GtE_Int_NotEqAssign_Gt_And_Div_GtE_Int_NotEq
1833Section 3.939Int_AssignInt_Assign
1939Section 4.143_Int_Int
2042Section 4.244_Str_Str
2144Section 4.344_USub_Str_Float_Int_USub_Str_Float_Int
2245Section 4.445_Assign_Float_print_Attribute_Div_Import_Int_a..._Assign_Float_print_Attribute_Div_Import_Int_a...
2340Section 4.546_Assign_print_Attribute_List_Import_Int_For_alias_Assign_print_Attribute_List_Import_Int_For_alias
2437Section 4.647_FunctionDef_Str_print_FunctionDef_Str_print
2541Section 4.748NaNNaN
2643Section 4.1051_Assign_FunctionDef_Str_print_Nonetype_Attribu..._Assign_FunctionDef_Str_print_Nonetype_Attribu...
2738Section 4.1454FunctionDef_Str_printFunctionDef_Str_print
2822Section 5.157Int_Assign_AddInt_Assign_Add
2925Section 5.258Assign_Sub_Str_print_Gt_While_IntAssign_Sub_Str_print_Gt_While_Int
3023Section 5.459Assign_Str_print_Break_input_If_Continue_While...Assign_Str_print_Break_input_If_Continue_While...
3127Section 5.359Assign_Str_print_Break_input_If_While_Eq_Bool_IntAssign_Str_print_Break_input_If_While_Eq_Bool_Int
3226Section 5.560Assign_Str_print_List_ForAssign_Str_print_List_For
3324Section 5.661Assign_Is_FunctionDef_Str_print_Nonetype_arg_I...Assign_Is_FunctionDef_Str_print_Nonetype_arg_I...
348Section 6.167Int_Assign_Str_printInt_Assign_Str_print
354Section 6.368_Assign_Str_print_While_Add_Lt_For_Int_Assign_Str_print_While_Add_Lt_For_Int
3610Section 6.268_Assign_Sub_Str_print_Int_Assign_Sub_Str_print_Int
377Section 6.469Assign_Str_print_Slice_IntAssign_Str_print_Slice_Int
382Section 6.570Assign_Str_print_Slice_Int_AddAssign_Str_print_Slice_Int_Add
390Section 6.670Assign_Str_print_If_Eq_Add_For_IntAssign_Str_print_If_Eq_Add_For_Int
406Section 6.771In_StrIn_Str
413Section 6.971_Assign_Str_print_Attribute_Int_Assign_Str_print_Attribute_Int
429Section 6.871Assign_Str_print_If_Gt_Eq_Lt_AddAssign_Str_print_If_Gt_Eq_Lt_Add
435Section 6.1074_Assign_Str_print_Attribute_Slice_Int_Add_Assign_Str_print_Attribute_Slice_Int_Add
441Section 6.1175Assign_Mod_Str_Tuple_IntAssign_Mod_Str_Tuple_Int
4511Section 6.1276_Assign_Str_print_Break_input_If_Attribute_Gt_..._Assign_Str_print_Break_input_If_Attribute_Gt_...
\n", + "
" + ], + "text/plain": [ + " index section_id page_num \\\n", + "0 20 Section 2.1 19 \n", + "1 19 Section 2.2 20 \n", + "2 16 Section 2.5 22 \n", + "3 21 Section 2.6 23 \n", + "4 17 Section 2.7 23 \n", + "5 13 Section 2.8 24 \n", + "6 18 Section 2.9 25 \n", + "7 14 Section 2.10 26 \n", + "8 12 Section 2.11 26 \n", + "9 15 Section 2.12 28 \n", + "10 35 Section 3.1 31 \n", + "11 28 Section 3.2 32 \n", + "12 36 Section 3.3 33 \n", + "13 29 Section 3.4 34 \n", + "14 31 Section 3.5 35 \n", + "15 34 Section 3.6 36 \n", + "16 32 Section 3.7 37 \n", + "17 30 Section 3.8 38 \n", + "18 33 Section 3.9 39 \n", + "19 39 Section 4.1 43 \n", + "20 42 Section 4.2 44 \n", + "21 44 Section 4.3 44 \n", + "22 45 Section 4.4 45 \n", + "23 40 Section 4.5 46 \n", + "24 37 Section 4.6 47 \n", + "25 41 Section 4.7 48 \n", + "26 43 Section 4.10 51 \n", + "27 38 Section 4.14 54 \n", + "28 22 Section 5.1 57 \n", + "29 25 Section 5.2 58 \n", + "30 23 Section 5.4 59 \n", + "31 27 Section 5.3 59 \n", + "32 26 Section 5.5 60 \n", + "33 24 Section 5.6 61 \n", + "34 8 Section 6.1 67 \n", + "35 4 Section 6.3 68 \n", + "36 10 Section 6.2 68 \n", + "37 7 Section 6.4 69 \n", + "38 2 Section 6.5 70 \n", + "39 0 Section 6.6 70 \n", + "40 6 Section 6.7 71 \n", + "41 3 Section 6.9 71 \n", + "42 9 Section 6.8 71 \n", + "43 5 Section 6.10 74 \n", + "44 1 Section 6.11 75 \n", + "45 11 Section 6.12 76 \n", + "\n", + " concept \\\n", + "0 _Str_Float_print_Int \n", + "1 _Assign_Str_Float_print_Int \n", + "2 Assign_Sub_Div_Add_Pow_Int_Mult \n", + "3 Int_Assign_Add \n", + "4 Sub_Div_Add_Pow_Int_Mult \n", + "5 Assign_Mod_print_Int_FloorDiv \n", + "6 Assign_Str_print_Add_Int_Mult \n", + "7 _Assign_Str_print_input_Int_Add \n", + "8 Div_Int_Assign_Mult \n", + "9 Assign_Float_print_For_Mult \n", + "10 _Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq \n", + "11 Gt_And_Lt_Bool_Int \n", + "12 Assign_Str_print_If_Gt_Pass_Lt_Int \n", + "13 Mod_Str_print_If_Eq_Int \n", + "14 Str_print_If_Gt_Eq_Lt \n", + "15 Str_print_If_And_Eq_Lt_Int \n", + "16 _Assign_Sub_Str_Float_print_Try_input_ExceptHa... \n", + "17 Assign_Gt_And_Div_GtE_Int_NotEq \n", + "18 Int_Assign \n", + "19 _Int \n", + "20 _Str \n", + "21 _USub_Str_Float_Int \n", + "22 _Assign_Float_print_Attribute_Div_Import_Int_a... \n", + "23 _Assign_print_Attribute_List_Import_Int_For_alias \n", + "24 _FunctionDef_Str_print \n", + "25 NaN \n", + "26 _Assign_FunctionDef_Str_print_Nonetype_Attribu... \n", + "27 FunctionDef_Str_print \n", + "28 Int_Assign_Add \n", + "29 Assign_Sub_Str_print_Gt_While_Int \n", + "30 Assign_Str_print_Break_input_If_Continue_While... \n", + "31 Assign_Str_print_Break_input_If_While_Eq_Bool_Int \n", + "32 Assign_Str_print_List_For \n", + "33 Assign_Is_FunctionDef_Str_print_Nonetype_arg_I... \n", + "34 Int_Assign_Str_print \n", + "35 _Assign_Str_print_While_Add_Lt_For_Int \n", + "36 _Assign_Sub_Str_print_Int \n", + "37 Assign_Str_print_Slice_Int \n", + "38 Assign_Str_print_Slice_Int_Add \n", + "39 Assign_Str_print_If_Eq_Add_For_Int \n", + "40 In_Str \n", + "41 _Assign_Str_print_Attribute_Int \n", + "42 Assign_Str_print_If_Gt_Eq_Lt_Add \n", + "43 _Assign_Str_print_Attribute_Slice_Int_Add \n", + "44 Assign_Mod_Str_Tuple_Int \n", + "45 _Assign_Str_print_Break_input_If_Attribute_Gt_... \n", + "\n", + " concept_upto \n", + "0 _Str_Float_print_Int \n", + "1 _Assign_Str_Float_print_Int \n", + "2 Assign_Sub_Div_Add_Pow_Int_Mult \n", + "3 Int_Assign_Add \n", + "4 Sub_Div_Add_Pow_Int_Mult \n", + "5 Assign_Mod_print_Int_FloorDiv \n", + "6 Assign_Str_print_Add_Int_Mult \n", + "7 _Assign_Str_print_input_Int_Add \n", + "8 Div_Int_Assign_Mult \n", + "9 Assign_Float_print_For_Mult \n", + "10 _Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq \n", + "11 Gt_And_Lt_Bool_Int \n", + "12 Assign_Str_print_If_Gt_Pass_Lt_Int \n", + "13 Mod_Str_print_If_Eq_Int \n", + "14 Str_print_If_Gt_Eq_Lt \n", + "15 Str_print_If_And_Eq_Lt_Int \n", + "16 _Assign_Sub_Str_Float_print_Try_input_ExceptHa... \n", + "17 Assign_Gt_And_Div_GtE_Int_NotEq \n", + "18 Int_Assign \n", + "19 _Int \n", + "20 _Str \n", + "21 _USub_Str_Float_Int \n", + "22 _Assign_Float_print_Attribute_Div_Import_Int_a... \n", + "23 _Assign_print_Attribute_List_Import_Int_For_alias \n", + "24 _FunctionDef_Str_print \n", + "25 NaN \n", + "26 _Assign_FunctionDef_Str_print_Nonetype_Attribu... \n", + "27 FunctionDef_Str_print \n", + "28 Int_Assign_Add \n", + "29 Assign_Sub_Str_print_Gt_While_Int \n", + "30 Assign_Str_print_Break_input_If_Continue_While... \n", + "31 Assign_Str_print_Break_input_If_While_Eq_Bool_Int \n", + "32 Assign_Str_print_List_For \n", + "33 Assign_Is_FunctionDef_Str_print_Nonetype_arg_I... \n", + "34 Int_Assign_Str_print \n", + "35 _Assign_Str_print_While_Add_Lt_For_Int \n", + "36 _Assign_Sub_Str_print_Int \n", + "37 Assign_Str_print_Slice_Int \n", + "38 Assign_Str_print_Slice_Int_Add \n", + "39 Assign_Str_print_If_Eq_Add_For_Int \n", + "40 In_Str \n", + "41 _Assign_Str_print_Attribute_Int \n", + "42 Assign_Str_print_If_Gt_Eq_Lt_Add \n", + "43 _Assign_Str_print_Attribute_Slice_Int_Add \n", + "44 Assign_Mod_Str_Tuple_Int \n", + "45 _Assign_Str_print_Break_input_If_Attribute_Gt_... " + ] + }, + "execution_count": 348, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "textbook = pd.read_csv('./out_merged_files/textbook_concepts_upto.csv')\n", + "textbook" + ] + }, + { + "cell_type": "code", + "execution_count": 349, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
indexsection_idpage_numpresent_conceptconcept
020Section 2.119_Str_Float_print_Int_Str_print_Int_Float
119Section 2.220_Assign_Str_Float_print_Int_Str_Assign_print_Int_Float
216Section 2.522Assign_Sub_Div_Add_Pow_Int_Mult_Sub_Str_Div_Assign_Mult_print_Pow_Add_Int_Float
321Section 2.623Int_Assign_Add_Sub_Str_Div_Assign_Mult_print_Pow_Add_Int_Float
417Section 2.723Sub_Div_Add_Pow_Int_Mult_Sub_Str_Div_Assign_Mult_print_Pow_Add_Int_Float
513Section 2.824Assign_Mod_print_Int_FloorDiv_Sub_Str_Div_Assign_Mod_Mult_print_Pow_Add_Int...
618Section 2.925Assign_Str_print_Add_Int_Mult_Sub_Str_Div_Assign_Mod_Mult_print_Pow_Add_Int...
714Section 2.1026_Assign_Str_print_input_Int_Add_Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_A...
812Section 2.1126Div_Int_Assign_Mult_Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_A...
915Section 2.1228Assign_Float_print_For_Mult_Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_A...
1035Section 3.131_Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq_Div_LtE_Assign_Str_IsNot_Eq_Mod_Mult_print_Ad...
1128Section 3.232Gt_And_Lt_Bool_Int_And_Div_LtE_Assign_Str_IsNot_Eq_Mod_Mult_prin...
1236Section 3.333Assign_Str_print_If_Gt_Pass_Lt_Int_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
1329Section 3.434Mod_Str_print_If_Eq_Int_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
1431Section 3.535Str_print_If_Gt_Eq_Lt_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
1534Section 3.636Str_print_If_And_Eq_Lt_Int_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
1632Section 3.737_Assign_Sub_Str_Float_print_Try_input_ExceptHa..._And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
1730Section 3.838Assign_Gt_And_Div_GtE_Int_NotEq_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
1833Section 3.939Int_Assign_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
1939Section 4.143_Int_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
2042Section 4.244_Str_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
2144Section 4.344_USub_Str_Float_Int_And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M...
2245Section 4.445_Assign_Float_print_Attribute_Div_Import_Int_a..._And_Div_LtE_Assign_alias_Attribute_Pass_Str_I...
2340Section 4.546_Assign_print_Attribute_List_Import_Int_For_alias_And_Div_LtE_Assign_alias_Attribute_Pass_Str_I...
2437Section 4.647_FunctionDef_Str_print_And_Div_LtE_Assign_alias_Attribute_Pass_Str_I...
2541Section 4.748NaN_And_Div_LtE_Assign_alias_Attribute_Pass_Str_I...
2643Section 4.1051_Assign_FunctionDef_Str_print_Nonetype_Attribu..._And_Div_LtE_Nonetype_Assign_alias_Attribute_P...
2738Section 4.1454FunctionDef_Str_print_And_Div_LtE_Nonetype_Assign_alias_Attribute_P...
2822Section 5.157Int_Assign_Add_And_Div_LtE_Nonetype_Assign_alias_Attribute_P...
2925Section 5.258Assign_Sub_Str_print_Gt_While_Int_And_Div_LtE_Nonetype_Assign_alias_Attribute_P...
3023Section 5.459Assign_Str_print_Break_input_If_Continue_While..._And_Div_LtE_Nonetype_Assign_alias_Continue_At...
3127Section 5.359Assign_Str_print_Break_input_If_While_Eq_Bool_Int_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
3226Section 5.560Assign_Str_print_List_For_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
3324Section 5.661Assign_Is_FunctionDef_Str_print_Nonetype_arg_I..._And_Div_LtE_Nonetype_Assign_alias_Continue_At...
348Section 6.167Int_Assign_Str_print_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
354Section 6.368_Assign_Str_print_While_Add_Lt_For_Int_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
3610Section 6.268_Assign_Sub_Str_print_Int_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
377Section 6.469Assign_Str_print_Slice_Int_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
382Section 6.570Assign_Str_print_Slice_Int_Add_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
390Section 6.670Assign_Str_print_If_Eq_Add_For_Int_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
406Section 6.771In_Str_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
413Section 6.971_Assign_Str_print_Attribute_Int_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
429Section 6.871Assign_Str_print_If_Gt_Eq_Lt_Add_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
435Section 6.1074_Assign_Str_print_Attribute_Slice_Int_Add_And_Div_LtE_Nonetype_Assign_alias_Continue_At...
441Section 6.1175Assign_Mod_Str_Tuple_Int_And_Div_LtE_Nonetype_Assign_alias_Continue_Tu...
4511Section 6.1276_Assign_Str_print_Break_input_If_Attribute_Gt_..._And_Div_LtE_Nonetype_Assign_alias_Continue_Tu...
\n", + "
" + ], + "text/plain": [ + " index section_id page_num \\\n", + "0 20 Section 2.1 19 \n", + "1 19 Section 2.2 20 \n", + "2 16 Section 2.5 22 \n", + "3 21 Section 2.6 23 \n", + "4 17 Section 2.7 23 \n", + "5 13 Section 2.8 24 \n", + "6 18 Section 2.9 25 \n", + "7 14 Section 2.10 26 \n", + "8 12 Section 2.11 26 \n", + "9 15 Section 2.12 28 \n", + "10 35 Section 3.1 31 \n", + "11 28 Section 3.2 32 \n", + "12 36 Section 3.3 33 \n", + "13 29 Section 3.4 34 \n", + "14 31 Section 3.5 35 \n", + "15 34 Section 3.6 36 \n", + "16 32 Section 3.7 37 \n", + "17 30 Section 3.8 38 \n", + "18 33 Section 3.9 39 \n", + "19 39 Section 4.1 43 \n", + "20 42 Section 4.2 44 \n", + "21 44 Section 4.3 44 \n", + "22 45 Section 4.4 45 \n", + "23 40 Section 4.5 46 \n", + "24 37 Section 4.6 47 \n", + "25 41 Section 4.7 48 \n", + "26 43 Section 4.10 51 \n", + "27 38 Section 4.14 54 \n", + "28 22 Section 5.1 57 \n", + "29 25 Section 5.2 58 \n", + "30 23 Section 5.4 59 \n", + "31 27 Section 5.3 59 \n", + "32 26 Section 5.5 60 \n", + "33 24 Section 5.6 61 \n", + "34 8 Section 6.1 67 \n", + "35 4 Section 6.3 68 \n", + "36 10 Section 6.2 68 \n", + "37 7 Section 6.4 69 \n", + "38 2 Section 6.5 70 \n", + "39 0 Section 6.6 70 \n", + "40 6 Section 6.7 71 \n", + "41 3 Section 6.9 71 \n", + "42 9 Section 6.8 71 \n", + "43 5 Section 6.10 74 \n", + "44 1 Section 6.11 75 \n", + "45 11 Section 6.12 76 \n", + "\n", + " present_concept \\\n", + "0 _Str_Float_print_Int \n", + "1 _Assign_Str_Float_print_Int \n", + "2 Assign_Sub_Div_Add_Pow_Int_Mult \n", + "3 Int_Assign_Add \n", + "4 Sub_Div_Add_Pow_Int_Mult \n", + "5 Assign_Mod_print_Int_FloorDiv \n", + "6 Assign_Str_print_Add_Int_Mult \n", + "7 _Assign_Str_print_input_Int_Add \n", + "8 Div_Int_Assign_Mult \n", + "9 Assign_Float_print_For_Mult \n", + "10 _Is_IsNot_Gt_LtE_Eq_GtE_Lt_Bool_Int_NotEq \n", + "11 Gt_And_Lt_Bool_Int \n", + "12 Assign_Str_print_If_Gt_Pass_Lt_Int \n", + "13 Mod_Str_print_If_Eq_Int \n", + "14 Str_print_If_Gt_Eq_Lt \n", + "15 Str_print_If_And_Eq_Lt_Int \n", + "16 _Assign_Sub_Str_Float_print_Try_input_ExceptHa... \n", + "17 Assign_Gt_And_Div_GtE_Int_NotEq \n", + "18 Int_Assign \n", + "19 _Int \n", + "20 _Str \n", + "21 _USub_Str_Float_Int \n", + "22 _Assign_Float_print_Attribute_Div_Import_Int_a... \n", + "23 _Assign_print_Attribute_List_Import_Int_For_alias \n", + "24 _FunctionDef_Str_print \n", + "25 NaN \n", + "26 _Assign_FunctionDef_Str_print_Nonetype_Attribu... \n", + "27 FunctionDef_Str_print \n", + "28 Int_Assign_Add \n", + "29 Assign_Sub_Str_print_Gt_While_Int \n", + "30 Assign_Str_print_Break_input_If_Continue_While... \n", + "31 Assign_Str_print_Break_input_If_While_Eq_Bool_Int \n", + "32 Assign_Str_print_List_For \n", + "33 Assign_Is_FunctionDef_Str_print_Nonetype_arg_I... \n", + "34 Int_Assign_Str_print \n", + "35 _Assign_Str_print_While_Add_Lt_For_Int \n", + "36 _Assign_Sub_Str_print_Int \n", + "37 Assign_Str_print_Slice_Int \n", + "38 Assign_Str_print_Slice_Int_Add \n", + "39 Assign_Str_print_If_Eq_Add_For_Int \n", + "40 In_Str \n", + "41 _Assign_Str_print_Attribute_Int \n", + "42 Assign_Str_print_If_Gt_Eq_Lt_Add \n", + "43 _Assign_Str_print_Attribute_Slice_Int_Add \n", + "44 Assign_Mod_Str_Tuple_Int \n", + "45 _Assign_Str_print_Break_input_If_Attribute_Gt_... \n", + "\n", + " concept \n", + "0 _Str_print_Int_Float \n", + "1 _Str_Assign_print_Int_Float \n", + "2 _Sub_Str_Div_Assign_Mult_print_Pow_Add_Int_Float \n", + "3 _Sub_Str_Div_Assign_Mult_print_Pow_Add_Int_Float \n", + "4 _Sub_Str_Div_Assign_Mult_print_Pow_Add_Int_Float \n", + "5 _Sub_Str_Div_Assign_Mod_Mult_print_Pow_Add_Int... \n", + "6 _Sub_Str_Div_Assign_Mod_Mult_print_Pow_Add_Int... \n", + "7 _Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_A... \n", + "8 _Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_A... \n", + "9 _Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_A... \n", + "10 _Div_LtE_Assign_Str_IsNot_Eq_Mod_Mult_print_Ad... \n", + "11 _And_Div_LtE_Assign_Str_IsNot_Eq_Mod_Mult_prin... \n", + "12 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "13 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "14 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "15 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "16 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "17 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "18 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "19 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "20 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "21 _And_Div_LtE_Assign_Pass_Str_IsNot_If_Eq_Mod_M... \n", + "22 _And_Div_LtE_Assign_alias_Attribute_Pass_Str_I... \n", + "23 _And_Div_LtE_Assign_alias_Attribute_Pass_Str_I... \n", + "24 _And_Div_LtE_Assign_alias_Attribute_Pass_Str_I... \n", + "25 _And_Div_LtE_Assign_alias_Attribute_Pass_Str_I... \n", + "26 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "27 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "28 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "29 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "30 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "31 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "32 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "33 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "34 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "35 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "36 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "37 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "38 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "39 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "40 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "41 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "42 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "43 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "44 _And_Div_LtE_Nonetype_Assign_alias_Continue_Tu... \n", + "45 _And_Div_LtE_Nonetype_Assign_alias_Continue_Tu... " + ] + }, + "execution_count": 349, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for ind, row in textbook.iterrows():\n", + " # if ind > 0:\n", + " prev_concepts = []\n", + " for j in range(ind):\n", + " if not(pd.isna(textbook.loc[j,'concept'])):\n", + " prev_concept = list(set(textbook.loc[j,'concept'].split('_')))\n", + " prev_concepts.extend(prev_concept)\n", + " # print(j,ind,textbook.loc[j,'concept'])\n", + " # print(list(set(prev_concepts)))\n", + " \n", + " if not(pd.isna(row['concept'])):\n", + " prev_concepts.extend(list(set(row['concept'].split('_'))))\n", + " \n", + " prev_concepts = list(set(prev_concepts))\n", + "\n", + "\n", + " textbook.loc[ind,'concept_upto'] = '_'.join(prev_concepts)\n", + "\n", + "textbook = textbook.rename(columns={\n", + " \"concept\": \"present_concept\",\n", + " \"concept_upto\": \"concept\"\n", + "})\n", + "\n", + "textbook.sort_values(by='page_num',inplace=True)\n", + "\n", + "textbook" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "if False:\n", + " for ind1, row1 in content_name_urls.iterrows():\n", + "\n", + " slc_concept = [x.lower() for x in set(row1['concept'].split('_'))] #if not(pd.isna(row1['concept'])) else []\n", + " page_numbers = []\n", + " section_ids = []\n", + " prev_matched = False\n", + " prev_match = count_match = 0\n", + " ind = textbook.shape[0]-1\n", + " while ind > 0 and prev_match <= count_match:\n", + " r_prev = textbook.loc[ind-1]\n", + " r = textbook.loc[ind]\n", + " bc_prev = [x.lower() for x in set(r_prev['concept'].split('_'))]\n", + " bc = [x.lower() for x in set(r['concept'].split('_'))]\n", + "\n", + " for concept in slc_concept:\n", + " for book_concept in bc: \n", + " if concept == book_concept: count_match += 1\n", + " \n", + " for concept in slc_concept:\n", + " for book_concept in bc_prev:\n", + " if concept == book_concept: prev_match += 1\n", + "\n", + " page_numbers.append(f\"{r_prev['section_id']}-{r_prev['page_num']}\")\n", + "\n", + " content_name_urls.loc[ind1,'page_numbers'] = ','.join([str(x) for x in set(page_numbers)])\n", + " # content_name_urls.loc[ind1,'section_ids'] = ','.join([str(x) for x in set(section_ids)])" + ] + }, + { + "cell_type": "code", + "execution_count": 350, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
content_namecontent_typedisplay_nameurlpage_numbersbook_conceptsconcept
0ps_helloparsonsHellohttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 2.1-19_Str_print_Int_FloatStr_print
1ps_simple_functionparsonsSimple Functionhttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 4.10-51_And_Div_LtE_Nonetype_Assign_alias_Attribute_P..._FunctionDef_Str_print
2ps_simple_paramsparsonsSimple Paramshttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 4.10-51_And_Div_LtE_Nonetype_Assign_alias_Attribute_P..._FunctionDef_print_arg_Int_Add_Return
3ps_return_bigger_or_noneparsonsReturn Bigger or Nonehttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 4.10-51_And_Div_LtE_Nonetype_Assign_alias_Attribute_P...FunctionDef_Nonetype_arg_If_Gt_Eq_Lt_Return
4ps_python_additionparsonsAdditionhttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 2.10-26_Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_A...Int_Assign_Add_print
........................
337ps_python_linked_list_sizequestionConstruct a function that checks the sizhttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 5.2-58_And_Div_LtE_Nonetype_Assign_alias_Attribute_P...Assign_FunctionDef_Attribute_arg_While_Add_Int...
338ps_python_merge_sortquestionConstruct a function that sorts a numerihttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 6.10-74_And_Div_LtE_Nonetype_Assign_alias_Continue_At..._Assign_FunctionDef_arg_If_LtE_Slice_Int_Retur...
339ps_python_quick_sortingquestionPracticing quick sort algorithmhttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 4.10-51_And_Div_LtE_Nonetype_Assign_alias_Attribute_P..._Assign_FunctionDef_Sub_arg_If_Add_Lt_Int_Return
340ps_python_tree_inorder_traversalquestionConstruct an inorder traversal functionhttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 4.10-51_And_Div_LtE_Nonetype_Assign_alias_Attribute_P..._Assign_FunctionDef_arg_If_Attribute_List_Add_...
341ps_python_tree_preorder_traversalquestionConstruct a preorder traversal functionhttps://acos.cs.vt.edu/html/jsparsons/jsparson...Section 4.10-51_And_Div_LtE_Nonetype_Assign_alias_Attribute_P..._Assign_FunctionDef_arg_If_Attribute_List_Add_...
\n", + "

342 rows × 7 columns

\n", + "
" + ], + "text/plain": [ + " content_name content_type \\\n", + "0 ps_hello parsons \n", + "1 ps_simple_function parsons \n", + "2 ps_simple_params parsons \n", + "3 ps_return_bigger_or_none parsons \n", + "4 ps_python_addition parsons \n", + ".. ... ... \n", + "337 ps_python_linked_list_size question \n", + "338 ps_python_merge_sort question \n", + "339 ps_python_quick_sorting question \n", + "340 ps_python_tree_inorder_traversal question \n", + "341 ps_python_tree_preorder_traversal question \n", + "\n", + " display_name \\\n", + "0 Hello \n", + "1 Simple Function \n", + "2 Simple Params \n", + "3 Return Bigger or None \n", + "4 Addition \n", + ".. ... \n", + "337 Construct a function that checks the siz \n", + "338 Construct a function that sorts a numeri \n", + "339 Practicing quick sort algorithm \n", + "340 Construct an inorder traversal function \n", + "341 Construct a preorder traversal function \n", + "\n", + " url page_numbers \\\n", + "0 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 2.1-19 \n", + "1 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 4.10-51 \n", + "2 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 4.10-51 \n", + "3 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 4.10-51 \n", + "4 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 2.10-26 \n", + ".. ... ... \n", + "337 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 5.2-58 \n", + "338 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 6.10-74 \n", + "339 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 4.10-51 \n", + "340 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 4.10-51 \n", + "341 https://acos.cs.vt.edu/html/jsparsons/jsparson... Section 4.10-51 \n", + "\n", + " book_concepts \\\n", + "0 _Str_print_Int_Float \n", + "1 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "2 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "3 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "4 _Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_A... \n", + ".. ... \n", + "337 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "338 _And_Div_LtE_Nonetype_Assign_alias_Continue_At... \n", + "339 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "340 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "341 _And_Div_LtE_Nonetype_Assign_alias_Attribute_P... \n", + "\n", + " concept \n", + "0 Str_print \n", + "1 _FunctionDef_Str_print \n", + "2 _FunctionDef_print_arg_Int_Add_Return \n", + "3 FunctionDef_Nonetype_arg_If_Gt_Eq_Lt_Return \n", + "4 Int_Assign_Add_print \n", + ".. ... \n", + "337 Assign_FunctionDef_Attribute_arg_While_Add_Int... \n", + "338 _Assign_FunctionDef_arg_If_LtE_Slice_Int_Retur... \n", + "339 _Assign_FunctionDef_Sub_arg_If_Add_Lt_Int_Return \n", + "340 _Assign_FunctionDef_arg_If_Attribute_List_Add_... \n", + "341 _Assign_FunctionDef_arg_If_Attribute_List_Add_... \n", + "\n", + "[342 rows x 7 columns]" + ] + }, + "execution_count": 350, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def get_page_nums(row,textbook):\n", + " slc_concepts = [x.lower() for x in set(row['concept'].split('_'))] if not(pd.isna(row['concept'])) else []\n", + " ind = 0\n", + " page_nums = {}\n", + "\n", + " matched_concepts = {}\n", + " while ind < textbook.shape[0]:\n", + " row1 = textbook.loc[ind]\n", + " book_concepts = [x.lower() for x in set(row1['concept'].split('_'))]\n", + " slc_match_count = 0\n", + " book_match_count = 0\n", + "\n", + " for concept in book_concepts:\n", + " if concept in slc_concepts: slc_match_count += 1\n", + " \n", + " for concept in slc_concepts:\n", + " if concept in book_concepts: book_match_count += 1\n", + " \n", + " if slc_match_count == book_match_count and len(slc_concepts) == slc_match_count:\n", + " page_nums[f\"{row1['section_id']}-{row1['page_num']}\"] = slc_match_count #slc_match_count if slc_match_count > book_match_count else 0\n", + " matched_concepts[f\"{row1['section_id']}-{row1['page_num']}\"] = row1['concept']\n", + "\n", + " ind += 1\n", + " \n", + " get_max_count = max(page_nums.values()) if len(page_nums.values()) > 0 else 0\n", + "\n", + " return min([(k,v,matched_concepts[k]) for k,v in page_nums.items() if v == get_max_count]) if get_max_count > 0 else ('','','')\n", + "\n", + "\n", + "content_name_urls['book_match'] = content_name_urls.apply(get_page_nums,1,args=(textbook,))\n", + "# content_name_urls = content_name_urls.explode('book_match')\n", + "content_name_urls['match_count'] = content_name_urls.apply(lambda x: x['book_match'][1],axis=1)\n", + "content_name_urls['book_concepts'] = content_name_urls.apply(lambda x: x['book_match'][2],axis=1)\n", + "content_name_urls['page_numbers'] = content_name_urls.apply(lambda x: x['book_match'][0],axis=1)\n", + "content_name_urls[['content_name','content_type','display_name','url','page_numbers','book_concepts','concept']] #,'section_ids']]" + ] + }, + { + "cell_type": "code", + "execution_count": 353, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'_Sub_Str_Div_Assign_input_Mod_Mult_print_Pow_Add_Int_For_FloorDiv_Float'" + ] + }, + "execution_count": 353, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "content_name_urls.loc[content_name_urls.page_numbers == 'Section 2.12-28',['page_numbers','book_concepts','concept']].loc[28,'book_concepts']" + ] + }, + { + "cell_type": "code", + "execution_count": 354, + "metadata": {}, + "outputs": [], + "source": [ + "content_name_urls[~(content_name_urls.page_numbers == '')].to_csv('./out_merged_files/content_name_concept_urls_page_numbers.csv',index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": 355, + "metadata": {}, + "outputs": [], + "source": [ + "content_name_urls = pd.read_csv('./out_merged_files/content_name_concept_urls_page_numbers.csv')" + ] + }, + { + "cell_type": "code", + "execution_count": 360, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/tmp/ipykernel_60743/4137109579.py:8: SettingWithCopyWarning: \n", + "A value is trying to be set on a copy of a slice from a DataFrame.\n", + "Try using .loc[row_indexer,col_indexer] = value instead\n", + "\n", + "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", + " pdf_reader_list_page.loc[:,'section'] = pdf_reader_list_page.apply(lambda x: x['page_numbers'].split('-')[0],axis=1) #['page_numbers'].str.split('-').str[0]\n", + "/tmp/ipykernel_60743/4137109579.py:9: SettingWithCopyWarning: \n", + "A value is trying to be set on a copy of a slice from a DataFrame.\n", + "Try using .loc[row_indexer,col_indexer] = value instead\n", + "\n", + "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", + " pdf_reader_list_page.loc[:,'page'] = pdf_reader_list_page.apply(lambda x: x['page_numbers'].split('-')[1],axis=1) #['page_numbers'].str.split('-').str[1]\n" + ] + } + ], + "source": [ + "pdf_reader_list = content_name_urls[['content_name','content_type','display_name','url','page_numbers','concept']]#,'section_ids']]\n", + "\n", + "# pdf_reader_list.loc[:,'page_numbers'] = pdf_reader_list['page_numbers'].str.split(',')\n", + "# pdf_reader_list_page = pdf_reader_list.explode('page_numbers')\n", + "\n", + "pdf_reader_list_page = pdf_reader_list\n", + "\n", + "pdf_reader_list_page.loc[:,'section'] = pdf_reader_list_page.apply(lambda x: x['page_numbers'].split('-')[0],axis=1) #['page_numbers'].str.split('-').str[0]\n", + "pdf_reader_list_page.loc[:,'page'] = pdf_reader_list_page.apply(lambda x: x['page_numbers'].split('-')[1],axis=1) #['page_numbers'].str.split('-').str[1]\n", + "pdf_reader_list_page = pdf_reader_list_page.astype({'page':'int32'})\n", + "pdf_reader_list_page['page'] = pdf_reader_list_page['page'] + 12\n", + "\n", + "rename_content_type={\n", + " \"question\":\"3:Tracing Problems\",\n", + " \"pcex_challenge\":\"2:Challenges\",\n", + " \"pcex_set\":\"1:Examples\",\n", + " \"parsons\":\"4:Construction Problems\"\n", + "}\n", + "\n", + "pdf_reader_list_page['content_type'] = pdf_reader_list_page.apply(lambda x: rename_content_type[x['content_type']],axis=1)\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 361, + "metadata": {}, + "outputs": [], + "source": [ + "pdf_reader_list_page.to_csv('./out_merged_files/pdf_reader_list.csv',index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": 228, + "metadata": {}, + "outputs": [], + "source": [ + "if False:\n", + " pdf_reader_list_submitted = pd.read_csv('./out_merged_files/pdf_reader_list_submitted_version.csv')\n", + " updated_manually = pdf_reader_list_page.merge(pdf_reader_list_submitted,how='outer',\n", + " on = ['content_name','content_type','display_name','section'], \n", + " indicator=True)\n", + "\n", + " updated_manually = updated_manually[(updated_manually['_merge'] == 'left_only') & (updated_manually['section'] != '')]\n", + "\n", + "\n", + " updated_manually[['content_name','content_type','display_name','url_x','section','page']].to_csv('./out_merged_files/pdf_reader_list_manually_updated.csv',index=False)\n", + " updated_manually[['content_name','content_type','display_name','url_x','section','page']]" + ] + }, + { + "cell_type": "code", + "execution_count": 362, + "metadata": {}, + "outputs": [], + "source": [ + "with open('./out_merged_files/pdf_reader_list_manually_updated.json','w+') as f:\n", + " \n", + " json.dump(pdf_reader_list_page[['content_type','display_name','url','section','page']].rename(columns={\n", + " \"content_type\":\"group\",\n", + " \"display_name\":\"title\",\n", + " }).to_dict('records'),f)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/merge_concepts.py b/merge_concepts.py new file mode 100644 index 0000000..b1f0c86 --- /dev/null +++ b/merge_concepts.py @@ -0,0 +1,11 @@ +import pandas as pd +import json + + + +def merge_concepts(smart_content_df): + + smart_content_df.loc[:,'concept'] = smart_content_df.loc[:,'component_name'] + smart_content_df = smart_content_df[['content_name','concept']] + + \ No newline at end of file diff --git a/parser.py b/parser.py deleted file mode 100644 index 9f011c2..0000000 --- a/parser.py +++ /dev/null @@ -1,163 +0,0 @@ -# ***************************************************************************** -# Python AST parser for the ADL project -# Version 0.1.0, Teemu Sirkia - -# Reads a given Python program and creates a JSON object -# describing line-by-line which language elements exist -# in the code. -# -# For the list of the available nodes, see: -# https://docs.python.org/3/library/ast.html#abstract-grammar -# ***************************************************************************** - -import ast, json, sys - -# These nodes will be ignored and are not added to the node list. -# -# For example, the operators are skipped because the actual operator -# will be added to the list instead of the operator family. -nodesToSkip = {'Store', 'Load', 'Name', 'Expr', 'arguments', 'Subscript', 'BoolOp', 'BinOp', 'Compare', 'UnaryOp'} - -# ***************************************************************************** -# Special handlers for some nodes - -def handleNameConstant(node, line): - """ Converts the NameConstant node to represent the type of the value (True, False, None). """ - return str(node.value) - -def handleNum(node, line): - """ Converts the Num node to represent the type of the value (Int, Float). """ - return node.n.__class__.__name__.capitalize() - -handlers = {'Num' : handleNum, 'NameConstant' : handleNameConstant} -# ***************************************************************************** - -def simpleTraverse(node, line, nodes): - - name = node.__class__.__name__ - - # Only some nodes contain line number - if hasattr(node, 'lineno'): - line = node.lineno - - if name not in nodesToSkip: - if line not in nodes['lines']: - nodes['lines'][line] = set() - if name not in handlers: - nodes['lines'][line].add(name) - else: - nodes['lines'][line].add(handlers[name](node, line)) - - for child in ast.iter_child_nodes(node): - simpleTraverse(child, line, nodes) - -def complexTraverse(node, line, nodes): - - name = node.__class__.__name__ - - # Only some nodes contain line number - if hasattr(node, 'lineno'): - line = node.lineno - - endLine = line - - current = {'name': name, 'startLine': line} - - if name not in nodesToSkip: - if line not in nodes['lines']: - nodes['lines'][line] = [] - if name not in handlers: - nodes['lines'][line].append(current) - else: - current['name'] = handlers[name](node, line) - nodes['lines'][line].append(current) - - maxLine = endLine - for child in ast.iter_child_nodes(node): - maxLine = max(maxLine, complexTraverse(child, line, nodes)) - - if maxLine != line: - current['endLine'] = maxLine - - return maxLine - -def hierarchicalTraverse(node, line, currentNode): - - name = node.__class__.__name__ - - # Only some nodes contain line number - if hasattr(node, 'lineno'): - line = node.lineno - - endLine = line - - current = {'name': name, 'startLine': line, 'children': []} - - if name not in nodesToSkip: - if name not in handlers: - currentNode['children'].append(current) - else: - current['name'] = handlers[name](node, line) - currentNode['children'].append(current) - else: - current = currentNode - - maxLine = endLine - for child in ast.iter_child_nodes(node): - maxLine = max(maxLine, hierarchicalTraverse(child, line, current)) - - if maxLine != line: - current['endLine'] = maxLine - - return maxLine - -def main(): - - data = input() - parsed = json.loads(data) - code = parsed['code'] - mode = parsed.get('mode', 'simple') - nodes = {'lines' : {}} - - try: - - tree = ast.parse(code) - startNode = {'name': 'root', 'children': []} - - # Traverse all the nodes in the AST - - if mode == 'complex': - for node in ast.iter_child_nodes(tree): - complexTraverse(node, 0, nodes) - elif mode == 'hierarchical': - for node in ast.iter_child_nodes(tree): - hierarchicalTraverse(node, 0, startNode) - elif mode in ('simple', 'concepts'): - for node in ast.iter_child_nodes(tree): - simpleTraverse(node, 0, nodes) - else: - print('Parsing failed!\n\nError occurred: Unknown parsing mode', file=sys.stderr) - sys.exit(1) - - # Convert sets to lists before JSON transformation - if mode == 'simple' or mode == 'complex': - for line in nodes['lines']: - nodes['lines'][line] = list(nodes['lines'][line]) - elif mode == 'hierarchical': - nodes = startNode - elif mode == 'concepts': - concepts = set() - for line in nodes['lines']: - for concept in list(nodes['lines'][line]): - concepts.add(concept) - nodes = list(concepts) - - print(json.dumps(nodes)) - - except Exception as e: - print('Parsing failed!\n\nError occurred: ' + str(e), file=sys.stderr) - sys.exit(1) - - -if __name__ == '__main__': - main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d1694fa --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +streamlit-ace +streamlit +fastapi[standard] +uvicorn[standard] +pydantic +requests +tqdm +pandas +numpy +ply diff --git a/setup_docker.sh b/setup_docker.sh new file mode 100644 index 0000000..36fc1e9 --- /dev/null +++ b/setup_docker.sh @@ -0,0 +1,16 @@ +docker build -t python-parser-api ./ -f Dockerfile.fastapi + +docker stop python-parser-api-container + +docker rm python-parser-api-container + +docker run --privileged=true -d --name python-parser-api-container -p 13456:13456 python-parser-api + +docker build -t python-parser-ui ./ -f Dockerfile.streamlit + +docker stop python-parser-ui-container + +docker rm python-parser-ui-container + +docker run --privileged=true -d --name python-parser-ui-container -p 13457:13457 python-parser-ui + diff --git a/static/alice_ontology_18june.owl b/static/alice_ontology_18june.owl new file mode 100644 index 0000000..ae4f68b --- /dev/null +++ b/static/alice_ontology_18june.owl @@ -0,0 +1,2351 @@ + + + + + + + + + + + + + + + + AccessingDictionary includes any operation that retrieves values from a dictionary, including direct indexing (dict[key]) and methods like .get(), .items(), .keys(), and .values().) + + + + + + + + + Referes to the expression dictionary[‘new_key' ]= value + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + An augmented assignment statement is += 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Evaluating boolean expressions + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CallingFunctionLibrary refers to ANY use of built-in Python functions (print, len, replace, etc.) and built-in methods of objects (like list.append() or string.replace(), etc.). + + + + + + + + + CallingNestedFunction refers to the call of functions that have in their code the definition of other user-defined functions + + + + + + + + + + + + + + + + + CallingRecursiveFunction refers to calling a function that calls itself (recursion) + + + + + + + + + CallingStandardFunction refers to calling a function that meets all the 3 following criteria:1) Does not call any other user-defined functions 2) Is not nested inside another function 3) Does not call itself (not recursive) Note: A standard function may still call built-in functions. + + + + + + + + + + + + + + + + + + + + + + + + + refers to using the expression dictionary[old_key]= value + + + + + + + + + list[index]= value + + + + + + + + + UpdatingVariable refers to when a variable that was already assigned to a value is update (e.g. x+=1 or x=x+1) + + + + + + + + + + + + + + + + + check for item with the 'in' construct + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + str() + string = "" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + DefiningNestedFunction refers to defining a function inside another user-defined function. + + + + + + + + + + + + + + + + + DefiningRecursiveFunction refers to defining a function that calls itself within its own body (recursion). + + + + + + + + + DefiningSimpleFunction refers to defining a function that: 1) Does not call any other user-defined functions 2) Is not nested inside another function 3) Does not call itself (not recursive) Note: A standard function may still call built-in functions. Additionally, DefiningSimpleFunction can still be later called in nested patterns (NestedFunctionCall). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + refers to the expression len() + + + + + + + + + + + + + + + + + ForLoopWithListIndexing refers to when there is an indexing of a list happening inside a for loop + + + + + + + + + + + + + + + + + + + + + + + + + f string + + + + + + + + + + + + + + + + + + + + + + + + + These data structure as they are not inherent to Python need to be evaluated separately + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Using try and except block as "except Exception as e:" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Using try and except block with the specific error + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IfChecking refers to an if statement which is not placed inside any loop + + + + + + + + + IfCheckingInForLoop refers to an if statement inside a for loop + + + + + + + + + IfCheckingInWhileLoop refers to an if statement inside a while loop + + + + + + + + + IfElifChecking refers to an if-elif statement which is not placed inside any loop + + + + + + + + + IfElifCheckingInForLoop refers to an if-elif statement inside a for loop + + + + + + + + + IfElifCheckingInWhileLoop refers to an if-elif statement inside a while loop + + + + + + + + + IfElifElseChecking refers to an if-elif-else statement which is not placed inside any loop + + + + + + + + + IfElifElseCheckingInForLoop refers to an if-elif-else statement inside a for loop + + + + + + + + + IfElifElseCheckingInWhileLoop refers to an if-elif-else statement inside a while loop + + + + + + + + + + + + + + + + + + + + + + + + + IfElseChecking refers to an if-else statement which is not placed inside any loop + + + + + + + + + IfElseCheckingInForLoop refers to an if-else statement inside a for loop + + + + + + + + + IfElseCheckingInWhileLoop refers to an if-else statement inside a while loop + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Refers to direct indexig with the expression dict[key] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + > + + + + + + + + + >= + + + + + + + + + < + + + + + + + + + <= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ListReferencing refers to the code in which one list is set equal to another, and a change to one of the lists causes the same change in the other list. ListReferencing should only be marked as present if a list is explicitly assigned to another list variable (e.g., list2 = list1). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MixedNestedLoopIteration refers to nested loop such that a while-loop inside a for-loop or a for-loop inside a while-loop + + + + + + + + + + + + + + + + + same as % + + + + + + + + + + + + + + + + + + + + + + + + + NestedForLoopIteration refers to nested loop such that a for-loop is inside another for-loop + + + + + + + + + + + + + + + + + NestedFunctionCall refers to when one function call is placed as an argument to another function call (e.g., f(g(x))) + + + + + + + + + + + + + + + + + Nested If Checking refers to having an if, elif, or else block inside another if, elif, or else block. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NestedWhileLoopIteration refers to nested loop such that a while-loop is inside another while-loop + + + + + + + + + + + + + + + + + != + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SingleForLoopIteration refers to a single use use of a for-loop that has no nested structure +When identifying nested loop structures, classify the entire structure under the appropriate nested loop category only (e.g., NestedForLoopIteration). Do not also include the single-loop categories for the outer loop + + + + + + + + + SingleWhileLoopIteration refers to a single use of a while-loop that has no nested structure +When identifying nested loop structures, classify the entire structure under the appropriate nested loop category only (e.g., NestedWhileLoopIteration). Do not also include the single-loop categories for the outer loop + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .split() or rsplit() + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Refers to when variables are swapped (e.g. +temp =a +a=b +b=temp +) + + + + + + + + + + + + + + + + + + + + + + + + + float() +int() + + + + + + + + + + + + + + + + + strip() or rstrip() + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WhileLoopWithListIndexing refers to when there is an indexing of a list happening inside a while loop + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + maybe delete this one actually + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = + + + + + + + + + == + + + + + + + + + ForLoopWith*= refers to when there is an update of a variable with the multiplication sign inside a for loop + + + + + + + + + ForLoopWith+= refers to when there is an update of a variable with the addition sign inside a for loop + + + + + + + + + WhileLoopWith*= refers to when there is an update of a variable with the multiplication sign inside a while loop + + + + + + + + + WhileLoopWith+= refers to when there is an update of a variable with the addition sign inside a while loop + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/static/alice_thesis_06_18_2025.png b/static/alice_thesis_06_18_2025.png new file mode 100644 index 0000000..1d27773 Binary files /dev/null and b/static/alice_thesis_06_18_2025.png differ diff --git a/static/java-ontology.png b/static/java-ontology.png new file mode 100644 index 0000000..3058695 Binary files /dev/null and b/static/java-ontology.png differ diff --git a/static/java.owl b/static/java.owl new file mode 100644 index 0000000..73b1d1f --- /dev/null +++ b/static/java.owl @@ -0,0 +1,9817 @@ + + + + + + + + + + + + java_ontology + + + + java_ontology by paws.sis.pitt.edu v. 0.8.1 2009-03-25 + + + + This is a second version of Java ontology created by the PAWS group for indexing adaptive java content +The main purpose of this ontology is to represent the domian of Java and provide the basis for modelling of student knowledge of java concepts and content-based adaptation of Java-related learning activities +This version is an RDFS ontology. It spesifieds the basic vocabulary of the domain. It has three relations: subClassOf, partOf-hasPart and relatedTo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #AbstractClass + false + + + + #AbstractClass + 1. Provide a contract between a service provider and its clients. 2. An abstract class can provide implementation. 3. To make an abstract method, use the abstract modifier in front of the method declaration. # An abstract class is a class that cannot be instantiated# An abstract class must be implemented by a subclass.An abstract class is a class that is declared abstract‚Äîit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.If a class includes abstract methods, the class itself must be declared abstract, as in:When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods). + + + + #AbstractClassDefinition + true + + + + #AbstractClassDefinition + 1. Provide a contract between a service provider and its clients. 2. An abstract class can provide implementation. 3. To make an abstract method, use the abstract modifier in front of the method declaration. # An abstract class is a class that cannot be instantiated# An abstract class must be implemented by a subclass.An abstract class is a class that is declared abstract‚Äîit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.If a class includes abstract methods, the class itself must be declared abstract, as in:When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods). + + + + #AbstractMethod + false + + + + #AbstractMethod + An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:If a class includes abstract methods, the class itself must be declared abstract, as in:All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be‚Äîit's just not necessary). + + + + #AbstractMethodDefinition + true + + + + #AbstractMethodDefinition + An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:If a class includes abstract methods, the class itself must be declared abstract, as in:All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be‚Äîit's just not necessary). + + + + #AbstractModifier + true + + + + #AbstractModifier + 1. Provide a contract between a service provider and its clients. 2. An abstract class can provide implementation. 3. To make an abstract method, use the abstract modifier in front of the method declaration. # An abstract class is a class that cannot be instantiated# An abstract class must be implemented by a subclass.An abstract class is a class that is declared abstract‚Äîit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.If a class includes abstract methods, the class itself must be declared abstract, as in:When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:If a class includes abstract methods, the class itself must be declared abstract, as in:All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be‚Äîit's just not necessary). + + + + #Abstraction + true + + + + #Abstraction + An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer. + + + + #AccessSpecifier + false + + + + #ActualMethodParameter + true + + + + #ActualMethodParameter + The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.Note:¬†Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and arrays.Here's an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y coordinate): + + + + #AddAssignmentExpression + true + + + + #AddAssignmentExpression + You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1. All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Adds value of the varibale to the left with the value of the expression to the right and assigns the result to the variable to the left '=+'^^http://www.w3.org/2001/XMLSchema#string + + + + #AddExpression + true + + + + #AddExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. + additive operatorAddition Operator '+'^^http://www.w3.org/2001/XMLSchema#string + + + + #AdditiveExpression + false + + + + #AdditiveExpression + Additive operators '+' '-' + + + + #AndExpression + true + + + + #AndExpression + The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1. Otherwise, the result has the value 0. The type of the result is int. Both operands must have a arithmetic or pointer type. The usual arithmetic conversions on each operand are performed. If both operands have values of true, the result has the value true. Otherwise, the result has the value false. Both operands and the result have type boolean. Unlike the & (bitwise AND) operator, the && operator guarantees left-to-right evaluation of the operands. If the left operand evaluates to false, the right operand is not evaluated. The && operator is like & (¬ß15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)&&(b))&&(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)&&((b)&&(c)).Each operand of && must be of type boolean, or a compile-time error occurs. The type of a conditional-and expression is always boolean.At run time, the left-hand operand expression is evaluated first; if its value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated and its value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.Boolean (Logical) AND '&&'^^http://www.w3.org/2001/XMLSchema#string + + + + #ArithmeticAssignmentExpression + false + + + + #ArithmeticAssignmentExpression + Following C and C++ syntax Java allows to combine arithmetical operators and simple assignement into complex assignements + + + + #ArithmeticExpression + false + + + + #ArithmeticExpression + Arithmetic operators '+' '-' '*' '/' '%' '(' ')' + + + + #ArrayCreationStatement + true + + + + #ArrayCreationStatement + The above program declares anArray with the following line of code: int[] anArray; // declares an array of integersLike declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array ‚Äî it simply tells the compiler that this variable will hold an array of the specified type.Similarly, you can declare arrays of other types: byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings;You can also place the square brackets after the array's name: float anArrayOfFloats[]; // this form is discouragedHowever, convention discourages this form; the brackets identify the array type and should appear with the type designation. One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable. anArray = new int[10]; // create an array of integersIf this statement were missing, the compiler would print an error like the following, and compilation would fail: ArrayDemo.java:4: Variable anArray may not have been initialized.Array Creation statement consist of array declaration, new oprator type of array elements and '[]'^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayDataType + true + + + + #ArrayDataType + An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the arrayAn array of ten elementsEach item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. 1. An array is a named set of same-type variables. 2. Each variable in the array is called an array element. 3. The first element will have an index of 0. + + + + #ArrayElement + true + + + + #ArrayElement + Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output. The next few lines assign values to each element of the array: anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc.Each array element is accessed by its numerical index: System.out.println("Element 1 at index 0: " + anArray[0]); System.out.println("Element 2 at index 1: " + anArray[1]); System.out.println("Element 3 at index 2: " + anArray[2]);Array element stores a single value. The array consists of array elements. All array elements have the same data type^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayElementType + true + + + + #ArrayElementType + An array is a container object that holds a fixed number of values of a single type.Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output.An array type is written as the name of an element type followed by some number of empty pairs of square brackets []. The number of bracket pairs indicates the depth of array nesting. An array's length is not part of its type.The element type of an array may be any type, whether primitive or reference. In particular: ‚Ä¢ Arrays with an interface type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any type that implements the interface. ‚Ä¢ Arrays with an abstract class type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any subclass of the abstract class that is not itself abstract.Array types are used in declarations and in cast expressionsArray element type specifies the type of array elements - the type of values that can be stored in the array^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayInitializationStatement + true + + + + #ArrayInitializationStatement + Alternatively, you can use the shortcut syntax to create and initialize an array: int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};Here the length of the array is determined by the number of values provided between { and }. array variable intialization (including type of array elements, [], and array variable name)^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayInitializer + true + + + + #ArrayInitializer + Alternatively, you can use the shortcut syntax to create and initialize an array:Here the length of the array is determined by the number of values provided between { and }.An array initializer may be specified in a declaration, or as part of an array creation expression (¬ß15.10), creating an array and providing some initial values:An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".The length of the constructed array will equal the number of expressions.The expressions in an array initializer are executed from left to right in the textual order they occur in the source code. The nth variable initializer specifies the value of the n-1st array component. Each expression must be assignment-compatible (¬ß5.2) with the array's component type, or a compile-time error results.If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.A trailing comma may appear after the last expression in an array initializer and is ignored. + + + + #ArrayLength + true + + + + #ArrayLength + One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable. anArray = new int[10]; // create an array of integersHere the length of the array is determined by the number of values provided between { and }. Finally, you can use the built-in length property to determine the size of any array. The code System.out.println(anArray.length);will print the array's size to standard output.Array Lenght spesifies how many elements the array can store^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayVariable + true + + + + #ArrayVariable + A variable of array type holds a reference to an object. Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array. However, the initializer part of a declarator (¬ß8.3) may create an array, a reference to which then becomes the initial value of the variable.Because an array's length is not part of its type, a single variable of array type may contain references to arrays of different lengths.Here are examples of declarations of array variables that do not create arrays:Here are some examples of declarations of array variables that create array objects:The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A. This may result in a run-time exception on a later assignment; see ¬ß10.10 for a discussion.a variable of array data type storing a reference to array representation in memory^^http://www.w3.org/2001/XMLSchema#string + + + + #AssignmentExpression + false + + + + #AssignmentExpression + Assignement operators change the value of the variable to the left with the vlaue of the expression to the right + + + + #AutoBoxing + true + + + + #AutoBoxing + 1. Boxing refers to the conversion of a primitive to a corresponding wrapper instance, such as from an int to a java.lang.Integer. 2. Unboxing is the conversion of a wrapper instance to a primitive type, such as from Byte to byte. 1. Related to Java's type wrappers. 2. How values are moved into and out of a wrapper instance 3. Java primitive type wrappers: Boolean, Byte, Character, Double, Float, Long, Integer, Short. 2. 17. 1. Type conversion (JDK1.5 Autoboxing/Unboxing) 2. 17. 2. Boxing and Unboxing 2. 17. 3. Autoboxing and Auto-Unboxing 2. 17. 6. To unbox an object 2. 17. 7. Autoboxing/unboxing: an argument passed to a method or returned from a method 2. 17. 8. Autoboxing/unboxing occurs inside expressions 2. 17. 9. Auto-unboxing: mix different types of numeric objects in an expression. 2. 17. 11. Autoboxing/Unboxing Boolean and Character Values 2. 17. 12. Autoboxing/unboxing takes place with method parameters and return values. 2. 17. 13. Auto-unboxing allows you to mix different types of numeric objects in an expression.When working with numbers, most of the time you use the primitive types in your code. For example:There are, however, reasons to use objects in place of primitives, and the Java platform provides wrapper classes for each of the primitive data types. These classes "wrap" the primitive in an object. Often, the wrapping is done by the compiler‚Äîif you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the compiler unboxes the object for you.Here is an example of boxing and unboxing:When x and y are assigned integer values, the compiler boxes the integers because x and y are integer objects. In the println() statement, x and y are unboxed so that they can be added as integers.All of the numeric wrapper classes are subclasses of the abstract class Number: + + + + #BitShiftAssignmentExpression + false + + + + #BitShiftAssignmentExpression + Compines simple assignment and bit shift operators + + + + #BitShiftExpression + false + + + + #BitwiseAndAssignmentExpression + true + + + + #BitwiseAndExpression + true + + + + #BitwiseAssignmentExpression + false + + + + #BitwiseAssignmentExpression + Compines simple assignment and bitwise operators + + + + #BitwiseExpression + false + + + + #BitwiseOrAssignmentExpression + true + + + + #BitwiseOrExpression + true + + + + #BitwiseXorAssignmentExpression + true + + + + #BitwiseXorExpression + true + + + + #BooleanDataType + true + + + + #BooleanDataType + boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined. # Variables of type boolean can have only one of two values, true or false.# The values 'true' and 'false' are boolean literals.boolean data type (reserved word "boolean")^^http://www.w3.org/2001/XMLSchema#string + + + + #BooleanExpression + false + + + + #BooleanExpression + Three major operators of Boolena Algebra (and, or, not) + + + + #BooleanValue + false + + + + #BreakStatement + true + + + + #BreakStatement + 1. The break statement is used to break from an enclosing do, while, for, or switch statement. 2. It is a compile error to use break anywhere else. 3. 'break' breaks the loop without executing the rest of the statements in the block. The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop, as shown in the following BreakDemo program:break statement (breaks loop execution) +most often break statment is used as a part of switch statement^^http://www.w3.org/2001/XMLSchema#string + + + + #ByteDataType + true + + + + #ByteDataType + byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation. integer data type for numbers between -128 and 127 (reserved word "byte")^^http://www.w3.org/2001/XMLSchema#string + + + + #ByteValue + true + + + + #CallBack + true + + + + #CaseClause + true + + + + #CaseClause + Another point of interest is the break statement after each case. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements. The following program, SwitchDemo2, illustrates why it might be useful to have case statements fall through:case clause - single option of a switch statement^^http://www.w3.org/2001/XMLSchema#string + + + + #CharDataType + true + + + + #CharDataType + char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). + + + + #CharValue + true + + + + #CharValue + A character literal is expressed as a character or an escape sequence, enclosed in ASCII single quotes. (The single-quote, or apostrophe, character is \u0027.)A character literal is always of type char. + + + + #Class + false + + + + #Class + In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.The following Bicycle class is one possible implementation of a bicycle:The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. Classes are the fundamental building blocks of a Java program. You can define an Employee class as follows: 1. By convention, class names capitalize the initial of each word. 2. For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator. 3. This type of naming convention is known as Pascal naming convention. 4. The other convention, the camel naming convention, capitalize the initial of each word, except the first word. 5. Method and field names use the camel naming convention.A class is a blueprint or prototype from which objects are created.^^http://www.w3.org/2001/XMLSchema#string + + + + #ClassBody + true + + + + #ClassConstantInitializationStatement + true + + + + #ClassConstantInitializationStatement + 'public static final' variables are constant.The naming convention for static final variables is to have them in upper case and separate two words with an underscore. For example:static final static final If you want to make a static final variable accessible from outside the class, you can make it public too:The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):static final double PI = 3.141592653589793;Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).Note:¬†If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value. + + + + #ClassDataType + true + + + + #ClassDataType + class as a data type + + + + #ClassDefinition + true + + + + #ClassDefinition + In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.The following Bicycle class is one possible implementation of a bicycle:The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. Classes are the fundamental building blocks of a Java program. You can define an Employee class as follows: 1. By convention, class names capitalize the initial of each word. 2. For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator. 3. This type of naming convention is known as Pascal naming convention. 4. The other convention, the camel naming convention, capitalize the initial of each word, except the first word. 5. Method and field names use the camel naming convention.You've seen classes defined in the following way:class MyClass { //field, constructor, and method declarations}This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.The preceding class declaration is a minimal one‚Äîit contains only those components of a class declaration that are required. You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration.You can also add modifiers like public or private at the very beginning‚Äîso you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private, which determine what other classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration. For the moment you do not need to worry about these extra complications.In general, class declarations can include these components, in order: 1. Modifiers such as public, private, and a number of others that you will encounter later. 2. The class name, with the initial letter capitalized by convention. 3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 5. The class body, surrounded by braces, {}. + + + + #ClassField + true + + + + #ClassField + Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. 1. Static members are not tied to class instances. 2. Static members can be called without having an instance.In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles, as follows:Class variables are referenced by the class name itself, as inThis makes it clear that they are class variables.A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.^^http://www.w3.org/2001/XMLSchema#string + + + + #ClassFieldDefinitionStatement + true + + + + #ClassFieldDefinitionStatement + 1. You can use the keyword static in front of a field declaration. 2. The static keyword may come before or after the access modifier. You can only declare a static variable in a class level.In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles, as follows:Class variables are referenced by the class name itself, as inThis makes it clear that they are class variables. + + + + #ClassMemberDefinition + false + + + + #ClassMemberInvocation + false + + + + #ClassName + true + + + + #ClassSingnature + true + + + + #ConditionalExpression + true + + + + #ConditionalExpression + The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)). ‚Ä¢ ConditionalExpression: ‚Ä¢ ConditionalOrExpression ‚Ä¢ ConditionalOrExpression ? Expression : ConditionalExpression ‚Ä¢ The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.The first expression must be of type boolean, or a compile-time error occurs.The conditional operator may be used to choose between second and third operands of numeric type, or second and third operands of type boolean, or second and third operands that are each of either reference type or the null type. All other cases result in a compile-time error.Note that it is not permitted for either the second or the third operand expression to be an invocation of a void method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear (¬ß14.8).At run time, the first operand expression of the conditional expression is evaluated first; its boolean value is then used to choose either the second or the third operand expression: ‚Ä¢ If the value of the first operand is true, then the second operand expression is chosen. ‚Ä¢ If the value of the first operand is false, then the third operand expression is chosen.The chosen operand expression is then evaluated and the resulting value is converted to the type of the conditional expression as determined by the rules stated above. The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.Ternary operator '? :' a shortcut for trivial if-else based calculations^^http://www.w3.org/2001/XMLSchema#string + + + + #Constant + true + + + + #Constant + 1. Using the final keyword to declare a variable. 2. The final keyword specifies that the value of a variable is final and cannot be changed. 3. It is a convention in Java to write constants in uppercase letters. You can prefix a variable declaration with the keyword final to make its value unchangeable. You can make both local variables and class fields final. 1. Once assigned a value, the final value cannot change. 2. Attempting to change it will result in a compile error. + + + + #ConstantInitializationStatement + true + + + + #ConstantInitializationStatement + 1. Using the final keyword to declare a variable. 2. The final keyword specifies that the value of a variable is final and cannot be changed. 3. It is a convention in Java to write constants in uppercase letters. You can prefix a variable declaration with the keyword final to make its value unchangeable. You can make both local variables and class fields final. 1. Once assigned a value, the final value cannot change. 2. Attempting to change it will result in a compile error. + + + + #ConstantInvocation + true + + + + #ConstantInvocation + class constants (final fields) are usually defined as public static final. One can invoke them the same way methods are invoked, Since theay are usually defined as static, no object needs ot be created to call them, class name is used instead. + + + + #Constructor + false + + + + #Constructor + 1. Every class must have at least one constructor. 2. If there is no constructors for your class, the compiler will supply a default constructor(no-arg constructor). 3. A constructor is used to construct an object. 4. A constructor looks like a method and is sometimes called a constructor method. 5. A constructor never returns a value 6. A constructor always has the same name as the class. 7. A constructor may have zero argument, in which case it is called a no-argument (or no-arg, for short) constructor. 8. Constructor arguments can be used to initialize the fields in the object.The syntax for a constructor is as follows. + + + + #ConstructorCall + true + + + + #ConstructorCall + A class instance creation expression is used to create new objects that are instances of classes.Class instance creation expressions have two forms:Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (¬ß15.9.5) and creates an instance of it.We say that a class is instantiated when an instance of the class is created by a class instance creation expression. Class instantiation involves determining what class is to be instantiated, what the enclosing instances (if any) of the newly created instance are, what constructor should be invoked to create the new instance and what arguments should be passed to that constructor.If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class.The type of the class instance creation expression is the class type being instantiated.At run time, evaluation of a class instance creation expression is as follows.First, if the class instance creation expression is a qualified class instance creation expression, the qualifying primary expression is evaluated. If the qualifying expression evaluates to null, a NullPointerException is raised, and the class instance creation expression completes abruptly. If the qualifying expression completes abruptly, the class instance creation expression completes abruptly for the same reason.Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError (¬ß15.9.6).The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (¬ß4.5.5).Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (¬ß8.8) and is described in detail in ¬ß12.5.The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.Call of the constructor creates an new object and returns a refernece to to it^^http://www.w3.org/2001/XMLSchema#string + + + + #ConstructorDefinition + true + + + + #ConstructorDefinition + 1. Every class must have at least one constructor. 2. If there is no constructors for your class, the compiler will supply a default constructor(no-arg constructor). 3. A constructor is used to construct an object. 4. A constructor looks like a method and is sometimes called a constructor method. 5. A constructor never returns a value 6. A constructor always has the same name as the class. 7. A constructor may have zero argument, in which case it is called a no-argument (or no-arg, for short) constructor. 8. Constructor arguments can be used to initialize the fields in the object.The syntax for a constructor is as follows.A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations‚Äîexcept that they use the name of the class and have no return type. For example, Bicycle has one constructor:To create a new Bicycle object called myBike, a constructor is called by the new operator:Bicycle myBike = new Bicycle(30, 0, 8);new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.Although Bicycle only has one constructor, it could have others, including a no-argument constructor:Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.You can use a superclass constructor yourself. The MountainBike class at the beginning of this lesson did just that. This will be discussed later, in the lesson on interfaces and inheritance.You can use access modifiers in a constructor's declaration to control which other classes can call the constructor. + + + + #ConstructorName + true + + + + #ConstructorSignature + true + + + + #ContinueStatement + true + + + + #ContinueStatement + The continue statement stops the execution of the current iteration and causes control to begin with the next iteration.The continue statement: skips all or part of a loop iterationThe continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.continue statement (interrupts current loop iteration)^^http://www.w3.org/2001/XMLSchema#string + + + + #DOM + true + + + + #Data + false + + + + #Data + Superconcept of everytrhing related to Data types, different kinds of variables, their values and operations with viriables + + + + #DataType + false + + + + #DataType + Data type + + + + #DefaultAccessSpecifier + true + + + + #DefaultAccessSpecifier + The default access is that a member can be accessed anywhere within the package that contains its declaration; other possibilities are public, protected, and private.if none of the access modifiers public, protected, or private are specified, a class member or constructor is accessible throughout the package that contains the declaration of the class in which the class member is declared, but the class member or constructor is not accessible in any other package.If a public class has a method or constructor with default access, then this method or constructor is not accessible to or inherited by a subclass declared outside this package.For example, if we have:then a subclass in another package may declare an unrelated move method, with the same signature (¬ß8.3.2) and return type. Because the original move method is not accessible from package morepoints, super may not be used: + + + + #DefaultClause + true + + + + #DefaultClause + The default section handles all values that aren't explicitly handled by one of the case sections.default clause - final option of the switch statement^^http://www.w3.org/2001/XMLSchema#string + + + + #DefinitionStatement + false + + + + #DivideAssignmentExpression + true + + + + #DivideAssignmentExpression + All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Divide the value of the varibale to the left by the value of the expression to the right and assigns the result to the variable to the left '=/'^^http://www.w3.org/2001/XMLSchema#string + + + + #DivideExpression + true + + + + #DivideExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. / division operatorThe binary / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor.Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (¬ß5.6.2) is an integer value q whose magnitude is as large as possible while satisfying ; moreover, q is positive when and n and d have the same sign, but q is negative when and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.Division operator '/'^^http://www.w3.org/2001/XMLSchema#string + + + + #DoStatement + true + + + + #DoStatement + The do-while statement is like the while statement, except that the associated block always gets executed at least once.Its syntax is as follows:Just like the while statement, you can omit the braces if there is only one statement within them. However, always use braces for the sake of clarity.The following do-while demonstrates that at least the code in the do block will be executed once even though the initial value of j used to test the expression j < 3 evaluates to false.he Java programming language also provides a do-while statement, which can be expressed as follows:do { statement(s)} while (expression);The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false. ‚Ä¢ DoStatement: ‚Ä¢ do Statement while ( Expression ) ; ‚Ä¢ The Expression must have type boolean, or a compile-time error occurs.A do statement is executed by first executing the Statement. Then there is a choice: ‚Ä¢ If execution of the Statement completes normally, then the Expression is evaluated. If evaluation of the Expression completes abruptly for some reason, the do statement completes abruptly for the same reason. Otherwise, there is a choice based on the resulting value: ‚ó¶ If the value is true, then the entire do statement is executed again. ‚ó¶ If the value is false, no further action is taken and the do statement completes normally. ‚Ä¢ If execution of the Statement completes abruptly, see ¬ß14.12.1 below.Executing a do statement always executes the contained Statement at least once.do-while loop (postcondition)^^http://www.w3.org/2001/XMLSchema#string + + + + #DoubleDataType + true + + + + #DoubleDataType + double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. double-precision folating-point type in Java for numbers from -10^308 to10^308 and up 15 significant deciamal digits (reserved word double)^^http://www.w3.org/2001/XMLSchema#string + + + + #DoubleValue + true + + + + #DoubleValue + A floating-point literal has the following parts: a whole-number part, a decimal point (represented by an ASCII period character), a fractional part, an exponent, and a type suffix. The exponent, if present, is indicated by the ASCII letter e or E followed by an optionally signed integer.At least one digit, in either the whole number or the fraction part, and either a decimal point, an exponent, or a float type suffix are required. All other parts are optional.A floating-point literal is of type double and it can optionally be suffixed with an ASCII letter D or d. + + + + #Encapsulation + true + + + + #Encapsulation + The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private. Other access modifiers will be discussed later. ‚Ä¢ private modifier‚Äîthe field is accessible only within its own class.In the spirit of encapsulation, it is common to make fields private. This means that they can only be directly accessed from the Bicycle class. We still need access to these values, however. This can be done indirectly by adding public methods that obtain the field values for us:Encapsulation is the hiding of the internal mechanisms and data structures of a class behind its public interface, in such a way that users of the component (other pieces of software) only need to know what the class does not and cannot make themselves dependent on the details of class implementation.^^http://www.w3.org/2001/XMLSchema#string + + + + #EqualExpression + true + + + + #EqualExpression + The equality operators are syntactically left-associative (they group left-to-right), but this fact is essentially never useful; for example, a==b==c parses as (a==b)==c. The result type of a==b is always boolean, and c must therefore be of type boolean or a compile-time error occurs. Thus, a==b==c does not test to see whether a, b, and c are all equal.The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, a<b==c<d is true whenever a<b and c<d have the same truth value.The equality operators may be used to compare two operands of numeric type, or two operands of type boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always boolean.In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative if the operand expressions have no side effects.Logical equality (equal-to operator) '=='^^http://www.w3.org/2001/XMLSchema#string + + + + #ExceptionClass + true + + + + #ExceptionClass + Every exception is represented by an instance of the class Throwable or one of its subclasses; such an object can be used to carry information from the point at which an exception occurs to the handler that catches it. The possible exceptions in a program are organized in a hierarchy of classes, rooted at class Throwable (¬ß11.5), a direct subclass of Object. The classes Exception and Error are direct subclasses of Throwable. The class RuntimeException is a direct subclass of Exception.Programs can use the pre-existing exception classes in throw statements, or define additional exception classes, as subclasses of Throwable or of any of its subclasses, as appropriate. To take advantage of the Java platform's compile-time checking for exception handlers, it is typical to define most new exception classes as checked exception classes, specifically as subclasses of Exception that are not subclasses of RuntimeException.The class Exception is the superclass of all the exceptions that ordinary programs may wish to recover from. The class RuntimeException is a subclass of class Exception. The subclasses of RuntimeException are unchecked exception classes. The subclasses of Exception other than RuntimeException are all checked exception classes.The class Error and its subclasses are exceptions from which ordinary programs are not ordinarily expected to recover. See the Java API specification for a detailed description of the exception hierarchy.The class Error is a separate subclass of Throwable, distinct from Exception in the class hierarchy, to allow programs to use the idiom.to catch all exceptions from which recovery may be possible without catching errors from which recovery is typically not possible. + + + + #ExceptionHandlingStatement + false + + + + #ExplicitTypeCasting + true + + + + #ExplicitTypeCasting + Casting conversion is applied to the operand of a cast operator (¬ß15.16): the type of the operand expression must be converted to the type explicitly named by the cast operator. Casting contexts allow the use of an identity conversion (¬ß5.1.1), a widening primitive conversion (¬ß5.1.2), a narrowing primitive conversion (¬ß5.1.3), a widening reference conversion (¬ß5.1.4), or a narrowing reference conversion (¬ß5.1.5). Thus casting conversions are more inclusive than assignment or method invocation conversions: a cast can do any permitted conversion other than a string conversion.Some casts can be proven incorrect at compile time; such casts result in a compile-time error.A value of a primitive type can be cast to another primitive type by identity conversion, if the types are the same, or by a widening primitive conversion or a narrowing primitive conversion.A value of a primitive type cannot be cast to a reference type by casting conversion, nor can a value of a reference type be cast to a primitive type.A cast expression converts, at run time, a value of one numeric type to a similar value of another numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type. ‚Ä¢ CastExpression: ‚Ä¢ ( PrimitiveType Dimsopt ) UnaryExpression ‚Ä¢ ( ReferenceType ) UnaryExpressionNotPlusMinus ‚Ä¢ See ¬ß15.15 for a discussion of the distinction between UnaryExpression and UnaryExpressionNotPlusMinus.The type of a cast expression is the type whose name appears within the parentheses. (The parentheses and the type they contain are sometimes called the cast operator.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.A cast operator has no effect on the choice of value set (¬ß4.2.3) for a value of type float or type double. Consequently, a cast to type float within an expression that is not FP-strict (¬ß15.4) does not necessarily cause its value to be converted to an element of the float value set, and a cast to type double within an expression that is not FP-strict does not necessarily cause its value to be converted to an element of the double value set.At run time, the operand value is converted by casting conversion (¬ß5.5) to the type specified by the cast operator.Not all casts are permitted by the language. Some casts result in an error at compile time. For example, a primitive value may not be cast to a reference type. Some casts can be proven, at compile time, always to be correct at run time. For example, it is always correct to convert a value of a class type to the type of its superclass; such a cast should require no special action at run time. Finally, some casts cannot be proven to be either always correct or always incorrect at compile time. Such casts require a test at run time. + + + + #Expression + false + + + + #Expression + An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. + + + + #ExpressionStatement + true + + + + #ExpressionStatement + Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).Such statements are called expression statements. Here are some examples of expression statements.In addition to expression statements, there are two other kinds of statements:Some expressions can be made statements by terminating them with a semicolon. For example, x++ is an expression. However, this is a statement:x++;Certain kinds of expressions may be used as statements by following them with semicolons:An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.Expression statement consits of an assignement expression or relational operator expression or incremenet/decremenet expassion and a semicolon^^http://www.w3.org/2001/XMLSchema#string + + + + #ExtendsSpecification + true + + + + #ExtendsSpecification + Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:A diagram of classes in a hierarchy.A hierarchy of bicycle classes.The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here}This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.You extend a class by using the extends keyword in a class declaration,The Parent classThe Child class + + + + #False + true + + + + #False + The boolean type has two values, represented by literals 'false' and ...The following code declares a boolean variable includeSign and assigns it the value of false.The boolean type has two values, represented by the literals true and false, formed from ASCII letters.A boolean literal is always of type boolean.Logical false value (reserved word "false")^^http://www.w3.org/2001/XMLSchema#string + + + + #Field + false + + + + #FieldDefinition + true + + + + #FieldDefinition + The variables of a class type are introduced by field declarations:The FieldModifiers are described in ¬ß8.3.1. The Identifier in a FieldDeclarator may be used in a name to refer to the field. Fields are members; the scope (¬ß6.3) of a field declaration is specified in ¬ß8.1.5. More than one field may be declared in a single field declaration by using more than one declarator; the FieldModifiers and Type apply to all the declarators in the declaration. Variable declarations involving array types are discussed in ¬ß10.2.The access modifiers public, protected, and private are discussed in ¬ß6.6. A compile-time error occurs if the same modifier appears more than once in a field declaration, or if a field declaration has more than one of the access modifiers public, protected, and private.If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.Initialization expressions for instance variables may use the simple name of any static variable declared in or inherited by the class, even one whose declaration occurs textually later.Thus the example:compiles without error; it initializes j to 1 when class Test is initialized, and initializes f to the current value of j every time an instance of class Test is created.Initialization expressions for instance variables are permitted to refer to the current object this (¬ß15.8.3) and to use the keyword super (¬ß15.11.2, ¬ß15.12).Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. See ¬ß8.3.2.3 for the precise rules governing forward reference to instance variables. + + + + #FieldDefinitionStatement + false + + + + #FieldDefinitionStatement + variable declaration (including variable type and variable name) +it is a part of the declaration statement + + + + #FieldInheritance + true + + + + #FieldInheritance + If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class. The field declaration also shadows (¬ß6.3.1) declarations of any accessible fields in enclosing classes or interfaces, and any local variables, formal method parameters, and exception handler parameters with the same name in any enclosing blocks.If a field declaration hides the declaration of another field, the two fields need not have the same type.A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.Note that a private field of a superclass might be accessible to a subclass (for example, if both classes are members of the same class). Nevertheless, a private field is never inherited by a subclass.It is possible for a class to inherit more than one field with the same name (¬ß8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.A class may inherit two or more fields with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited field by its simple name. A qualified name or a field access expression that contains the keyword super (¬ß15.11.2) may be used to access such fields unambiguously. In the example:Subclass inherits all instance fields and class fields of the superclass. ^^http://www.w3.org/2001/XMLSchema#string + + + + #FinalClass + false + + + + #FinalClass + You can prevent others from extending your class by making it final using the keyword final in the class declaration.Note that you can also declare an entire class final ‚Äî this prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class. + + + + #FinalClass + + + + + #FinalClassDefinition + true + + + + #FinalClassDefinition + You can prevent others from extending your class by making it final using the keyword final in the class declaration.Note that you can also declare an entire class final ‚Äî this prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class. + + + + #FinalInstanceFieldInitializationStatement + true + + + + #FinalInstanceFieldInitializationStatement + If a field declarator contains a variable initializer, then it has the semantics of an assignment (¬ß15.26) to the declared variable, and: ‚Ä¢ If the declarator is for a class variable (that is, a static field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized One subtlety here is that, at run time, static variables that are final and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (¬ß9.3.1). These variables are "constants" that will never be observed to have their default initial values (¬ß4.5.5), even by devious programs. See ¬ß12.4.2 and ¬ß13.4.8 for more discussion. Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See ¬ß8.3.2.3 for the precise rules governing forward reference to class variables. + + + + #FinalMethod + false + + + + #FinalMethod + You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this‚Äîa number of its methods are final.You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. + + + + #FinalMethodDefintion + true + + + + #FinalMethodDefintion + You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this‚Äîa number of its methods are final.You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. + + + + #FinalModifier + true + + + + #FinalModifier + You can prevent others from extending your class by making it final using the keyword final in the class declaration.Note that you can also declare an entire class final ‚Äî this prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class.You can prefix a variable declaration with the keyword final to make its value unchangeable. You can make both local variables and class fields final. 1. Once assigned a value, the final value cannot change. 2. Attempting to change it will result in a compile error.The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):static final double PI = 3.141592653589793;Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).Note:¬†If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this‚Äîa number of its methods are final.You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. + + + + #FloatDataType + true + + + + #FloatDataType + float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform. single-precision floating-point type in Java for number form -10^38 to 10^38 and up to 7 significant deciam digits (reserved word "float")^^http://www.w3.org/2001/XMLSchema#string + + + + #FloatValue + true + + + + #FloatValue + A floating-point literal has the following parts: a whole-number part, a decimal point (represented by an ASCII period character), a fractional part, an exponent, and a type suffix. The exponent, if present, is indicated by the ASCII letter e or E followed by an optionally signed integer.At least one digit, in either the whole number or the fraction part, and either a decimal point, an exponent, or a float type suffix are required. All other parts are optional.A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; + + + + #ForEachStatement + true + + + + #ForEachStatement + The general form of the for-each version of the for is shown here:for(type itr-var : iterableObj) statement-blockThe object referred to by iterableObj must be an array or an object that implements the new Iterable interface.The for-each loop is essentially read-onlyUsing the For-Each Loop with CollectionsUsing 'for each' to loop through arrayThe for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:int[] numbers = {1,2,3,4,5,6,7,8,9,10};The following program, EnhancedForDemo, uses the enhanced for to loop through the array:for-each loop (enhanced for loop) available starting from Java 5.0^^http://www.w3.org/2001/XMLSchema#string + + + + #ForStatement + true + + + + #ForStatement + The for statement is like the while statement, i.e. you use it to create loop. The for statement has following syntax: 1. init is an initialization that will be performed before the first iteration. 2. booleanExpression is a boolean expression which will cause the execution of statement(s) if it evaluates to true. 3. update is a statement that will be executed after the execution of the statement block. 4. init, expression, and update are optional.The for statement will stop only if one of the following conditions is met: 1. booleanExpression evaluates to false 2. A break or continue statement is executed 3. A runtime error occurs. It is common to declare a variable and assign a value to it in the initialization part. The variable declared will be visible to the expression and update parts as well as to the statement block.For example, the following for statement loops five times and each time prints the value of i. Note that the variable i is not visible anywhere else since it is declared within the for loop.The initialization part of the for statement is optional.The update statement is optional.You can even omit the booleanExpression part.If you compare for and while, you'll see that you can always replace the while statement with for. This is to say thatThe for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:for (initialization; termination; increment) { statement(s)}When using this version of the for statement, keep in mind that: ‚Ä¢ The initialization expression initializes the loop; it's executed once, as the loop begins. ‚Ä¢ When the termination expression evaluates to false, the loop terminates. ‚Ä¢ The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.The three expressions of the for loop are optional; an infinite loop can be created as follows:for ( ; ; ) { // infinite loop // your code goes here}The for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.A for statement is executed by first executing the ForInit code: ‚Ä¢ If the ForInit code is a list of statement expressions (¬ß14.8), the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the for statement completes abruptly for the same reason; any ForInit statement expressions to the right of the one that completed abruptly are not evaluated.If the ForInit code is a local variable declaration, it is executed as if it were a local variable declaration statement (¬ß14.4) appearing in a block. The scope of a local variable declared in the ForInit part of a for statement (¬ß14.13) includes all of the following: ‚Ä¢ Its own initializer ‚Ä¢ Any further declarators to the right in the ForInit part of the for statement ‚Ä¢ The Expression and ForUpdate parts of the for statement ‚Ä¢ The contained StatementIf execution of the local variable declaration completes abruptly for any reason, the for statement completes abruptly for the same reason. ‚Ä¢ If the ForInit part is not present, no action is taken. Next, a for iteration step is performed, as follows: ‚Ä¢ If the Expression is present, it is evaluated, and if evaluation of the Expression completes abruptly, the for statement completes abruptly for the same reason. Otherwise, there is then a choice based on the presence or absence of the Expression and the resulting value if the Expression is present: ‚ó¶ If the Expression is not present, or it is present and the value resulting from its evaluation is true, then the contained Statement is executed. Then there is a choice: ‚ñ™ If execution of the Statement completes normally, then the following two steps are performed in sequence: ‚ñ™ First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the for statement completes abruptly for the same reason; any ForUpdate statement expressions to the right of the one that completed abruptly are not evaluated. If the ForUpdate part is not present, no action is taken. ‚ñ™ Second, another for iteration step is performed. ‚ñ™ If execution of the Statement completes abruptly, see ¬ß14.13.3 below. ‚ó¶ If the Expression is present and the value resulting from its evaluation is false, no further action is taken and the for statement completes normally.If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement.for loop (counter)^^http://www.w3.org/2001/XMLSchema#string + + + + #FormalMethodParameter + true + + + + #FormalMethodParameter + Parameters You've already seen examples of parameters, both in the Bicycle class and in the main method of the "Hello World!" application. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the tutorial. Primitive variables are passed by value.# When you pass a primitive variable, the JVM will copy the value of the passed-in variable to a new local variable.# If you change the value of the local variable, the change will not affect the passed in primitive variable.reference variables are passed by reference.# If you pass a reference variable, the local variable will refer to the same object as the passed in reference variable.# If you change the object referenced within your method, the change will also be reflected in the calling code.The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.Note:¬†Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and arrays.Here's an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y coordinate):When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor.A parameter can have the same name as one of the class's fields. If this is the case, the parameter is said to shadow the field. Shadowing fields can make your code difficult to read and is conventionally used only within constructors and methods that set a particular field. For example, consider the following Circle class and its setOrigin method: + + + + #GenericClass + false + + + + #GenericClass + Let's update our Box class to use generics. We'll first create a generic type declaration by changing the code "public class Box" to "public class Box<T>"; this introduces one type variable, named T, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There's nothing particularly complex about this concept. In fact, it's quite similar to what you already know about variables in general. Just think of T as a special kind of variable, whose "value" will be whatever type you pass in; this can be any class type, any interface type, or even another type variable. It just can't be any of the primitive data types. In this context, we also say that T is a formal type parameter of the Box class.As you can see, we've replaced all occurrences of Object with T. To reference this generic class from within your own code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:It's important to understand that type variables are not actually types themselves. In the above examples, you won't find T.java or T.class anywhere on the filesystem. Furthermore, T is not a part of the Box class name. In fact during compilation, all generic information will be removed entirely, leaving only Box.class on the filesystem. We'll discuss this later in the section on Type ErasureAlso note that a generic type may have multiple type parameters, but each parameter must be unique within its declaring class or interface. A declaration of Box<T,T>, for example, would generate an error on the second occurrence of T, but Box<T,U>, however, would be allowed.Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared.Here we've added one generic method, named inspect, that defines one type parameter, named U. This method accepts an object and prints its type to standard output. For comparison, it also prints out the type of T. For convenience, this class now also has a main method so that it can be run as an application.A more realistic use of generic methods might be something like the following, which defines a static method that stuffs references to a single item into multiple boxes:To use this method, your code would look something like the following:The complete syntax for invoking this method is:Here we've explicitly provided the type to be used as U, but more often than not, this can be left out and the compiler will infer the type that's needed:This feature, known as type inference, allows you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets. + + + + #GenericClassDefinition + true + + + + #GenericClassDefinition + Let's update our Box class to use generics. We'll first create a generic type declaration by changing the code "public class Box" to "public class Box<T>"; this introduces one type variable, named T, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There's nothing particularly complex about this concept. In fact, it's quite similar to what you already know about variables in general. Just think of T as a special kind of variable, whose "value" will be whatever type you pass in; this can be any class type, any interface type, or even another type variable. It just can't be any of the primitive data types. In this context, we also say that T is a formal type parameter of the Box class.As you can see, we've replaced all occurrences of Object with T. To reference this generic class from within your own code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:It's important to understand that type variables are not actually types themselves. In the above examples, you won't find T.java or T.class anywhere on the filesystem. Furthermore, T is not a part of the Box class name. In fact during compilation, all generic information will be removed entirely, leaving only Box.class on the filesystem. We'll discuss this later in the section on Type ErasureAlso note that a generic type may have multiple type parameters, but each parameter must be unique within its declaring class or interface. A declaration of Box<T,T>, for example, would generate an error on the second occurrence of T, but Box<T,U>, however, would be allowed.Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared.Here we've added one generic method, named inspect, that defines one type parameter, named U. This method accepts an object and prints its type to standard output. For comparison, it also prints out the type of T. For convenience, this class now also has a main method so that it can be run as an application.A more realistic use of generic methods might be something like the following, which defines a static method that stuffs references to a single item into multiple boxes:To use this method, your code would look something like the following:The complete syntax for invoking this method is:Here we've explicitly provided the type to be used as U, but more often than not, this can be left out and the compiler will infer the type that's needed:This feature, known as type inference, allows you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets. + + + + #GenericObjectCreationStatement + true + + + + #GenericObjectCreationStatement + You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you're passing a type argument ‚Äî Integer in this case ‚Äî to the Box class itself. Like any other variable declaration, this code does not actually create a new Box object. It simply declares that integerBox will hold a reference to a "Box of Integer", which is how Box<Integer> is read.An invocation of a generic type is generally known as a parameterized type.To instantiate this class, use the new keyword, as usual, but place <Integer> between the class name and the parenthesis:Or, you can put the entire statement on one line, such as:Box<Integer> integerBox = new Box<Integer>();Once integerBox is initialized, you're free to invoke its get method without providing a cast, as in BoxDemo3:Furthermore, if you try adding an incompatible type to the box, such as String, compilation will fail, alerting you to what previously would have been a runtime bug: + + + + #GotoStatement + true + + + + #GotoStatement + go-to statement (the most hated programming statement) + + + + #GreaterEqualExpression + true + + + + #GreaterEqualExpression + The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.The type of a relational expression is always boolean.Numerical Comparison Operators <, <=, >, and >= ‚Ä¢ The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.Greater than or equal to '>='^^http://www.w3.org/2001/XMLSchema#string + + + + #GreaterExpression + true + + + + #GreaterExpression + The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.The type of a relational expression is always boolean.Numerical Comparison Operators <, <=, >, and >= ‚Ä¢ The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.Greater than '>'^^http://www.w3.org/2001/XMLSchema#string + + + + #Identifier + false + + + + #IfElseIfStatement + true + + + + #IfElseIfStatement + if-else-if statement (conditional statement with many options - switch substitute) + + + + #IfElseStatement + true + + + + #IfElseStatement + The if statement is a conditional branch statement. The syntax of the if statement is either one of these twoIn the following example, the if block will be executed if a is greater than 3. Otherwise, the else block will be executed.The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.An if-then-else statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, then the if-then-else statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value: ‚Ä¢ If the value is true, then the first contained Statement (the one before the else keyword) is executed; the if-then-else statement completes normally if and only if execution of that statement completes normally. ‚Ä¢ If the value is false, then the second contained Statement (the one after the else keyword) is executed; the if-then-else statement completes normally if and only if execution of that statement completes normally.if-else statement (conditional statement with two options)^^http://www.w3.org/2001/XMLSchema#string + + + + #IfStatement + true + + + + #IfStatement + The if statement is a conditional branch statement. The syntax of the if statement is either one of these twoFor example, in the following if statement, the if block will be executed if x is greater than 4.The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion.f this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.An if-then statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the if-then statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value: ‚Ä¢ If the value is true, then the contained Statement is executed; the if-then statement completes normally if and only if execution of the Statement completes normally. ‚Ä¢ If the value is false, no further action is taken and the if-then statement completes normally.simple if statement (conditional statement with one option)^^http://www.w3.org/2001/XMLSchema#string + + + + #ImplementsSpecification + true + + + + #ImplementsSpecification + As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. An implementation class has to override all methods in the interface. 2. A class can implement multiple interfaces. + + + + #ImplicitTypeCasting + true + + + + #ImplicitTypeCasting + Every expression written in the Java programming language has a type that can be deduced from the structure of the expression and the types of the literals, variables, and methods mentioned in the expression. It is possible, however, to write an expression in a context where the type of the expression is not appropriate. In some cases, this leads to an error at compile time; for example, if the expression in an if statement (¬ß14.9) has any type other than boolean, a compile-time error occurs. In other cases, the context may be able to accept a type that is related to the type of the expression; as a convenience, rather than requiring the programmer to indicate a type conversion explicitly, the language performs an implicit conversion from the type of the expression to a type acceptable for its surrounding context.Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of an identity conversion (¬ß5.1.1) or a widening primitive conversion (¬ß5.1.2).Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. The two kinds of numeric promotion are unary numeric promotion (¬ß5.6.1) and binary numeric promotion (¬ß5.6.2). The analogous conversions in C are called "the usual unary conversions" and "the usual binary conversions."Numeric promotion is not a general feature of the Java programming language, but rather a property of the specific definitions of the built-in operations. + + + + #ImportStatement + true + + + + #ImportStatement + Java provides the keyword import to indicate that you want to use a package or a class from a package. For example, to use the java.io.File class, you must have the following import statement: 1. 'import' statements must come after the package statement but before the class declaration. 2. The import keyword can appear multiple times in a class. You can import all classes in the same package by using the wild character *. For example, the following code imports all members of the java.io package. However, to make your code more readable, it is recommended that you import a package member one at a time. Members of the java.lang package are imported automatically. Thus, to use the java.lang.String, for example, you do not need to explicitly import the class.The only way to use classes that belong to other packages without importing them is to use the fully qualified names of the classes in your code. For example, the following code declares the java.io.File class using its fully qualified name.If you class import identically-named classes from different packages, you must use the fully qualified names when declaring the classes. For example, the Java core libraries contain the classes java.sql.Date and java.util.Date. In this case, you must write the fully qualified names of java.sql.Date and java.util.Date to use them.The types that comprise a package are known as the package members.To use a public package member from outside its package, you must do one of the following: ‚Ä¢ Refer to the member by its fully qualified name ‚Ä¢ Import the package member ‚Ä¢ Import the member's entire packageEach is appropriate for different situations, as explained in the sections that follow.So far, most of the examples in this tutorial have referred to types by their simple names, such as Rectangle and StackOfInts. You can use a package member's simple name if the code you are writing is in the same package as that member or if that member has been imported.However, if you are trying to use a member from a different package and that package has not been imported, you must use the member's fully qualified name, which includes the package name. Here is the fully qualified name for the Rectangle class declared in the graphics package in the previous example.You could use this qualified name to create an instance of graphics.Rectangle:Qualified names are all right for infrequent use. When a name is used repetitively, however, typing the name repeatedly becomes tedious and the code becomes difficult to read. As an alternative, you can import the member or its package and then use its simple name.To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here's how you would import the Rectangle class from the graphics package created in the previous section.import graphics.Rectangle;Now you can refer to the Rectangle class by its simple name.Rectangle myRectangle = new Rectangle();This approach works well if you use just a few members from the graphics package. But if you use many types from a package, you should import the entire package.To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character.import graphics.*;Now you can refer to any class or interface in the graphics package by its simple name.The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the graphics package that begin with A.Instead, it generates a compiler error. With the import statement, you generally import only a single package member or an entire package.Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its nested classes by using the following two statements.For convenience, the Java compiler automatically imports three entire packages for each source file: (1) the package with no name, (2) the java.lang package, and (3) the current package (the package for the current file). + + + + #IncrementDecrementExpression + false + + + + #IncrementDecrementExpression + Incremenet and decrement operators + + + + #Inheritance + true + + + + #Inheritance + Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:A diagram of classes in a hierarchy.A hierarchy of bicycle classes.The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here}This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass. 1. You extend a class by creating a new class. 2. The former and the latter will then have a parent-child relationship. 3. The original class is the parent class or the base class or the superclass. 4. The new class is called a child class or a subclass or a derived class of the parent. 5. The process of extending a class in object-oriented programming is called inheritance. 6. In a subclass you can add new methods and new fields as well as override existing methods in the parent class to change their behaviors. 7. Inheritance gives you the opportunity to add some functionality that does not exist in the original class. 8. Inheritance can also change the behaviors of the existing class to better suit your needs. 9. The subclass and the superclass has an "is-a" relationship. Within a subclass you can access its superclass's public and protected methods and fields , but not the superclass's private methods. If the subclass and the superclass are in the same package, you can also access the superclass's default methods and fields.In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.Inheritance is a way to form new classes using classes that have already been defined. +It provides a mechanism for organizing and structuring classes into hierarchies.^^http://www.w3.org/2001/XMLSchema#string + + + + #InheritanceBasedPolymorphism + true + + + + #InheritanceBasedPolymorphism + It means the ability of a single variable of a given type to be used to reference objects of different types and to automatically call the method that is specific to the type of object the variable references.polymorphism works with derived class objects.When a subclasses overrride methods of a superclass, a variable declared as asuperclass will invoke differnt methods depending on the actual sublcass type of the obejct referred by the variable^^http://www.w3.org/2001/XMLSchema#string + + + + #InnerClass + false + + + + #InnerClassDefinition + true + + + + #InnerClassDefinition + An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (¬ß8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (¬ß15.28).To illustrate these rules, consider the example below:Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language. Member interfaces (¬ß8.5) are always implicitly static so they are never considered to be inner classes. + + + + #InstanceField + true + + + + #InstanceField + Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another. 1. Fields are variables. 2. They can be primitives or references to objects.For example, the Employee class has two fields, age and salary. 1. Field names should follow the camel naming convention. 2. The initial of each word in the field, except for the first word, is written with a capital letter. 3. For example: age, maxAge, address, validAddress, numberOfRows. Member variables in a class‚Äîthese are called fields. The Bicycle class uses the following lines of code to define its fields:public int cadence;public int gear;public int speed;Field declarations are composed of three components, in order: 1. Zero or more modifiers, such as public or private. 2. The field's type. 3. The field's name.The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class.Objects store their individual states in the fields declared without the static keyword. Instance fields are also known as instance variables because their values are unique to each instance of a class (to each object).^^http://www.w3.org/2001/XMLSchema#string + + + + #InstanceFieldDefinitionStatement + true + + + + #InstanceFieldDefinitionStatement + 1. Fields are variables. 2. They can be primitives or references to objects.For example, the Employee class has two fields, age and salary. 1. Field names should follow the camel naming convention. 2. The initial of each word in the field, except for the first word, is written with a capital letter. 3. For example: age, maxAge, address, validAddress, numberOfRows. Member variables in a class‚Äîthese are called fields. The Bicycle class uses the following lines of code to define its fields:public int cadence;public int gear;public int speed;Field declarations are composed of three components, in order: 1. Zero or more modifiers, such as public or private. 2. The field's type. 3. The field's name.The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class. + + + + #InstanceFieldInitializationStatement + true + + + + #InstanceFieldInvocation + true + + + + #InstanceOfExpression + true + + + + #InstanceOfExpression + The Type Comparison Operator instanceofThe instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface. The type of a RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The ReferenceType mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs.At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (¬ß15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.Checks whether the object is an instance of a class +(More spesifically, whether the object/interface variable stores a reference to the object of this particular class or one one of its subclasses)^^http://www.w3.org/2001/XMLSchema#string + + + + #IntDataType + true + + + + #IntDataType + int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead. integer data type for numbers between -2,147,483,648 and 2,147,483,647 (reserved word "int")^^http://www.w3.org/2001/XMLSchema#string + + + + #IntValue + true + + + + #IntValue + The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.The values of the integral types are integers in the following ranges: ‚Ä¢ For byte, from -128 to 127, inclusive ‚Ä¢ For short, from -32768 to 32767, inclusive ‚Ä¢ For int, from -2147483648 to 2147483647, inclusive ‚Ä¢ For long, from -9223372036854775808 to 9223372036854775807, inclusive ‚Ä¢ For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535 + + + + #Interface + false + + + + #InterfaceBasedPolymorphism + true + + + + #InterfaceBasedPolymorphism + The compile time type of a variable is always declared, and the compile time type of an expression can be deduced at compile time. The compile time type limits the possible values that the variable can hold or the expression can produce at run time. If a run-time value is a reference that is not null, it refers to an object or array that has a class, and that class will necessarily be compatible with the compile-time type.Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements (¬ß8.1.4) that interface.An object varibale declared using an interface type will invoke differnt methods depending on the actual class of the object reffered by the variable ^^http://www.w3.org/2001/XMLSchema#string + + + + #InterfaceBody + true + + + + #InterfaceClassConversion + true + + + + #InterfaceDataType + true + + + + #InterfaceDataType + Interface as a data type + + + + #InterfaceDefinition + true + + + + #InterfaceDefinition + As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. The interface should be regarded as a contract between a service provider and its clients. 4. In Java, the interface is a type.Follow this format to write an interface:1. Fields in an interface must be initialized and are implicitly public, static, and final. 2. You declare methods in an interface just as you would in a class. 3. Methods in an interface do not have a body. 4. All methods are implicitly public and abstractThere are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile‚Äîstop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated‚Äîthey can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.Defining an interface is similar to creating a new class:Note that the method signatures have no braces and are terminated with a semicolon.An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body. For example:The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.The interface body contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon, but no braces, because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public, so the public modifier can be omitted.An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted. + + + + #InterfaceImplementation + false + + + + #InterfaceImplementation + As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. An implementation class has to override all methods in the interface. 2. A class can implement multiple interfaces.To use an interface, you write a class that implements the interface. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. For example,To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.By convention, the implements clause follows the extends clause, if there is one.If you want to be able to compare the size of similar objects, no matter what they are, the class that instantiates them should implement Relatable.Any class can implement Relatable if there is some way to compare the relative "size" of objects instantiated from the class. For strings, it could be number of characters; for books, it could be number of pages; for students, it could be weight; and so forth. For planar geometric objects, area would be a good choice (see the RectanglePlus class that follows), while volume would work for three-dimensional geometric objects. All such classes can implement the isLargerThan() method.If you know that a class implements Relatable, then you know that you can compare the size of the objects instantiated from that class.Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable.Because RectanglePlus implements Relatable, the size of any two RectanglePlus objects can be compared + + + + #InterfaceName + true + + + + #InterfaceSignature + true + + + + #Interfacing + false + + + + #Interfacing + As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. The interface should be regarded as a contract between a service provider and its clients. 4. In Java, the interface is a type.Follow this format to write an interface:1. Fields in an interface must be initialized and are implicitly public, static, and final. 2. You declare methods in an interface just as you would in a class. 3. Methods in an interface do not have a body. 4. All methods are implicitly public and abstractThere are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile‚Äîstop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated‚Äîthey can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.Defining an interface is similar to creating a new class:Note that the method signatures have no braces and are terminated with a semicolon.^^http://www.w3.org/2001/XMLSchema#string + + + + #IterationStatement + false + + + + #IterationStatement + Java itereation (loop) statements + + + + #Java + false + + + + #Java + Abstract superconcept of Java + + + + #JavaDatabaseAccess + true + + + + #JavaDatabaseAccess + Java and Relational Databases + + + + #JavaLanguage + false + + + + #JavaLanguage + false + + + + #JavaLanguage + Superconcept of Java Programming Language. It combines Java syntax, data processing, structure of java programs, etc + + + + #JavaNetworking + true + + + + #JavaNetworking + Programming networking applications iin Java + + + + #JavaOOP + false + + + + #JavaOOP + Object-oriented programming iin Java + + + + #JavaPortability + true + + + + #JavaPortability + Portability issues of Java + + + + #JavaSequirity + true + + + + #JavaSequirity + Sequirity issues in Java + + + + #JavaStandardLibrary + false + + + + #JavaStandardLibrary + Java Standard Edition API Specification, Java SDK + + + + #JavaStandardLibraryClass + true + + + + #JavaStandardLibraryInterface + true + + + + #JavaStandardLibraryMethod + true + + + + #JavaStandardLibraryObject + true + + + + #JavaStandardLibraryPackage + true + + + + #JavaStandardLibraryPackage + A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. + + + + #JavaTechnology + false + + + + #JavaTechnology + Spesific aspects of Java tehcnology + + + + #JavaXMLProcessing + true + + + + #JavaXMLProcessing + XML parsing, genenration and processing in Java + + + + #JumpStatement + false + + + + #JumpStatement + Java jump statements + + + + #LessEqualExpression + true + + + + #LessEqualExpression + The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.The type of a relational expression is always boolean.Numerical Comparison Operators <, <=, >, and >= ‚Ä¢ The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.Less than or equal to '<='^^http://www.w3.org/2001/XMLSchema#string + + + + #LessExpression + true + + + + #LessExpression + The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.The type of a relational expression is always boolean.Numerical Comparison Operators <, <=, >, and >= ‚Ä¢ The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.Less than '<'^^http://www.w3.org/2001/XMLSchema#string + + + + #LogicalExpression + false + + + + #LogicalExpression + Logical operators. The result of logical expressions have type boolean + + + + #LongDataType + true + + + + #LongDataType + long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. integer data type for numbers between -9,223.372,036,854,808 and 9,223.372,036,854,807 (reserved word "long")^^http://www.w3.org/2001/XMLSchema#string + + + + #LongValue + true + + + + #LongValue + The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.The values of the integral types are integers in the following ranges: ‚Ä¢ For byte, from -128 to 127, inclusive ‚Ä¢ For short, from -32768 to 32767, inclusive ‚Ä¢ For int, from -2147483648 to 2147483647, inclusive ‚Ä¢ For long, from -9223372036854775808 to 9223372036854775807, inclusive ‚Ä¢ For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535 + + + + #MainMethod + false + + + + #MainMethodDefintion + true + + + + #MainMethodDefintion + 1. A special method called main provides the entry point to an application. 2. An application can have many classes and only one of the classes needs to have the method main. 3. This method allows the class containing it to be invoked. + + + + #Method + false + + + + #MethodBody + true + + + + #MethodDefinition + true + + + + #MethodDefinition + 1. ethods define actions that a class's objects (or instances) can do. 2. A method has a declaration part and a body. 3. The declaration part consists of a return value, the method name, and a list of arguments. 4. The body contains code that perform the action. 5. The return type of a method can be a primitive, an object, or void. 6. The return type void means that the method returns nothing. 7. The declaration part of a method is also called the signature of the method.For example, here is the getSalary method that returns a double.Here is an example of a typical method declaration:public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) { //do the calculation here}The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}.More generally, method declarations have six components, in order: 1. Modifiers‚Äîsuch as public, private, and others you will learn about later. 2. The return type‚Äîthe data type of the value returned by the method, or void if the method does not return a value. 3. The method name‚Äîthe rules for field names apply to method names as well, but the convention is a little different. 4. The parameter list in parenthesis‚Äîa comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. 5. An exception list‚Äîto be discussed later. 6. The method body, enclosed between braces‚Äîthe method's code, including the declaration of local variables, goes here.Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.Definition:¬†Two of the components of a method declaration comprise the method signature‚Äîthe method's name and the parameter types.The signature of the method declared above is:calculateAnswer(double, int, double, double) + + + + #MethodImplementation + true + + + + #MethodInheritance + true + + + + #MethodInheritance + In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, with four fields and five methods. However, you didn't have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:The inherited fields can be used directly, just like any other fields.The inherited methods can be used directly as they are.Subclass inherits all methods of the superclass. ^^http://www.w3.org/2001/XMLSchema#string + + + + #MethodInvocation + false + + + + #MethodInvocationStatement + true + + + + #MethodInvocationStatement + You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:The first statement invokes rectOne's getArea() method and displays the results. The second line moves rectTwo because the move() method assigns new values to the object's origin.x and origin.y.As with instance fields, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. The new operator returns an object reference, so you can use the value returned from new to invoke a new object's methods:The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As shown, you can use the dot notation to invoke the new Rectangle's getArea() method to compute the area of the new rectangle.Some methods, such as getArea(), return a value. For methods that return a value, you can use the method invocation in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle:Remember, invoking a method on a particular object is the same as sending a message to that object. In this case, the object that getArea() is invoked on is the rectangle returned by the constructor.You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:The first statement invokes rectOne's getArea() method and displays the results. The second line moves rectTwo because the move() method assigns new values to the object's origin.x and origin.y.As with instance fields, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. The new operator returns an object reference, so you can use the value returned from new to invoke a new object's methods:The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As shown, you can use the dot notation to invoke the new Rectangle's getArea() method to compute the area of the new rectangle.Some methods, such as getArea(), return a value. For methods that return a value, you can use the method invocation in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle:Remember, invoking a method on a particular object is the same as sending a message to that object. In this case, the object that getArea() is invoked on is the rectangle returned by the constructor. + + + + #MethodName + true + + + + #MethodName + Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples: + + + + #MethodOverloading + Java allows you to have multiple methods having the same name, as long as each method accept different sets of argument types. In other words, in our example, it is legal to have these two methods in the same class.This technique is called method overloading. The return value of the method is not taken into consideration. As such, these two methods must not exist in the same class:A method's name with the types and sequence of the parameters form the method's signatureTypically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method‚Äîfor example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list.Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type. + + + + #MethodOverriding + true + + + + #MethodOverriding + 1. When you extends a class, you can change the behavior of a method in the parent class. 2. This is called method overriding. 3. This happens when you write in a subclass a method that has the same signature as a method in the parent class. 4. If only the name is the same but the list of arguments is not, then it is method overloading.An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error.Subclass can override methods of the superclass if these methods should behave differently for the objects fot eh subclass.^^http://www.w3.org/2001/XMLSchema#string + + + + #MethodSignature + true + + + + #Modifier + false + + + + #ModulusAssignmentExpression + true + + + + #ModulusAssignmentExpression + All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Find the reminder of the division of the value of the varibale to the left by the value of the expression to the right and assigns the result to the variable to the left '=%'^^http://www.w3.org/2001/XMLSchema#string + + + + #ModulusExpression + true + + + + #ModulusExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result. % remainder operatorThe binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.In Java programming language, it also accepts floating-point operands.The remainder operation for operands that are integers after binary numeric promotion (¬ß5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor. If the value of the divisor for an integer remainder operator is 0, then an ArithmeticException is thrown.The result of a floating-point remainder operation as computed by the % operator is not the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding division, not a truncating division, and so its behavior is not analogous to that of the usual integer remainder operator. Instead, the Java programming language defines % on floating-point operations to behave in a manner analogous to that of the integer remainder operator; this may be compared with the C library function fmod.Division reminder operator '%'^^http://www.w3.org/2001/XMLSchema#string + + + + #MultiplicativeExpression + false + + + + #MultiplicativeExpression + Multiplicative operators '*' '/' '%' + + + + #MultiplyAssignmentExpression + true + + + + #MultiplyAssignmentExpression + All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Multiply the value of the varibale to the left by the value of the expression to the right and assigns the result to the variable to the left '=*'^^http://www.w3.org/2001/XMLSchema#string + + + + #MultiplyExpression + true + + + + #MultiplyExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. * multiplication operatorThe binary * operator performs multiplication, producing the product of its operands. Multiplication is a commutative operation if the operand expressions have no side effects. While integer multiplication is associative when the operands are all of the same type, floating-point multiplication is not associative.If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.Multiplication Operator '-'^^http://www.w3.org/2001/XMLSchema#string + + + + #NestedStatement + true + + + + #NestedStatement + nested statement (statement inside another statement) + + + + #NotEqualExpression + true + + + + #NotEqualExpression + The equality operators are syntactically left-associative (they group left-to-right), but this fact is essentially never useful; for example, a==b==c parses as (a==b)==c. The result type of a==b is always boolean, and c must therefore be of type boolean or a compile-time error occurs. Thus, a==b==c does not test to see whether a, b, and c are all equal.The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, a<b==c<d is true whenever a<b and c<d have the same truth value.The equality operators may be used to compare two operands of numeric type, or two operands of type boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always boolean.In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative if the operand expressions have no side effects.Logical inequality (not-equal-to operator) '!='^^http://www.w3.org/2001/XMLSchema#string + + + + #NotExpression + true + + + + #NotExpression + The type of the operand expression of the unary ! operator must be boolean, or a compile-time error occurs. The type of the unary logical complement expression is boolean.At run time, the value of the unary logical complement expression is true if the operand value is false and false if the operand value is true.Boolean (Logical) NOT '!'^^http://www.w3.org/2001/XMLSchema#string + + + + #OOPPrinciple + false + + + + #Object + false + + + + #Object + Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.A circle with an inner circle filled with items, surrounded by gray wedges representing methods that allow access to the inner circle.A software object.Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation ‚Äî a fundamental principle of object-oriented programming.Consider a bicycle, for example:A picture of an object, with bibycle methods and instance variables.A bicycle modeled as a software object.By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.Bundling code into individual software objects provides a number of benefits, including: 1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. 2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. 3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code. 4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine. As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.Each of these statements has three parts (discussed in detail below): 1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. 2. Instantiation: The new keyword is a Java operator that creates the object. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life.^^http://www.w3.org/2001/XMLSchema#string + + + + #ObjectCreationStatement + true + + + + #ObjectCreationStatement + 1. Using the new keyword. 2. new is always followed by the constructor of the class.For example, to create an Employee object, you write:Here, 'employee' is an object reference of type Employee. 1. Once you have an object, you can call its methods and access its fields, by using the object reference. 2. You use a period (.) to call a method or a field.The following code, for instance, creates an Employee object and assigns values to its age and salary fields:When an object is created, the JVM also performs initialization that assign default values to fields.As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.Each of these statements has three parts (discussed in detail below): 1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. 2. Instantiation: The new keyword is a Java operator that creates the object. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object. The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.Note:¬†The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:This statement will be discussed in the next section.This class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as declared by the code (int a, int b). The following statement provides 23 and 94 as values for those arguments:A class instance creation expression is used to create new objects that are instances of classes.Class instance creation expressions have two forms:Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (¬ß15.9.5) and creates an instance of it.We say that a class is instantiated when an instance of the class is created by a class instance creation expression. Class instantiation involves determining what class is to be instantiated, what the enclosing instances (if any) of the newly created instance are, what constructor should be invoked to create the new instance and what arguments should be passed to that constructor.If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class.The type of the class instance creation expression is the class type being instantiated.At run time, evaluation of a class instance creation expression is as follows.First, if the class instance creation expression is a qualified class instance creation expression, the qualifying primary expression is evaluated. If the qualifying expression evaluates to null, a NullPointerException is raised, and the class instance creation expression completes abruptly. If the qualifying expression completes abruptly, the class instance creation expression completes abruptly for the same reason.Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError (¬ß15.9.6).The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (¬ß4.5.5).Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (¬ß8.8) and is described in detail in ¬ß12.5.The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.Object creation consists of object creation and a semicolon^^http://www.w3.org/2001/XMLSchema#string + + + + #ObjectEquality + true + + + + #ObjectEquality + If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (¬ß5.5). The run-time values of the two operands would necessarily be unequal.At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters. The contents of two strings s and t can be tested for equality by the method invocation s.equals(t)The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal‚Äîthat is, if the objects compared are the exact same object. + + + + #ObjectMethodInvocation + true + + + + #ObjectMethodInvocation + To call a method for a certain object you need to spesify the object and a the method separated by "." This operation calls to invoke a method. The method will operate on the data stored in object's fields and the parameters passed to the method. + + + + #ObjectReference + true + + + + #ObjectReference + An object is a class instance or an array.The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.A new class instance is implicitly created when the string concatenation operator + (¬ß15.18.1) is used in an expression, resulting in a new object of type String (¬ß4.3.3). A new array object is implicitly created when an array initializer expression (¬ß10.6) is evaluated; this can occur when a class or interface is initialized (¬ß12.4), when a new instance of a class is created (¬ß15.9), or when a local variable declaration statement is executed (¬ß14.4).There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable. + + + + #ObjectVariable + true + + + + #ObjectVariable + Variables are data placeholders. There are two data types in Java: 1. Reference types provides a reference to an object.Object varaibale storing a reference to the object representation in memory^^http://www.w3.org/2001/XMLSchema#string + + + + #Operator + false + + + + #Operator + Every expression in Java must have at least one operator + + + + #OperatorAssociativity + true + + + + #OperatorAssociativity + Associativity of operators (left to right or right to left) + + + + #OperatorPrecedence + true + + + + #OperatorPrecedence + As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left. If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated firstPrecedence of operators^^http://www.w3.org/2001/XMLSchema#string + + + + #OrExpression + true + + + + #OrExpression + The || operator is like | (¬ß15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)||(b))||(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)||((b)||(c)).Each operand of || must be of type boolean, or a compile-time error occurs. The type of a conditional-or expression is always boolean.At run time, the left-hand operand expression is evaluated first; if its value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated and its value becomes the value of the conditional-or expression.Thus, || computes the same result as | on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.Boolean (Logical) OR '||'^^http://www.w3.org/2001/XMLSchema#string + + + + #OverridingClone + true + + + + #OverridingClone + If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method to create a copy from an existing object. To create a clone, you write:aCloneableObject.clone();Object's implementation of this method checks to see whether the object on which clone() was invoked implements the Cloneable interface. If the object does not, the method throws a CloneNotSupportedException exception. Exception handling will be covered in a later lesson. For the moment, you need to know that clone() must be declared asprotected Object clone() throws CloneNotSupportedException -- or --public Object clone() throws CloneNotSupportedExceptionif you are going to write a clone() method to override the one in Object.If the object on which clone() was invoked does implement the Cloneable interface, Object's implementation of the clone() method creates an object of the same class as the original object and initializes the new object's member variables to have the same values as the original object's corresponding member variables.The simplest way to make your class cloneable is to add implements Cloneable to your class's declaration. then your objects can invoke the clone() method.For some classes, the default behavior of Object's clone() method works just fine. If, however, an object contains a reference to an external object, say ObjExternal, you may need to override clone() to get correct behavior. Otherwise, a change in ObjExternal made by one object will be visible in its clone also. This means that the original object and its clone are not independent‚Äîto decouple them, you must override clone() so that it clones the object and ObjExternal. Then the original object references ObjExternal and the clone references a clone of ObjExternal, so that the object and its clone are truly independent.clone() is one of the four basic methods of the Object class that should be overriden by any good-style class to avoid incorect clonning by inherited Object.clone()^^http://www.w3.org/2001/XMLSchema#string + + + + #OverridingEquals + true + + + + #OverridingEquals + The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal‚Äîthat is, if the objects compared are the exact same object.To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method. Here is an example of a Book class that overrides equals():Consider this code that tests two instances of the Book class for equality:This program displays objects are equal even though firstBook and secondBook reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number.You should always override the equals() method if the identity operator is not appropriate for your class.Note:¬†If you override equals(), you must override hashCode() as well.equals() is one of the four basic methods of the Object class that should be overriden by any good-style class to avoid incorect objecte comparison by inherited Object.equals()^^http://www.w3.org/2001/XMLSchema#string + + + + #OverridingHashCode + true + + + + #OverridingHashCode + The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.hashCode() is one of the four basic methods of the Object class that should be overriden by any good-style class to avoid incorect hash code computation by inherited Object.hashCode()^^http://www.w3.org/2001/XMLSchema#string + + + + #OverridingToString + true + + + + #OverridingToString + You should always consider overriding the toString() method in your classes.The Object's toString() method returns a String representation of the object, which is very useful for debugging. The String representation for an object depends entirely on the object, which is why you need to override toString() in your classes.You can use toString() along with System.out.println() to display a text representation of an object, such as an instance of Book:System.out.println(firstBook.toString());which would, for a properly overridden toString() method, print something useful, like this:toString() is one of the four basic methods of the Object class that should be overriden by any good-style class to avoid incorect printing of objects by inherited Object.toString()^^http://www.w3.org/2001/XMLSchema#string + + + + #Package + false + + + + #Package + A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. Java provides the keyword import to indicate that you want to use a package or a class from a package. For example, to use the java.io.File class, you must have the following import statement: 1. 'import' statements must come after the package statement but before the class declaration. 2. The import keyword can appear multiple times in a class. You can import all classes in the same package by using the wild character *. For example, the following code imports all members of the java.io package. However, to make your code more readable, it is recommended that you import a package member one at a time. Members of the java.lang package are imported automatically. Thus, to use the java.lang.String, for example, you do not need to explicitly import the class.The only way to use classes that belong to other packages without importing them is to use the fully qualified names of the classes in your code. For example, the following code declares the java.io.File class using its fully qualified name.If you class import identically-named classes from different packages, you must use the fully qualified names when declaring the classes. For example, the Java core libraries contain the classes java.sql.Date and java.util.Date. In this case, you must write the fully qualified names of java.sql.Date and java.util.Date to use them.To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages.A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.The types that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on. You can put your types in packages too.You should bundle these classes and the interface in a package for several reasons, including the following: ‚Ä¢ You and other programmers can easily determine that these types are related. ‚Ä¢ You and other programmers know where to find types that can provide graphics-related functions. ‚Ä¢ The names of your types won't conflict with the type names in other packages because the package creates a new namespace. ‚Ä¢ You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package. To create a package, you choose a name for the package (naming conventions are discussed in the next section) and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package. If you do not use a package statement, your type ends up in an unnamed package. Generally speaking, an unnamed package is only for small or temporary applications or when you are just beginning the development process. Otherwise, classes and interfaces belong in named packages. Package names are written in all lowercase to avoid conflict with the names of classes or interfaces.Companies use their reversed Internet domain name to begin their package names‚Äîfor example, com.example.orion for a package named orion created by a programmer at example.com.Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.company.region.package).Packages in the Java language itself begin with java. or javax.In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example: + + + + #PackageSpecificationStatement + true + + + + #PackageSpecificationStatement + A package declaration appears within a compilation unit to indicate the package to which the compilation unit belongs.A package declaration in a compilation unit specifies the name (¬ß6.2) of the package to which the compilation unit belongs. ‚Ä¢ PackageDeclaration: ‚Ä¢ package PackageName ; ‚Ä¢ The package name mentioned in a package declaration must be the fully qualified name (¬ß6.7) of the package. + + + + #Parenthesis + true + + + + #Parenthesis + Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence. An implementation may not take advantage of algebraic identities such as the associative law to rewrite expressions into a more convenient computational order unless it can be proven that the replacement expression is equivalent in value and in its observable side effects, even in the presence of multiple threads of execution (using the thread execution model in ¬ß17), for all possible computational values that might be involved.Parenthesis '(' ')' to change the default presedence of operators^^http://www.w3.org/2001/XMLSchema#string + + + + #PolymorphicObjectCreationStatement + true + + + + #Polymorphism + false + + + + #Polymorphism + Polymorphism assumes different behavior of an invoked method depending on the actual type of an object, which is determined at a run time + + + + #PostDecrementExpression + true + + + + #PostDecrementExpression + A postfix expression followed by a -- operator is a postfix decrement expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix decrement expression is the type of the variable. The result of the postfix decrement expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, then the postfix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (¬ß5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (¬ß5.1.3) to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable before the new value is stored.Post-decrement '--' decreases the value of the operand by one after the entire expression has been evaluated^^http://www.w3.org/2001/XMLSchema#string + + + + #PostIncrementExpression + true + + + + #PostIncrementExpression + The unary operators require only one operand; they perform various operations such as incrementing ++ Increment operator; increments a value by 1The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference. A postfix expression followed by a ++ operator is a postfix increment expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (¬ß5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (¬ß5.1.3) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.Post-increment '++' increases the value of the operand by one after the entire expression has been evaluated^^http://www.w3.org/2001/XMLSchema#string + + + + #PreDecrementExpression + true + + + + #PreDecrementExpression + A unary expression preceded by a -- operator is a prefix decrement expression. The result of the unary expression must be a variable of a numeric type, or a compile-time error occurs. The type of the prefix decrement expression is the type of the variable. The result of the prefix decrement expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, then the prefix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (¬ß5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (¬ß5.1.3) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.Pre-decrement '--' decreases the value of the operand by one before the rest of the expression has been evaluated^^http://www.w3.org/2001/XMLSchema#string + + + + #PreIncrementExpression + true + + + + #PreIncrementExpression + The unary operators require only one operand; they perform various operations such as incrementing ++ Increment operator; increments a value by 1The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference. A unary expression preceded by a ++ operator is a prefix increment expression. The result of the unary expression must be a variable of a numeric type, or a compile-time error occurs. The type of the prefix increment expression is the type of the variable. The result of the prefix increment expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (¬ß5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (¬ß5.1.3) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored.Pre-increment '++' increases the value of the operand by one before the rest of the expression has been evaluated^^http://www.w3.org/2001/XMLSchema#string + + + + #PrivateAccessSpecifier + true + + + + #PrivateAccessSpecifier + The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private. Other access modifiers will be discussed later. ‚Ä¢ private modifier‚Äîthe field is accessible only within its own class.In the spirit of encapsulation, it is common to make fields private. This means that they can only be directly accessed from the Bicycle class. We still need access to these values, however. This can be done indirectly by adding public methods that obtain the field values for us: + + + + #ProgramElementBody + false + + + + #ProgramElementDefinition + false + + + + #ProgramElementSignature + false + + + + #ProgramStructure + false + + + + #ProtectedAccessSpecifier + true + + + + #ProtectedAccessSpecifier + A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of CLet C be the class in which a protected constructor is declared and let S be the innermost class in whose declaration the use of the protected constructor occurs. + + + + #PublicAccessSpecifier + true + + + + #PublicAccessSpecifier + The first (left-most) modifier used lets you control what other classes have access to a member field.public modifier‚Äîthe field is accessible from all classes. + + + + #RelationalExpression + false + + + + #RelationalExpression + Relational operators compare the values of their operands + + + + #ReturnStatement + true + + + + #ReturnStatement + The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword. return ++count;The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value.A method returns to the code that invoked it when it ‚Ä¢ completes all the statements in the method, ‚Ä¢ reaches a return statement, or ‚Ä¢ throws an exception (covered later),whichever occurs first.You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: return; If you try to return a value from a method that is declared void, you will get a compiler error.Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.This method returns the integer that the expression width*height evaluates to.The area method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:A return statement returns control to the invoker of a method (¬ß8.4, ¬ß15.12) or constructor (¬ß8.8, ¬ß15.9). ‚Ä¢ ReturnStatement: ‚Ä¢ return Expressionopt ; ‚Ä¢ A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (¬ß8.4), or in the body of a constructor (¬ß8.8). A compile-time error occurs if a return statement appears within an instance initializer or a static initializer (¬ß8.7). A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it.To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value.A return statement with an Expression must be contained in a method declaration that is declared to return a value (¬ß8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable (¬ß5.2) to the declared result type of the method, or a compile-time error occurs.A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V. If the expression is of type float and is not FP-strict (¬ß15.4), then the value may be an element of either the float value set or the float-extended-exponent value set (¬ß4.2.3). If the expression is of type double and is not FP-strict, then the value may be an element of either the double value set or the double-extended-exponent value set.It can be seen, then, that a return statement always completes abruptly.The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (¬ß14.19) within the method or constructor whose try blocks contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.return statement (ends the method execution and returns (optionally) the result of the method)^^http://www.w3.org/2001/XMLSchema#string + + + + #ReturnedType + true + + + + #ReturnedType + A method returns to the code that invoked it when it ‚Ä¢ completes all the statements in the method, ‚Ä¢ reaches a return statement, or ‚Ä¢ throws an exception (covered later),whichever occurs first.You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: return; If you try to return a value from a method that is declared void, you will get a compiler error.Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.This method returns the integer that the expression width*height evaluates to.The area method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this: + + + + #ReturnedValue + false + + + + #ReturnedValue + A method returns to the code that invoked it when it ‚Ä¢ completes all the statements in the method, ‚Ä¢ reaches a return statement, or ‚Ä¢ throws an exception (covered later),whichever occurs first.You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: return; If you try to return a value from a method that is declared void, you will get a compiler error.Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.This method returns the integer that the expression width*height evaluates to.The area method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:the method returned value (the result of the method)^^http://www.w3.org/2001/XMLSchema#string + + + + #SAX + true + + + + #SelectionStatement + false + + + + #SelectionStatement + Java selection (decision, conditional) statements + + + + #ShortDataType + true + + + + #ShortDataType + short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. integer data type for numbers between -32,768 and 32,767 (reserved word "short")^^http://www.w3.org/2001/XMLSchema#string + + + + #ShortValue + true + + + + #SignedLeftShiftAssignmentExpression + true + + + + #SignedLeftShiftExpression + true + + + + #SignedRightShiftAssignmentExpression + true + + + + #SignedRightShiftExpression + true + + + + #SimpleAssignmentExpression + true + + + + #SimpleAssignmentExpression + One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:This operator can also be used on objects to assign object references, as discussed in Creating Objects. Simple (default, traditional) assignment '='^^http://www.w3.org/2001/XMLSchema#string + + + + #SimpleDataType + false + + + + #SimpleDataType + The Java programming language is staticaly-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen: int gear = 1;Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are: Java has eight primitive types of data: byte, short, int, long, char, float, double, and boolean.These can be put in four groups: 1. Integers includes byte, short, int, and long 2. Floating-point numbers includes float and double 3. Characters includes char, like letters and numbers. 4. Boolean includes boolean representing true/false values.Simple (fundamental, basic) data types^^http://www.w3.org/2001/XMLSchema#string + + + + #SimpleDataTypeValue + false + + + + #SimpleVariable + true + + + + #SimpleVariable + Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared ‚Äî which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Variables are data placeholders. There are two data types in Java: Primitive types hold a primitive.A local variable storing a value of a simple data type. Local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.^^http://www.w3.org/2001/XMLSchema#string + + + + #Specification + false + + + + #StandardIdentifier + true + + + + #Statement + false + + + + #Statement + 1. In programming, a statement is an instruction to do something. 2. It controls the sequence of execution of a program. 3. In Java, a statement is terminated with a semicolon and multiple statements can be written on a single line. Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution.Java programming statements (or instructions)^^http://www.w3.org/2001/XMLSchema#string + + + + #StatementBlock + true + + + + #StatementBlock + 1. You can have a block of statements enclosed between braces. 2. If the value of expression is true, all the statements enclosed in the block will be executed. 3. Without the braces, the code no longer has a statement block. A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.A block is a sequence of statements, local class declarations and local variable declaration statements within braces.A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.The scope of a local variable declaration in a block (¬ß14.2) is the rest of the block in which the declaration appears, starting with its own initializer (¬ß14.4) and including any further declarators to the right in the local variable declaration statement.The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. The name of a local variable v may not be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. However, a local variable of a method or initializer block may be shadowed (¬ß6.3.1) anywhere inside a class declaration nested within the scope of the local variable.A local variable cannot be referred to using a qualified name (¬ß6.6), only a simple name.A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.^^http://www.w3.org/2001/XMLSchema#string + + + + #StaticMethod + false + + + + #StaticMethod + 1. Static members are not tied to class instances. 2. Static members can be called without having an instance.The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as inA common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:Not all combinations of instance and class variables and methods are allowed: + + + + #StaticMethodDefinition + true + + + + #StaticMethodDefinition + 1. You can use the keyword static in front of a method declaration. 2. The static keyword may come before or after the access modifier. # From inside a static method, you cannot call instance methods or instance fields because they only exist after you create an object.# You can access other static methods or fields from a static method.The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as inA common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:Not all combinations of instance and class variables and methods are allowed: + + + + #StaticMethodInvocation + true + + + + #StaticMethodInvocation + If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified.The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in + + + + #StaticModifier + true + + + + #StaticModifier + 1. Static members are not tied to class instances. 2. Static members can be called without having an instance. 1. You can use the keyword static in front of a method declaration. 2. The static keyword may come before or after the access modifier. # From inside a static method, you cannot call instance methods or instance fields because they only exist after you create an object.# You can access other static methods or fields from a static method.In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles, as follows:Class variables are referenced by the class name itself, as inThis makes it clear that they are class variables.The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as inA common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:Not all combinations of instance and class variables and methods are allowed:The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):static final double PI = 3.141592653589793;Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).Note:¬†If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value. + + + + #StringAddition + true + + + + #StringAddition + The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program: class ConcatDemo { public static void main(String[] args){ String firstString = "This is"; String secondString = " a concatenated string."; String thirdString = firstString+secondString; System.out.println(thirdString); } }By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output. 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.Strings are more commonly concatenated with the +(addition) operator, as in"Hello," + " world" + "!"which results in"Hello, world!"The + operator is widely used in print statements. For example:Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.The Java programming language does not permit literal strings to span lines in source files, so you must use the + concatenation operator at the end of each line in a multi-line string. For example,Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a newly created String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.Any type may be converted to type String by string conversion.A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.Arithmetic addition of strings results in string concatenation. If only one of the arguments is string, it will be concatenated with the string representation of the second argument^^http://www.w3.org/2001/XMLSchema#string + + + + #StringDataType + true + + + + #StringDataType + In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Simple Data ObjectsStrings, 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.The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.The most direct way to create a string is to write:String greeting = "Hello world!";In this case, "Hello world!" is a string literal‚Äîa series of characters in your code that is enclosed in double quotes. 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 thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters: + + + + #StringInitializationStatement + true + + + + #StringInitializationStatement + The most direct way to create a string is to write:String greeting = "Hello world!";In this case, "Hello world!" is a string literal‚Äîa series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value‚Äîin this case, Hello world!Initialization of a String object by a string literal +String Initialization is a kind of variable initialialization^^http://www.w3.org/2001/XMLSchema#string + + + + #StringLiteral + true + + + + #StringLiteral + A string literal consists of zero or more characters enclosed in double quotes. Each character may be represented by an escape sequence.A string literal is always of type String (¬ß4.3.3. A string literal always refers to the same instance (¬ß4.3.1) of class String. + + + + #StringLiteralMethodInvocation + true + + + + #StringVariable + true + + + + #StringVariable + a variable of class String, storing a reference to the String representation in memory + + + + #Subclass + false + + + + #Subclass + Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:A diagram of classes in a hierarchy.A hierarchy of bicycle classes.The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here}This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, with four fields and five methods. However, you didn't have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members: ‚Ä¢ The inherited fields can be used directly, just like any other fields. ‚Ä¢ You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). ‚Ä¢ You can declare new fields in the subclass that are not in the superclass. ‚Ä¢ The inherited methods can be used directly as they are. ‚Ä¢ You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. ‚Ä¢ You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. ‚Ä¢ You can declare new methods in the subclass that are not in the superclass. ‚Ä¢ You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.The following sections in this lesson will expand on these topics. + + + + #SubtractAssignmentExpression + true + + + + #SubtractAssignmentExpression + All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Subtract the value of the expression to the right from the value of the varibale to the left and assigns the result to the variable to the left '=-"^^http://www.w3.org/2001/XMLSchema#string + + + + #SubtractExpression + true + + + + #SubtractExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. - subtraction operatorSubtraction Operator '-'^^http://www.w3.org/2001/XMLSchema#string + + + + #SuperReference + true + + + + #SuperReference + If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:Here is a subclass, called Subclass, that overrides printMethod():Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following: + + + + #Superclass + false + + + + #Superclass + Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:A diagram of classes in a hierarchy.A hierarchy of bicycle classes.The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here}This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass. + + + + #SuperclassConstructor + false + + + + #SuperclassConstructor + 1. You can explicitly call the parent's constructor from a subclass's constructor by using the super keyword. 2. 'super' must be the first statement in the constructor.^^http://www.w3.org/2001/XMLSchema#string + + + + #SuperclassConstructorCall + true + + + + #SuperclassConstructorCall + 1. You can explicitly call the parent's constructor from a subclass's constructor by using the super keyword. 2. 'super' must be the first statement in the constructor.The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example that MountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own:nvocation of a superclass constructor must be the first line in the subclass constructor.The syntax for calling a superclass constructor issuper(); --or--super(parameter list);With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.Note:¬†If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.Constructors of the subclasses must call the super constructor first to initialize inherited fields and then initialize new added fields of the subclass. To call the super constructor one shoudl use "super()"^^http://www.w3.org/2001/XMLSchema#string + + + + #SuperclassMethod + false + + + + #SuperclassMethod + to call methods of the superclass, if they are not overriden, one call them the way, the are implemented in the subclass, If a method has been overriden, then inside the sublcass one should use super refference. + + + + #SuperclassMethodCall + true + + + + #SuperclassMethodCall + The special forms using the keyword super are valid only in an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class; these are exactly the same situations in which the keyword this may be used (¬ß15.8.3). The forms involving super may not be used anywhere in the class Object, since Object has no superclass; if super appears in class Object, then a compile-time error results.Suppose that a field access expression super.name appears within class C, and the immediate superclass of C is class S. Then super.name is treated exactly as if it had been the expression ((S)this).name; thus, it refers to the field named name of the current object, but with the current object viewed as an instance of the superclass. Thus it can access the field named name that is visible in class S, even if that field is hidden by a declaration of a field named name in class C. + + + + #SuperclassSubclassConversion + true + + + + #SuperclassSubclassConversion + 1. With objects, you can cast an instance of a subclass to its parent class. 2. Casting an object to a parent class is called upcasting. To upcast a Child object, all you need to do is assign the object to a reference variable of type Parent. The parent reference variable cannot access the members that are only available in Child.Because parent references an object of type Child, you can cast it back to Child. It is called downcasting because you are casting an object to a class down the inheritance hierarchy. Downcasting requires that you write the child type in brackets. For example:We have seen that an object is of the data type of the class from which it was instantiated. For example, if we writepublic MountainBike myBike = new MountainBike();then myBike is of type MountainBike.MountainBike is descended from Bicycle and Object. Therefore, a MountainBike is a Bicycle and is also an Object, and it can be used wherever Bicycle or Object objects are called for.The reverse is not necessarily true: a Bicycle may be a MountainBike, but it isn't necessarily. Similarly, an Object may be a Bicycle or a MountainBike, but it isn't necessarily.Casting shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations. For example, if we writeObject obj = new MountainBike();then obj is both an Object and a Mountainbike (until such time as obj is assigned another object that is not a Mountainbike). This is called implicit casting.If, on the other hand, we writeMountainBike myBike = obj;we would get a compile-time error because obj is not known to the compiler to be a MountainBike. However, we can tell the compiler that we promise to assign a MountainBike to obj by explicit casting:MountainBike myBike = (MountainBike)obj;This cast inserts a runtime check that obj is assigned a MountainBike so that the compiler can safely assume that obj is a MountainBike. If obj is not a Mountainbike at runtime, an exception will be thrown.Note:¬†You can make a logical test as to the type of a particular object using the instanceof operator. This can save you from a runtime error owing to an improper cast. For example:if (obj instanceof MountainBike) { MountainBike myBike = (MountainBike)obj;}Here the instanceof operator verifies that obj refers to a MountainBike so that we can make the cast with knowledge that there will be no runtime exception thrown. + + + + #SwitchStatement + true + + + + #SwitchStatement + 1. An alternative to a series of else if is the switch statement. 2. The switch statement allows you to choose a block of statements to run from a selection of code, based on the return value of an expression. 3. The expression used in the switch statement must return an int or an enumerated value.The syntax of the switch statement is as follows.Failure to add a break statement after a case will not generate a compile error but may have more serious consequences because the statements on the next case will be executed.Here is an example of the switch statement:Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).The following program, SwitchDemo, declares an int named month whose value represents a month out of the year. The program displays the name of the month, based on the value of month, using the switch statement.The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case.The switch statement transfers control to one of several statements depending on the value of an expression.The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. These labels are said to be associated with the switch statement, as are the values of the constant expressions (¬ß15.28) in the case labels.All of the following must be true, or a compile-time error will result: ‚Ä¢ Every case constant expression associated with a switch statement must be assignable (¬ß5.2) to the type of the switch Expression. ‚Ä¢ No two of the case constant expressions associated with a switch statement may have the same value. ‚Ä¢ At most one default label may be associated with the same switch statement.switch statement (selector, multiple selection statement)^^http://www.w3.org/2001/XMLSchema#string + + + + #ThisReference + true + + + + #ThisReference + You use the this keyword from any method or constructor to refer to the current object.Within an instance method or a constructor, this is a reference to the current object ‚Äî the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.Each argument to the constructor shadows one of the object's fields ‚Äî inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.If present, the invocation of another constructor must be the first line in the constructor.The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.When used as a primary expression, the keyword this denotes a value, that is a reference to the object for which the instance method was invoked (¬ß15.12), or to the object being constructed.The keyword this is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body + + + + #ThrowStatement + true + + + + #ThrowStatement + A throw statement causes an exception (¬ß11) to be thrown. The result is an immediate transfer of control (¬ß11.3) that may exit multiple statements and multiple constructor, instance initializer, static initializer and field initializer evaluations, and method invocations until a try statement (¬ß14.19) is found that catches the thrown value. If no such try statement is found, then execution of the thread (¬ß17) that executed the throw is terminated (¬ß11.3) after invocation of the uncaughtException method for the thread group to which the thread belongs. ‚Ä¢ ThrowStatement: ‚Ä¢ throw Expression ; ‚Ä¢ The Expression in a throw statement must denote a variable or value of a reference type which is assignable (¬ß5.2) to the type Throwable, or a compile-time error occurs. Moreover, at least one of the following three conditions must be true, or a compile-time error occurs: ‚Ä¢ The exception is not a checked exception (¬ß11.2)-specifically, one of the following situations is true: ‚ó¶ The type of the Expression is the class RuntimeException or a subclass of RuntimeException. ‚ó¶ The type of the Expression is the class Error or a subclass of Error. ‚Ä¢ The throw statement is contained in the try block of a try statement (¬ß14.19) and the type of the Expression is assignable (¬ß5.2) to the type of the parameter of at least one catch clause of the try statement. (In this case we say the thrown value is caught by the try statement.) ‚Ä¢ The throw statement is contained in a method or constructor declaration and the type of the Expression is assignable (¬ß5.2) to at least one type listed in the throws clause (¬ß8.4.4, ¬ß8.8.4) of the declaration.A throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a non-null value V, then the throw statement completes abruptly, the reason being a throw with value V. If evaluation of the Expression completes normally, producing a null value, then an instance V' of class NullPointerException is created and thrown instead of null. The throw statement then completes abruptly, the reason being a throw with value V'.It can be seen, then, that a throw statement always completes abruptly.If there are any enclosing try statements (¬ß14.19) whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.If a throw statement is contained in a method declaration, but its value is not caught by some try statement that contains it, then the invocation of the method completes abruptly because of the throw.If a throw statement is contained in a constructor declaration, but its value is not caught by some try statement that contains it, then the class instance creation expression that invoked the constructor will complete abruptly because of the throw.If a throw statement is contained in a static initializer (¬ß8.7), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it. If at run-time, despite this check, the value is not caught by some try statement that contains the throw statement, then the value is rethrown if it is an instance of class Error or one of its subclasses; otherwise, it is wrapped in an ExceptionInInitializerError object, which is then thrown (¬ß12.4.2).If a throw statement is contained in an instance initializer (¬ß8.6), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it, or the type of the thrown exception (or one of its superclasses) occurs in the throws clause of every constructor of the class.By convention, user-declared throwable types should usually be declared to be subclasses of class Exception, which is a subclass of class Throwable (¬ß11.5).All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.throw someThrowableObject;Let's look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes. For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur. + + + + #ThrowsSpecification + true + + + + #ThrowsSpecification + A throws clause is used to declare any checked exceptions (¬ß11.2) that can result from the execution of a method or constructor:A compile-time error occurs if any ClassType mentioned in a throws clause is not the class Throwable or a subclass of Throwable. It is permitted but not required to mention other (unchecked) exceptions in a throws clause.For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a superclass of that exception type is mentioned in a throws clause in the declaration of the method or constructor.The requirement to declare checked exceptions allows the compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions will normally result in a compile-time error because of the lack of a proper exception type in a throws clause. The Java programming language thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.The previous section showed how to write an exception handler for the writeList method in the ListOfNumbers class. Sometimes, it's appropriate for code to catch exceptions that can occur within it. In other cases, however, it's better to let a method further up the call stack handle the exception. For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it.If the writeList method doesn't catch the checked exceptions that can occur within it, the writeList method must specify that it can throw these exceptions. Let's modify the original writeList method to specify the exceptions it can throw instead of catching them. To remind you, here's the original version of the writeList method that won't compile.To specify that writeList can throw two exceptions, add a throws clause to the method declaration for the writeList method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method; here's an example.Remember that ArrayIndexOutOfBoundsException is an unchecked exception; including it in the throws clause is not mandatory. You could just write the following. + + + + #True + true + + + + #True + The boolean type has two values, represented by literals 'true' and ...The following code declares a boolean variable includeSign and assigns it the value of true.The boolean type has two values, represented by the literals true and false, formed from ASCII letters.A boolean literal is always of type boolean.logical true values (reserved word "true")^^http://www.w3.org/2001/XMLSchema#string + + + + #TryCatchFinallyStatement + true + + + + #TryCatchFinallyStatement + If the try statement has a finally clause, then another block of code is executed, no matter whether the try block completes normally or abruptly, and no matter whether a catch clause is first given control.TryStatement: try Block Catches try Block Catchesopt FinallyCatches: CatchClause Catches CatchClauseCatchClause: catch ( FormalParameter ) BlockFinally: finally Block A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.Handling of the finally block is rather complex, so the two cases of a try statement with and without a finally block are described separately. + + + + #TryCatchStatement + true + + + + #TryCatchStatement + A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause.TryStatement: try Block Catches try Block Catchesopt FinallyCatches: CatchClause Catches CatchClauseCatchClause: catch ( FormalParameter ) Block The Block immediately after the keyword try is called the try block of the try statement. The Block immediately after the keyword finally is called the finally block of the try statement.A try statement may have catch clauses (also called exception handlers). A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass of Throwable, or a compile-time error occurs. The scope of the parameter variable is the Block of the catch clause.An exception parameter of a catch clause must not have the same name as a local variable or parameter of the method or initializer block immediately enclosing the catch clause, or a compile-time error occurs.The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (¬ß14.19) is the entire block associated with the catch.Within the Block of the catch clause, the name of the parameter may not be redeclared as a local variable of the directly enclosing method or initializer block, nor may it be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method or initializer block, or a compile-time error occurs. However, an exception parameter may be shadowed (¬ß6.3.1) anywhere inside a class declaration nested within the Block of the catch clause.It is a compile-time error if an exception parameter that is declared final is assigned to within the body of the catch clause.Exception parameters cannot be referred to using qualified names (¬ß6.6), only by simple names.Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its actual argument the thrown exception object. + + + + #TypeCasting + false + + + + #TypeCasting + Typecasting, datatype withing brackets '(datatype)' +Necessary for casting with potential information loss (e.g. double to int or long to int or double to float), for casting from the interface to the class implementing it, and for casting from the superclass to the subclass + + + + #UnaryMinusOperator + true + + + + #UnaryMinusOperator + The type of the operand expression of the unary - operator must be a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (¬ß5.6.1) is performed on the operand. The type of the unary minus expression is the promoted type of the operand.At run time, the value of the unary minus expression is the arithmetic negation of the promoted value of the operand.For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0. Unary minus merely inverts the sign of a floating-point number.Unary minus,'-' to change the sign of the expression result^^http://www.w3.org/2001/XMLSchema#string + + + + #UnsignedRightShiftAssignmentExpression + true + + + + #UnsignedRightShiftExpression + true + + + + #Value + false + + + + #Variable + false + + + + #Variable + General concept of a variable in Java +Variables have DataTypes +Variable serve as operands in Expressions + + + + #VariableDeclarationStatement + true + + + + #VariableDeclarationStatement + A local variable declaration statement declares one or more local variable names.A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable. If a declarator does not have an initialization expression, then a Java compiler must prove, using exactly the algorithm given in ¬ß16, that every reference to the variable is necessarily preceded by execution of an assignment to the variable. If this is not the case, then a compile-time error occurs.Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.A local variable declaration can also appear in the header of a for statement (¬ß14.13). In this case it is executed in the same manner as if it were part of a local variable declaration statement.Each declarator in a local variable declaration declares one local variable, whose name is the Identifier that appears in the declarator.If the optional keyword final appears at the start of the declarator, the variable being declared is a final variable(¬ß4.5.4).The type of the variable is denoted by the Type that appears in the local variable declaration, followed by any bracket pairs that follow the Identifier in the declarator.Thus, the local variable declaration: is equivalent to the series of declarations:A local variable of type float always contains a value that is an element of the float value set (¬ß4.2.3); similarly, a local variable of type double always contains a value that is an element of the double value set. It is not permitted for a local variable of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a local variable of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.Declaration statement consists of the variable declaration and a semicolon^^http://www.w3.org/2001/XMLSchema#string + + + + #VariableInitializationStatement + true + + + + #VariableInitializationStatement + Initialization statement consists of the variable initialization and a semicolon.Both simple variables and object variables. + + + + #VariableName + true + + + + #VariableName + Variable names are case-sensitive. A variable's name can be any legal identifier ‚Äî an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted. Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word. All variables, whether they are fields, local variables, or parameters, follow the same naming rules and conventions that were covered in the Language Basics lesson, Variables‚ÄîNaming .In this lesson, be aware that the same naming rules and conventions are used for method and class names, except that ‚Ä¢ the first letter of a class name should be capitalized, and ‚Ä¢ the first (or only) word in a method name should be a verb. + + + + #VoidDataType + true + + + + #WhileStatement + true + + + + #WhileStatement + 1. One way to create a loop is by using the while statement. 2. Another way is to use the for statementThe while statement has the following syntax. 1. statement(s) will be executed as long as booleanExpression evaluates to true. 2. If there is only a single statement inside the braces, you may omit the braces. 3. For clarity, you should always use braces even when there is only one statement.As an example of the while statement, the following code prints integer numbers that are less than three.The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:while (expression) { statement(s)}The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false. ‚Ä¢ WhileStatement: ‚Ä¢ while ( Expression ) Statement ‚Ä¢ ‚Ä¢ WhileStatementNoShortIf: ‚Ä¢ while ( Expression ) StatementNoShortIf ‚Ä¢ The Expression must have type boolean, or a compile-time error occurs.A while statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the while statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value: ‚Ä¢ If the value is true, then the contained Statement is executed. Then there is a choice: ‚ó¶ If execution of the Statement completes normally, then the entire while statement is executed again, beginning by re-evaluating the Expression. ‚ó¶ If execution of the Statement completes abruptly, see ¬ß14.11.1 below. ‚Ä¢ If the value of the Expression is false, no further action is taken and the while statement completes normally.If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.while loop (precondition)^^http://www.w3.org/2001/XMLSchema#string + + + + #WrapperClass + false + + + + #XPath + true + + + + #XSLT + true + + + + #indexing + This property specifies whether the class can be used for content indexing + + + + #java.lang + true + + + + #java.lang + Provides classes that are fundamental to the design of the Java programming language. The most important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time.Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose. An object of type Double, for example, contains a field whose type is double, representing that value in such a way that a reference to it can be stored in a variable of reference type. These classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode. The Void class is a non-instantiable class that holds a reference to a Class object represening the primitive type void.The class Math provides commonly used mathematical functions such as sine, cosine, and square root. The classes String and StringBuffer similarly provide commonly used operations on character strings.Classes ClassLoader, Process, Runtime, SecurityManager, and System provide "system operations" that manage the dynamic loading of classes, creation of external processes, host environment inquiries such as the time of day, and enforcement of security policies.Class Throwable encompasses objects that may be thrown by the throw statement (¬ß14.16). Subclasses of Throwable represent errors and exceptions.java.lang package^^http://www.w3.org/2001/XMLSchema#string + + + + #java.lang.Boolean + true + + + + #java.lang.Boolean + The java.lang.Boolean class wraps a boolean. You can construct a Boolean object from a boolean or a String, using one of these constructors.public Boolean (boolean value) public Boolean (String value)For example:Boolean b1 = new Boolean (false); Boolean b2 = new Boolean ("true");To convert a Boolean to a boolean, use its booleanValue method: public boolean booleanValue() + + + + #java.lang.Byte + true + + + + #java.lang.Byte + The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.In addition, this class provides several methods for converting a byte to a String and a String to a byte, as well as other constants and methods useful when dealing with a byte. + + + + #java.lang.Character + true + + + + #java.lang.Character + The Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char.In addition, this class provides several methods for determining a character's category (lowercase letter, digit, etc.) and for converting characters from uppercase to lowercase and vice versa.Character information is based on the Unicode Standard, version 4.0.The methods and data of class Character are defined by the information in the UnicodeData file that is part of the Unicode Character Database maintained by the Unicode Consortium. This file specifies various properties including name and general category for every defined Unicode code point or character range. + + + + #java.lang.Class + true + + + + #java.lang.Class + nstances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader. + + + + #java.lang.Class.forName + true + + + + #java.lang.Class.forName + Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to: Class.forName(className, true, currentLoader) where currentLoader denotes the defining class loader of the current class.For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread: Class¬†t¬†= Class.forName("java.lang.Thread") A call to forName("X") causes the class named X to be initialized.Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName) this method attempts to locate, load, and link the class or interface. The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.If name denotes a primitive type or void, an attempt will be made to locate a user-defined class in the unnamed package whose name is name. Therefore, this method cannot be used to obtain any of the Class objects representing primitive types or void.If name denotes an array class, the component type of the array class is loaded but not initialized.For example, in an instance method the expression: Class.forName("Foo") is equivalent to: Class.forName("Foo", true, this.getClass().getClassLoader()) Note that this method throws errors related to loading, linking or initializing as specified in Sections 12.2, 12.3 and 12.4 of The Java Language Specification. Note that this method does not check whether the requested class is accessible to its caller.If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader.^^http://www.w3.org/2001/XMLSchema#string + + + + #java.lang.Double + true + + + + #java.lang.Double + The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double. + + + + #java.lang.Double.parseDouble + true + + + + #java.lang.Double.parseDouble + Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double. + + + + #java.lang.Exception + true + + + + #java.lang.Exception + The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.When a program violates the semantic constraints of the Java programming language, the Java virtual machine signals this error to the program as an exception. An example of such a violation is an attempt to index outside the bounds of an array. Some programming languages and their implementations react to such errors by peremptorily terminating the program; other programming languages allow an implementation to react in an arbitrary or unpredictable way. Neither of these approaches is compatible with the design goals of the Java platform: to provide portability and robustness. Instead, the Java programming language specifies that an exception will be thrown when semantic constraints are violated and will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer. An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.The Java programming language uses exceptions to handle errors and other exceptional events. This lesson describes when and how to use exceptions.When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates. + + + + #java.lang.Float + true + + + + #java.lang.Float + The Float class wraps a value of primitive type float in an object. An object of type Float contains a single field whose type is float.In addition, this class provides several methods for converting a float to a String and a String to a float, as well as other constants and methods useful when dealing with a float. + + + + #java.lang.Integer + true + + + + #java.lang.Integer + The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int. + + + + #java.lang.Integer.parseInt + true + + + + #java.lang.Integer.parseInt + Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned.An exception of type NumberFormatException is thrown if any of the following situations occurs: ‚Ä¢ The first argument is null or is a string of length zero. ‚Ä¢ The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX. ‚Ä¢ Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1. ‚Ä¢ The value represented by the string is not a value of type int. + + + + #java.lang.Long + true + + + + #java.lang.Long + The Long class wraps a value of the primitive type long in an object. An object of type Long contains a single field whose type is long.In addition, this class provides several methods for converting a long to a String and a String to a long, as well as other constants and methods useful when dealing with a long. + + + + #java.lang.Math + true + + + + #java.lang.Math + The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.Unlike some of the numeric methods of class StrictMath, all implementations of the equivalent functions of class Math are not defined to return the bit-for-bit same results. This relaxation permits better-performing implementations where strict reproducibility is not required.By default many of the Math methods simply call the equivalent method in StrictMath for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math. + + + + #java.lang.Math.abs + true + + + + #java.lang.Math.ceil + true + + + + #java.lang.Math.ceil + Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases: ‚Ä¢ If the argument value is already equal to a mathematical integer, then the result is the same as the argument. ‚Ä¢ If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. ‚Ä¢ If the argument value is less than zero but greater than -1.0, then the result is negative zero.Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x). + + + + #java.lang.Math.cos + true + + + + #java.lang.Math.cos + Returns the trigonometric cosine of an angle. Special cases: ‚Ä¢ If the argument is NaN or an infinity, then the result is NaN.The computed result must be within 1 ulp of the exact result. Results must be semi-monotonic. + + + + #java.lang.Math.exp + true + + + + #java.lang.Math.exp + Returns Euler's number e raised to the power of a double value. Special cases: ‚Ä¢ If the argument is NaN, the result is NaN. ‚Ä¢ If the argument is positive infinity, then the result is positive infinity. ‚Ä¢ If the argument is negative infinity, then the result is positive zero.The computed result must be within 1 ulp of the exact result. Results must be semi-monotonic. + + + + #java.lang.Math.floor + true + + + + #java.lang.Math.floor + Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. Special cases: ‚Ä¢ If the argument value is already equal to a mathematical integer, then the result is the same as the argument. ‚Ä¢ If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. + + + + #java.lang.Math.log + true + + + + #java.lang.Math.max + true + + + + #java.lang.Math.min + true + + + + #java.lang.Math.min + Returns the smaller of two double values. That is, the result is the value closer to negative infinity. If the arguments have the same value, the result is that same value. If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. If one argument is positive zero and the other is negative zero, the result is negative zero. + + + + #java.lang.Math.pow + true + + + + #java.lang.Math.pow + Returns the value of the first argument raised to the power of the second argument. + + + + #java.lang.Math.round + true + + + + #java.lang.Math.round + Returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. In other words, the result is equal to the value of the expression: + + + + #java.lang.Math.sin + true + + + + #java.lang.Math.sqrt + true + + + + #java.lang.Math.tan + true + + + + #java.lang.Object + true + + + + #java.lang.Object + The Object class, defined in the java.lang package, defines and implements behavior common to all classes‚Äîincluding the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of the hierarchy provide more specialized behavior. + + + + #java.lang.Object.clone + true + + + + #java.lang.Object.clone + If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method to create a copy from an existing object. To create a clone, you write:aCloneableObject.clone();Object's implementation of this method checks to see whether the object on which clone() was invoked implements the Cloneable interface. If the object does not, the method throws a CloneNotSupportedException exception. Exception handling will be covered in a later lesson. For the moment, you need to know that clone() must be declared asprotected Object clone() throws CloneNotSupportedException -- or --public Object clone() throws CloneNotSupportedExceptionif you are going to write a clone() method to override the one in Object.If the object on which clone() was invoked does implement the Cloneable interface, Object's implementation of the clone() method creates an object of the same class as the original object and initializes the new object's member variables to have the same values as the original object's corresponding member variables.The simplest way to make your class cloneable is to add implements Cloneable to your class's declaration. then your objects can invoke the clone() method.For some classes, the default behavior of Object's clone() method works just fine. If, however, an object contains a reference to an external object, say ObjExternal, you may need to override clone() to get correct behavior. Otherwise, a change in ObjExternal made by one object will be visible in its clone also. This means that the original object and its clone are not independent‚Äîto decouple them, you must override clone() so that it clones the object and ObjExternal. Then the original object references ObjExternal and the clone references a clone of ObjExternal, so that the object and its clone are truly independent. + + + + #java.lang.Object.equals + true + + + + #java.lang.Object.equals + The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal‚Äîthat is, if the objects compared are the exact same object.To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method. Here is an example of a Book class that overrides equals():Consider this code that tests two instances of the Book class for equality:This program displays objects are equal even though firstBook and secondBook reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number.You should always override the equals() method if the identity operator is not appropriate for your class.Note:¬†If you override equals(), you must override hashCode() as well. + + + + #java.lang.Object.hashCode + true + + + + #java.lang.Object.hashCode + The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well. + + + + #java.lang.Object.toString + true + + + + #java.lang.Object.toString + You should always consider overriding the toString() method in your classes.The Object's toString() method returns a String representation of the object, which is very useful for debugging. The String representation for an object depends entirely on the object, which is why you need to override toString() in your classes.You can use toString() along with System.out.println() to display a text representation of an object, such as an instance of Book:System.out.println(firstBook.toString());which would, for a properly overridden toString() method, print something useful, like this: + + + + #java.lang.Short + true + + + + #java.lang.Short + The Short class wraps a value of primitive type short in an object. An object of type Short contains a single field whose type is short.In addition, this class provides several methods for converting a short to a String and a String to a short, as well as other constants and methods useful when dealing with a short. + + + + #java.lang.String + true + + + + #java.lang.String + The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.The Java language provides special support for the string concatenation operator (¬†+¬†), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values). + + + + #java.lang.String.charAt + true + + + + #java.lang.String.charAt + Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. + + + + #java.lang.String.compareTo + true + + + + #java.lang.String.compareTo + Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true. + + + + #java.lang.String.compareToIgnoreCase + true + + + + #java.lang.String.compareToIgnoreCase + Compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character.Note that this method does not take locale into account, and will result in an unsatisfactory ordering for certain locales. The java.text package provides collators to allow locale-sensitive ordering. + + + + #java.lang.String.concat + true + + + + #java.lang.String.concat + Concatenates the specified string to the end of this string.If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. + + + + #java.lang.String.equals + true + + + + #java.lang.String.equals + Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. + + + + #java.lang.String.equalsIgnoreCase + true + + + + #java.lang.String.equalsIgnoreCase + Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.Two characters c1 and c2 are considered the same ignoring case if at least one of the following is true: ‚Ä¢ The two characters are the same (as compared by the == operator) ‚Ä¢ Applying the method Character.toUpperCase(char) to each character produces the same result ‚Ä¢ Applying the method Character.toLowerCase(char) to each character produces the same result + + + + #java.lang.String.indexOf + true + + + + #java.lang.String.indexOf + Returns the index within this string of the first occurrence of the specified character. If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned. + + + + #java.lang.String.length + true + + + + #java.lang.String.length + One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.public int length()Returns the length of this string. The length is equal to the number of Unicode code units in the string. + + + + #java.lang.String.replace + true + + + + #java.lang.String.replace + Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar. + + + + #java.lang.String.substring + true + + + + #java.lang.String.substring + Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. + + + + #java.lang.String.toLowerCase + true + + + + #java.lang.String.toLowerCase + Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. + + + + #java.lang.String.toUpperCase + true + + + + #java.lang.String.toUpperCase + Returns a copy of the string, with leading and trailing whitespace omitted.If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k,¬†m+1).This method may be used to trim whitespace (as defined above) from the beginning and end of a string. + + + + #java.lang.System + true + + + + #java.lang.System + The System class contains several useful class fields and methods. It cannot be instantiated.Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array. + + + + #java.lang.System.err + true + + + + #java.lang.System.err + The "standard" error output stream. This stream is already open and ready to accept output data.Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored. + + + + #java.lang.System.in + true + + + + #java.lang.System.in + The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user. + + + + #java.lang.System.out + true + + + + #java.lang.System.out + The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. + + + + #java.lang.System.out.print + true + + + + #java.lang.System.out.print + Prints its argument to the standard output stream. + + + + #java.lang.System.out.println + true + + + + #java.lang.System.out.println + Prints its argument to the standard output stream and then terminates the line. + + + + #java.lang.Thread + true + + + + #java.lang.Thread + A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs: ‚Ä¢ The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. ‚Ä¢ All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method. + + + + #java.lang.Throwable + true + + + + #java.lang.Throwable + The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Finally, it can contain a cause: another throwable that caused this throwable to get thrown. The cause facility is new in release 1.4. It is also known as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another. + + + + #java.lang.Void + true + + + + #java.lang.Void + The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void. + + + + #java.util + true + + + + #java.util + Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array). + + + + #java.util.ArrayList + true + + + + #java.util.ArrayList + Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. + + + + #java.util.ArrayList.add + true + + + + #java.util.ArrayList.add + Appends the specified element to the end of this list.Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). + + + + #java.util.ArrayList.get + true + + + + #java.util.ArrayList.get + Returns the element at the specified position in this list. + + + + #java.util.ArrayList.indexOf + true + + + + #java.util.ArrayList.indexOf + Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null¬†?¬†get(i)==null¬†:¬†o.equals(get(i))), or -1 if there is no such index. + + + + #java.util.ArrayList.remove + true + + + + #java.util.ArrayList.remove + Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null¬†?¬†get(i)==null¬†:¬†o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call). + + + + #java.util.ArrayList.set + true + + + + #java.util.ArrayList.set + Replaces the element at the specified position in this list with the specified element. + + + + #java.util.ArrayList.size + true + + + + #java.util.ArrayList.size + Returns the number of elements in this list. + + + + #java.util.List + true + + + + #java.util.List + An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list. + + + + #java.util.Random + true + + + + #java.util.Random + An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 3, Section 3.2.1.)If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits. + + + + #java.util.Random.nextDouble + true + + + + #java.util.Random.nextDouble + Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.The general contract of nextDouble is that one double value, chosen (approximately) uniformly from the range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated and returned.The method nextDouble is implemented by class Random as if by:The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose double values from the stated range with perfect uniformity. + + + + #java.util.Random.nextInt + true + + + + #java.util.Random.nextInt + Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability. The method nextInt(int n) is implemented by class Random as if by:The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose int values from the stated range with perfect uniformity. + + + + #java.util.Scanner + true + + + + #java.util.Scanner + A simple text scanner which can parse primitive types and strings using regular expressions.A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace. The reset() method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed.A scanning operation may block waiting for input.The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.The findInLine(java.lang.String), findWithinHorizon(java.lang.String, int), and skip(java.util.regex.Pattern) methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\\s" could return empty tokens since it only passes one space at a time.A scanner can read text from any object which implements the Readable interface. If an invocation of the underlying readable's Readable.read(java.nio.CharBuffer) method throws an IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the ioException() method.When a Scanner is closed, it will close its input source if the source implements the Closeable interface.A Scanner is not safe for multithreaded use without external synchronization.Unless otherwise mentioned, passing a null parameter into any method of a Scanner will cause a NullPointerException to be thrown.A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the useRadix(int) method. The reset() method will reset the value of the scanner's radix to 10 regardless of whether it was previously changed. + + + + #java.util.Scanner.next + true + + + + #java.util.Scanner.next + Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.Returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.Returns the next token if it matches the pattern constructed from the specified string. If the match is successful, the scanner advances past the input that matched the pattern.An invocation of this method of the form next(pattern) behaves in exactly the same way as the invocation next(Pattern.compile(pattern)). + + + + #java.util.Scanner.nextDouble + true + + + + #java.util.Scanner.nextInt + true + + + + #java.util.Scanner.nextInt + Scans the next token of the input as an int.An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.If the next token matches the Integer regular expression defined above then the token is converted into an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Integer.parseInt with the specified radix. + + + + #java.util.Scanner.nextLine + true + + + + #java.util.Scanner.nextLine + Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present. + + + + #null + true + + + + #null + You can test if a reference variable is null by using the == operator. For instance. + + + \ No newline at end of file diff --git a/static/py-ontology-4-8-24.png b/static/py-ontology-4-8-24.png new file mode 100644 index 0000000..e584df5 Binary files /dev/null and b/static/py-ontology-4-8-24.png differ diff --git a/static/py_keyword_functions.json b/static/py_keyword_functions.json new file mode 100644 index 0000000..74408b6 --- /dev/null +++ b/static/py_keyword_functions.json @@ -0,0 +1,101 @@ +{ + "print": "print-to-user", + "input": "get-user-input", + "dict":"create-dict", + "set":"create-set", + "list":"create-list", + "read":"file-read", + "tuple":"create-tuple", + "str":"typecast-str", + "int":"typecast-int", + "float": "typecast-float", + "bool": "typecast-bool", + "len":"length-of-collection-or-str", + "range":"range-func", + "enumerate":"enumerate-for-iter", + "zip":"create-dict-for-iter", + "sorted":"sort-collection", + "reversed":"reverse-collection", + "sum":"sum-of-collection", + "min":"min-of-collection", + "max":"max-of-collection", + "abs":"absolute-value", + "round":"round-down", + "pow":"expontent", + "any":"any-op-collection", + "all":"all-op-collection", + "map":"map-op-collection", + "filter":"filter-op-collection", + "reduce":"reduce-op-collection", + "next":"next-op-generator", + "iter":"iter-op-generator", + "re":"re-gex", + "open":"file-open", + "close":"file-close", + "readline":"file-read", + "readlines":"file-read", + "write":"file-write", + "writelines":"file-write", + "seek":"file--seek", + "tell":"file-get-fp", + "flush":"fp-flush", + "isinstance":"get-type-of", + "issubclass":"is-attribute", + "split":"str-split-op", + "append":"collection-append-op", + "extend":"collection-extend-op", + "insert":"collection-insert-op", + "remove":"collection-remove-op", + "pop":"collection-pop-func", + "index":"collection-index-func", + "count":"collection-count-func", + "sort":"collection-sort-func", + "reverse":"collection-reverse-func", + "copy":"copy-func", + "clear":"clear-func", + "join":"str-join-func", + "replace":"replace-func", + "find":"find-func", + "rfind":"regex-find-func", + "strip":"str-strip-func", + "lstrip":"str-left-strip-func", + "rstrip": "str-right-strip-func", + "capitalize": "str-capitalize-func", + "title": "str-title-func", + "upper": "str-allcaps-func", + "lower": "str-allsmall-func", + "swapcase": "str-swapcase-func", + "startswith": "str-startswith-func", + "endswith": "str-endswith-func", + "isdigit": "str-isdigit-func", + "isalpha": "str-isalpha-func", + "isalnum": "str-isalnum-func", + "isspace": "str-isspace-func", + "isupper": "str-isupper-func", + "islower":"str-islower-func", + "istitle":"str-istitle-func", + "isnumeric":"str-title-func", + "getattr":"collection-get-attribute", + "setattr":"collection-set-attribute", + "delattr":"collection-delete-attribute", + "hasattr":"collection-has-attribute", + "callable":"callable-function-class", + "dir":"python-object-browser", + "globals":"python-globals", + "locals":"python-locals", + "vars":"class-variables", + "eval":"python-eval", + "exec":"python-exec", + "compile":"python-compile", + "help":"python-help", + "repr":"str-representation", + "ascii":"ascii-list", + "ord":"get-ordinal-number", + "chr":"get-character", + "bin":"get-binary", + "oct":"get-octal", + "hex":"get-hex", + "format":"str-format-func", + "divmod":"modulo", + "Keyword": "func-keyword-arguments" +} \ No newline at end of file diff --git a/static/py_ops.json b/static/py_ops.json new file mode 100644 index 0000000..3c48a08 --- /dev/null +++ b/static/py_ops.json @@ -0,0 +1,35 @@ +{ + + "Add":"Str-or-Num-Add-op", + "Sub":"Num-Sub-op", + "Mult":"Num-Mul-op", + "MatMult":"Matrix-op", + "Div":"Num-Div-op", + "Mod":"Num-Modulo-op", + "LShift":"Num-Left-Shift-op", + "RShift":"Num-Right-Shift-op", + "BitOr":"Bitwise-Or", + "BitXor":"Bitwise-Xor", + "BitAnd":"Bitwise-And", + "FloorDiv":"Floor-Div", + "Invert":"Invert-Binary-Op", + "Not":"Not-Binary-Op", + "UAdd":"Unary-Add-Op", + "USub":"Unary-Sub-Op", + "Eq":"Compare-Equals", + "NotEq":"Compare-NotEquals", + "Lt":"Compare-LessThan", + "LtE":"Compare-LessThan-Equals", + "Gt":"Compare-GreaterThan", + "GtE":"Compare-GreaterThan-Equals", + "Is":"Compare-Type", + "IsNot":"Compare-Type-Not", + "In":"In-Collection", + "NotIn":"Not-In-Collection", + "Try":"Exception-Handler", + "ExceptHandler":"Exception-Handler", + "And":"Conditional-And", + "Or":"Conditional-Or", + "Assign": "Numeric-or-String-or-Collection-Assignment", + "Keyword":"func-keyword-arguments" +} \ No newline at end of file diff --git a/static/python.owl b/static/python.owl new file mode 100644 index 0000000..d0d74a8 --- /dev/null +++ b/static/python.owl @@ -0,0 +1,758 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/static/python_ontology_alice_202504301242.owl b/static/python_ontology_alice_202504301242.owl new file mode 100644 index 0000000..a09db81 --- /dev/null +++ b/static/python_ontology_alice_202504301242.owl @@ -0,0 +1,2494 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AccessingDictionary includes any operation that retrieves values from a dictionary, including direct indexing (dict[key]) and methods like .get(), .items(), .keys(), and .values().) + + + + + + + + + Referes to the expression dictionary[‘new_key' ]= value + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + An augmented assignment statement is += 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Evaluating boolean expressions + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CallingFunctionLibrary refers to ANY use of built-in Python functions (print, len, replace, etc.) and built-in methods of objects (like list.append() or string.replace(), etc.). + + + + + + + + + CallingNestedFunction refers to the call of functions that have in their code the definition of other user-defined functions + + + + + + + + + + + + + + + + + CallingRecursiveFunction refers to calling a function that calls itself (recursion) + + + + + + + + + + + + + + + + + + + + + + + + + + + CallingStandardFunction refers to calling a function that meets all the 3 following criteria:1) Does not call any other user-defined functions 2) Is not nested inside another function 3) Does not call itself (not recursive) Note: A standard function may still call built-in functions. + + + + + + + + + + + + + + + + + + + + + + + + + check for item with the 'in' construct + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + str() + string = "" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + DefiningNestedFunction refers to defining a function inside another user-defined function. + + + + + + + + + + + + + + + + + DefiningRecursiveFunction refers to defining a function that calls itself within its own body (recursion). + + + + + + + + + + + + + + + + + + + + + DefiningStandardFunction refers to defining a function that: 1) Does not call any other user-defined functions 2) Is not nested inside another function 3) Does not call itself (not recursive) Note: A standard function may still call built-in functions. Additionally, DefiningStandardFunction can still be later called in nested patterns (NestedFunctionCall). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + refers to the expression len() + + + + + + + + + + + + + + + + + ForLoopWithListIndexing refers to when there is an indexing of a list happening inside a for loop + + + + + + + + + + + + + + + + + + + + + + + + + f string + + + + + + + + + + + + + + + + + + + + + + + + + These data structure as they are not inherent to Python need to be evaluated separately + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Using try and except block as "except Exception as e:" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Using try and except block with the specific error + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IfChecking refers to an if statement which is not placed inside any loop + + + + + + + + + IfCheckingInForLoop refers to an if statement inside a for loop + + + + + + + + + IfCheckingInWhileLoop refers to an if statement inside a while loop + + + + + + + + + + + + + + + + + + + + + IfElifChecking refers to an if-elif statement which is not placed inside any loop + + + + + + + + + IfElifCheckingInForLoop refers to an if-elif statement inside a for loop + + + + + + + + + IfElifCheckingInWhileLoop refers to an if-elif statement inside a while loop + + + + + + + + + + + + + + + + + + + + + IfElifElseChecking refers to an if-elif-else statement which is not placed inside any loop + + + + + + + + + IfElifElseCheckingInForLoop refers to an if-elif-else statement inside a for loop + + + + + + + + + IfElifElseCheckingInWhileLoop refers to an if-elif-else statement inside a while loop + + + + + + + + + + + + + + + + + + + + + + + + + IfElseChecking refers to an if-else statement which is not placed inside any loop + + + + + + + + + IfElseCheckingInForLoop refers to an if-else statement inside a for loop + + + + + + + + + IfElseCheckingInWhileLoop refers to an if-else statement inside a while loop + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Refers to direct indexig with the expression dict[key] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + > + + + + + + + + + >= + + + + + + + + + < + + + + + + + + + <= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ListReferencing refers to the code in which one list is set equal to another, and a change to one of the lists causes the same change in the other list. ListReferencing should only be marked as present if a list is explicitly assigned to another list variable (e.g., list2 = list1). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MixedNestedLoopIteration refers to nested loop such that a while-loop inside a for-loop or a for-loop inside a while-loop + + + + + + + + + + + + + + + + + same as % + + + + + + + + + + + + + + + + + + + + + + + + + NestedForLoopIteration refers to nested loop such that a for-loop is inside another for-loop + + + + + + + + + + + + + + + + + NestedFunctionCall refers to when one function call is placed as an argument to another function call (e.g., f(g(x))) + + + + + + + + + + + + + + + + + Nested If Checking refers to having an if, elif, or else block inside another if, elif, or else block. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NestedWhileLoopIteration refers to nested loop such that a while-loop is inside another while-loop + + + + + + + + + + + + + + + + + != + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + refers to using the expression dictionary[old_key]= value + + + + + + + + + + + + + + + + + + + + + + + list[index]= value + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SingleForLoopIteration refers to a single use use of a for-loop that has no nested structure +When identifying nested loop structures, classify the entire structure under the appropriate nested loop category only (e.g., NestedForLoopIteration). Do not also include the single-loop categories for the outer loop + + + + + + + + + + + + + + + + + + + + + SingleWhileLoopIteration refers to a single use of a while-loop that has no nested structure +When identifying nested loop structures, classify the entire structure under the appropriate nested loop category only (e.g., NestedWhileLoopIteration). Do not also include the single-loop categories for the outer loop + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .split() or rsplit() + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Refers to when variables are swapped (e.g. +temp =a +a=b +b=temp +) + + + + + + + + + + + + + + + + + + + + + + + + + float() +int() + + + + + + + + + + + + + + + + + strip() or rstrip() + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UpdatingVariable refers to when a variable that was already assigned to a value is update (e.g. x+=1 or x=x+1) + + + + + + + + + + + + + + + + + WhileLoopWithListIndexing refers to when there is an indexing of a list happening inside a while loop + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + maybe delete this one actually + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = + + + + + + + + + == + + + + + + + + + ForLoopWith*= refers to when there is an update of a variable with the multiplication sign inside a for loop + + + + + + + + + ForLoopWith+= refers to when there is an update of a variable with the addition sign inside a for loop + + + + + + + + + WhileLoopWith*= refers to when there is an update of a variable with the multiplication sign inside a while loop + + + + + + + + + WhileLoopWith+= refers to when there is an update of a variable with the addition sign inside a while loop + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/static/python_ontology_alice_202504301242.png b/static/python_ontology_alice_202504301242.png new file mode 100644 index 0000000..17c0a87 Binary files /dev/null and b/static/python_ontology_alice_202504301242.png differ diff --git a/static/references/java-ontology.png b/static/references/java-ontology.png new file mode 100644 index 0000000..3157f3e Binary files /dev/null and b/static/references/java-ontology.png differ diff --git a/static/references/java.owl b/static/references/java.owl new file mode 100644 index 0000000..34d279e --- /dev/null +++ b/static/references/java.owl @@ -0,0 +1,9817 @@ + + + + + + + + + + + + java_ontology + + + + java_ontology by paws.sis.pitt.edu v. 0.8.1 2009-03-25 + + + + This is a second version of Java ontology created by the PAWS group for indexing adaptive java content +The main purpose of this ontology is to represent the domian of Java and provide the basis for modelling of student knowledge of java concepts and content-based adaptation of Java-related learning activities +This version is an RDFS ontology. It spesifieds the basic vocabulary of the domain. It has three relations: subClassOf, partOf-hasPart and relatedTo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #AbstractClass + false + + + + #AbstractClass + 1. Provide a contract between a service provider and its clients. 2. An abstract class can provide implementation. 3. To make an abstract method, use the abstract modifier in front of the method declaration. # An abstract class is a class that cannot be instantiated# An abstract class must be implemented by a subclass.An abstract class is a class that is declared abstract‚Äîit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.If a class includes abstract methods, the class itself must be declared abstract, as in:When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods). + + + + #AbstractClassDefinition + true + + + + #AbstractClassDefinition + 1. Provide a contract between a service provider and its clients. 2. An abstract class can provide implementation. 3. To make an abstract method, use the abstract modifier in front of the method declaration. # An abstract class is a class that cannot be instantiated# An abstract class must be implemented by a subclass.An abstract class is a class that is declared abstract‚Äîit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.If a class includes abstract methods, the class itself must be declared abstract, as in:When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods). + + + + #AbstractMethod + false + + + + #AbstractMethod + An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:If a class includes abstract methods, the class itself must be declared abstract, as in:All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be‚Äîit's just not necessary). + + + + #AbstractMethodDefinition + true + + + + #AbstractMethodDefinition + An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:If a class includes abstract methods, the class itself must be declared abstract, as in:All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be‚Äîit's just not necessary). + + + + #AbstractModifier + true + + + + #AbstractModifier + 1. Provide a contract between a service provider and its clients. 2. An abstract class can provide implementation. 3. To make an abstract method, use the abstract modifier in front of the method declaration. # An abstract class is a class that cannot be instantiated# An abstract class must be implemented by a subclass.An abstract class is a class that is declared abstract‚Äîit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.If a class includes abstract methods, the class itself must be declared abstract, as in:When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:If a class includes abstract methods, the class itself must be declared abstract, as in:All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be‚Äîit's just not necessary). + + + + #Abstraction + true + + + + #Abstraction + An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer. + + + + #AccessSpecifier + false + + + + #ActualMethodParameter + true + + + + #ActualMethodParameter + The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.Note:¬†Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and arrays.Here's an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y coordinate): + + + + #AddAssignmentExpression + true + + + + #AddAssignmentExpression + You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1. All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Adds value of the varibale to the left with the value of the expression to the right and assigns the result to the variable to the left '=+'^^http://www.w3.org/2001/XMLSchema#string + + + + #AddExpression + true + + + + #AddExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. + additive operatorAddition Operator '+'^^http://www.w3.org/2001/XMLSchema#string + + + + #AdditiveExpression + false + + + + #AdditiveExpression + Additive operators '+' '-' + + + + #AndExpression + true + + + + #AndExpression + The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1. Otherwise, the result has the value 0. The type of the result is int. Both operands must have a arithmetic or pointer type. The usual arithmetic conversions on each operand are performed. If both operands have values of true, the result has the value true. Otherwise, the result has the value false. Both operands and the result have type boolean. Unlike the & (bitwise AND) operator, the && operator guarantees left-to-right evaluation of the operands. If the left operand evaluates to false, the right operand is not evaluated. The && operator is like & (¬ß15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)&&(b))&&(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)&&((b)&&(c)).Each operand of && must be of type boolean, or a compile-time error occurs. The type of a conditional-and expression is always boolean.At run time, the left-hand operand expression is evaluated first; if its value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated and its value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.Boolean (Logical) AND '&&'^^http://www.w3.org/2001/XMLSchema#string + + + + #ArithmeticAssignmentExpression + false + + + + #ArithmeticAssignmentExpression + Following C and C++ syntax Java allows to combine arithmetical operators and simple assignement into complex assignements + + + + #ArithmeticExpression + false + + + + #ArithmeticExpression + Arithmetic operators '+' '-' '*' '/' '%' '(' ')' + + + + #ArrayCreationStatement + true + + + + #ArrayCreationStatement + The above program declares anArray with the following line of code: int[] anArray; // declares an array of integersLike declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array ‚Äî it simply tells the compiler that this variable will hold an array of the specified type.Similarly, you can declare arrays of other types: byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings;You can also place the square brackets after the array's name: float anArrayOfFloats[]; // this form is discouragedHowever, convention discourages this form; the brackets identify the array type and should appear with the type designation. One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable. anArray = new int[10]; // create an array of integersIf this statement were missing, the compiler would print an error like the following, and compilation would fail: ArrayDemo.java:4: Variable anArray may not have been initialized.Array Creation statement consist of array declaration, new oprator type of array elements and '[]'^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayDataType + true + + + + #ArrayDataType + An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the arrayAn array of ten elementsEach item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. 1. An array is a named set of same-type variables. 2. Each variable in the array is called an array element. 3. The first element will have an index of 0. + + + + #ArrayElement + true + + + + #ArrayElement + Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output. The next few lines assign values to each element of the array: anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc.Each array element is accessed by its numerical index: System.out.println("Element 1 at index 0: " + anArray[0]); System.out.println("Element 2 at index 1: " + anArray[1]); System.out.println("Element 3 at index 2: " + anArray[2]);Array element stores a single value. The array consists of array elements. All array elements have the same data type^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayElementType + true + + + + #ArrayElementType + An array is a container object that holds a fixed number of values of a single type.Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output.An array type is written as the name of an element type followed by some number of empty pairs of square brackets []. The number of bracket pairs indicates the depth of array nesting. An array's length is not part of its type.The element type of an array may be any type, whether primitive or reference. In particular: ‚Ä¢ Arrays with an interface type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any type that implements the interface. ‚Ä¢ Arrays with an abstract class type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any subclass of the abstract class that is not itself abstract.Array types are used in declarations and in cast expressionsArray element type specifies the type of array elements - the type of values that can be stored in the array^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayInitializationStatement + true + + + + #ArrayInitializationStatement + Alternatively, you can use the shortcut syntax to create and initialize an array: int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};Here the length of the array is determined by the number of values provided between { and }. array variable intialization (including type of array elements, [], and array variable name)^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayInitializer + true + + + + #ArrayInitializer + Alternatively, you can use the shortcut syntax to create and initialize an array:Here the length of the array is determined by the number of values provided between { and }.An array initializer may be specified in a declaration, or as part of an array creation expression (¬ß15.10), creating an array and providing some initial values:An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".The length of the constructed array will equal the number of expressions.The expressions in an array initializer are executed from left to right in the textual order they occur in the source code. The nth variable initializer specifies the value of the n-1st array component. Each expression must be assignment-compatible (¬ß5.2) with the array's component type, or a compile-time error results.If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.A trailing comma may appear after the last expression in an array initializer and is ignored. + + + + #ArrayLength + true + + + + #ArrayLength + One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable. anArray = new int[10]; // create an array of integersHere the length of the array is determined by the number of values provided between { and }. Finally, you can use the built-in length property to determine the size of any array. The code System.out.println(anArray.length);will print the array's size to standard output.Array Lenght spesifies how many elements the array can store^^http://www.w3.org/2001/XMLSchema#string + + + + #ArrayVariable + true + + + + #ArrayVariable + A variable of array type holds a reference to an object. Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array. However, the initializer part of a declarator (¬ß8.3) may create an array, a reference to which then becomes the initial value of the variable.Because an array's length is not part of its type, a single variable of array type may contain references to arrays of different lengths.Here are examples of declarations of array variables that do not create arrays:Here are some examples of declarations of array variables that create array objects:The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A. This may result in a run-time exception on a later assignment; see ¬ß10.10 for a discussion.a variable of array data type storing a reference to array representation in memory^^http://www.w3.org/2001/XMLSchema#string + + + + #AssignmentExpression + false + + + + #AssignmentExpression + Assignement operators change the value of the variable to the left with the vlaue of the expression to the right + + + + #AutoBoxing + true + + + + #AutoBoxing + 1. Boxing refers to the conversion of a primitive to a corresponding wrapper instance, such as from an int to a java.lang.Integer. 2. Unboxing is the conversion of a wrapper instance to a primitive type, such as from Byte to byte. 1. Related to Java's type wrappers. 2. How values are moved into and out of a wrapper instance 3. Java primitive type wrappers: Boolean, Byte, Character, Double, Float, Long, Integer, Short. 2. 17. 1. Type conversion (JDK1.5 Autoboxing/Unboxing) 2. 17. 2. Boxing and Unboxing 2. 17. 3. Autoboxing and Auto-Unboxing 2. 17. 6. To unbox an object 2. 17. 7. Autoboxing/unboxing: an argument passed to a method or returned from a method 2. 17. 8. Autoboxing/unboxing occurs inside expressions 2. 17. 9. Auto-unboxing: mix different types of numeric objects in an expression. 2. 17. 11. Autoboxing/Unboxing Boolean and Character Values 2. 17. 12. Autoboxing/unboxing takes place with method parameters and return values. 2. 17. 13. Auto-unboxing allows you to mix different types of numeric objects in an expression.When working with numbers, most of the time you use the primitive types in your code. For example:There are, however, reasons to use objects in place of primitives, and the Java platform provides wrapper classes for each of the primitive data types. These classes "wrap" the primitive in an object. Often, the wrapping is done by the compiler‚Äîif you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the compiler unboxes the object for you.Here is an example of boxing and unboxing:When x and y are assigned integer values, the compiler boxes the integers because x and y are integer objects. In the println() statement, x and y are unboxed so that they can be added as integers.All of the numeric wrapper classes are subclasses of the abstract class Number: + + + + #BitShiftAssignmentExpression + false + + + + #BitShiftAssignmentExpression + Compines simple assignment and bit shift operators + + + + #BitShiftExpression + false + + + + #BitwiseAndAssignmentExpression + true + + + + #BitwiseAndExpression + true + + + + #BitwiseAssignmentExpression + false + + + + #BitwiseAssignmentExpression + Compines simple assignment and bitwise operators + + + + #BitwiseExpression + false + + + + #BitwiseOrAssignmentExpression + true + + + + #BitwiseOrExpression + true + + + + #BitwiseXorAssignmentExpression + true + + + + #BitwiseXorExpression + true + + + + #BooleanDataType + true + + + + #BooleanDataType + boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined. # Variables of type boolean can have only one of two values, true or false.# The values 'true' and 'false' are boolean literals.boolean data type (reserved word "boolean")^^http://www.w3.org/2001/XMLSchema#string + + + + #BooleanExpression + false + + + + #BooleanExpression + Three major operators of Boolena Algebra (and, or, not) + + + + #BooleanValue + false + + + + #BreakStatement + true + + + + #BreakStatement + 1. The break statement is used to break from an enclosing do, while, for, or switch statement. 2. It is a compile error to use break anywhere else. 3. 'break' breaks the loop without executing the rest of the statements in the block. The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop, as shown in the following BreakDemo program:break statement (breaks loop execution) +most often break statment is used as a part of switch statement^^http://www.w3.org/2001/XMLSchema#string + + + + #ByteDataType + true + + + + #ByteDataType + byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation. integer data type for numbers between -128 and 127 (reserved word "byte")^^http://www.w3.org/2001/XMLSchema#string + + + + #ByteValue + true + + + + #CallBack + true + + + + #CaseClause + true + + + + #CaseClause + Another point of interest is the break statement after each case. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements. The following program, SwitchDemo2, illustrates why it might be useful to have case statements fall through:case clause - single option of a switch statement^^http://www.w3.org/2001/XMLSchema#string + + + + #CharDataType + true + + + + #CharDataType + char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). + + + + #CharValue + true + + + + #CharValue + A character literal is expressed as a character or an escape sequence, enclosed in ASCII single quotes. (The single-quote, or apostrophe, character is \u0027.)A character literal is always of type char. + + + + #Class + false + + + + #Class + In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.The following Bicycle class is one possible implementation of a bicycle:The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. Classes are the fundamental building blocks of a Java program. You can define an Employee class as follows: 1. By convention, class names capitalize the initial of each word. 2. For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator. 3. This type of naming convention is known as Pascal naming convention. 4. The other convention, the camel naming convention, capitalize the initial of each word, except the first word. 5. Method and field names use the camel naming convention.A class is a blueprint or prototype from which objects are created.^^http://www.w3.org/2001/XMLSchema#string + + + + #ClassBody + true + + + + #ClassConstantInitializationStatement + true + + + + #ClassConstantInitializationStatement + 'public static final' variables are constant.The naming convention for static final variables is to have them in upper case and separate two words with an underscore. For example:static final static final If you want to make a static final variable accessible from outside the class, you can make it public too:The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):static final double PI = 3.141592653589793;Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).Note:¬†If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value. + + + + #ClassDataType + true + + + + #ClassDataType + class as a data type + + + + #ClassDefinition + true + + + + #ClassDefinition + In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.The following Bicycle class is one possible implementation of a bicycle:The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. Classes are the fundamental building blocks of a Java program. You can define an Employee class as follows: 1. By convention, class names capitalize the initial of each word. 2. For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator. 3. This type of naming convention is known as Pascal naming convention. 4. The other convention, the camel naming convention, capitalize the initial of each word, except the first word. 5. Method and field names use the camel naming convention.You've seen classes defined in the following way:class MyClass { //field, constructor, and method declarations}This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.The preceding class declaration is a minimal one‚Äîit contains only those components of a class declaration that are required. You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration.You can also add modifiers like public or private at the very beginning‚Äîso you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private, which determine what other classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration. For the moment you do not need to worry about these extra complications.In general, class declarations can include these components, in order: 1. Modifiers such as public, private, and a number of others that you will encounter later. 2. The class name, with the initial letter capitalized by convention. 3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 5. The class body, surrounded by braces, {}. + + + + #ClassField + true + + + + #ClassField + Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. 1. Static members are not tied to class instances. 2. Static members can be called without having an instance.In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles, as follows:Class variables are referenced by the class name itself, as inThis makes it clear that they are class variables.A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.^^http://www.w3.org/2001/XMLSchema#string + + + + #ClassFieldDefinitionStatement + true + + + + #ClassFieldDefinitionStatement + 1. You can use the keyword static in front of a field declaration. 2. The static keyword may come before or after the access modifier. You can only declare a static variable in a class level.In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles, as follows:Class variables are referenced by the class name itself, as inThis makes it clear that they are class variables. + + + + #ClassMemberDefinition + false + + + + #ClassMemberInvocation + false + + + + #ClassName + true + + + + #ClassSingnature + true + + + + #ConditionalExpression + true + + + + #ConditionalExpression + The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)). ‚Ä¢ ConditionalExpression: ‚Ä¢ ConditionalOrExpression ‚Ä¢ ConditionalOrExpression ? Expression : ConditionalExpression ‚Ä¢ The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.The first expression must be of type boolean, or a compile-time error occurs.The conditional operator may be used to choose between second and third operands of numeric type, or second and third operands of type boolean, or second and third operands that are each of either reference type or the null type. All other cases result in a compile-time error.Note that it is not permitted for either the second or the third operand expression to be an invocation of a void method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear (¬ß14.8).At run time, the first operand expression of the conditional expression is evaluated first; its boolean value is then used to choose either the second or the third operand expression: ‚Ä¢ If the value of the first operand is true, then the second operand expression is chosen. ‚Ä¢ If the value of the first operand is false, then the third operand expression is chosen.The chosen operand expression is then evaluated and the resulting value is converted to the type of the conditional expression as determined by the rules stated above. The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.Ternary operator '? :' a shortcut for trivial if-else based calculations^^http://www.w3.org/2001/XMLSchema#string + + + + #Constant + true + + + + #Constant + 1. Using the final keyword to declare a variable. 2. The final keyword specifies that the value of a variable is final and cannot be changed. 3. It is a convention in Java to write constants in uppercase letters. You can prefix a variable declaration with the keyword final to make its value unchangeable. You can make both local variables and class fields final. 1. Once assigned a value, the final value cannot change. 2. Attempting to change it will result in a compile error. + + + + #ConstantInitializationStatement + true + + + + #ConstantInitializationStatement + 1. Using the final keyword to declare a variable. 2. The final keyword specifies that the value of a variable is final and cannot be changed. 3. It is a convention in Java to write constants in uppercase letters. You can prefix a variable declaration with the keyword final to make its value unchangeable. You can make both local variables and class fields final. 1. Once assigned a value, the final value cannot change. 2. Attempting to change it will result in a compile error. + + + + #ConstantInvocation + true + + + + #ConstantInvocation + class constants (final fields) are usually defined as public static final. One can invoke them the same way methods are invoked, Since theay are usually defined as static, no object needs ot be created to call them, class name is used instead. + + + + #Constructor + false + + + + #Constructor + 1. Every class must have at least one constructor. 2. If there is no constructors for your class, the compiler will supply a default constructor(no-arg constructor). 3. A constructor is used to construct an object. 4. A constructor looks like a method and is sometimes called a constructor method. 5. A constructor never returns a value 6. A constructor always has the same name as the class. 7. A constructor may have zero argument, in which case it is called a no-argument (or no-arg, for short) constructor. 8. Constructor arguments can be used to initialize the fields in the object.The syntax for a constructor is as follows. + + + + #ConstructorCall + true + + + + #ConstructorCall + A class instance creation expression is used to create new objects that are instances of classes.Class instance creation expressions have two forms:Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (¬ß15.9.5) and creates an instance of it.We say that a class is instantiated when an instance of the class is created by a class instance creation expression. Class instantiation involves determining what class is to be instantiated, what the enclosing instances (if any) of the newly created instance are, what constructor should be invoked to create the new instance and what arguments should be passed to that constructor.If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class.The type of the class instance creation expression is the class type being instantiated.At run time, evaluation of a class instance creation expression is as follows.First, if the class instance creation expression is a qualified class instance creation expression, the qualifying primary expression is evaluated. If the qualifying expression evaluates to null, a NullPointerException is raised, and the class instance creation expression completes abruptly. If the qualifying expression completes abruptly, the class instance creation expression completes abruptly for the same reason.Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError (¬ß15.9.6).The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (¬ß4.5.5).Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (¬ß8.8) and is described in detail in ¬ß12.5.The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.Call of the constructor creates an new object and returns a refernece to to it^^http://www.w3.org/2001/XMLSchema#string + + + + #ConstructorDefinition + true + + + + #ConstructorDefinition + 1. Every class must have at least one constructor. 2. If there is no constructors for your class, the compiler will supply a default constructor(no-arg constructor). 3. A constructor is used to construct an object. 4. A constructor looks like a method and is sometimes called a constructor method. 5. A constructor never returns a value 6. A constructor always has the same name as the class. 7. A constructor may have zero argument, in which case it is called a no-argument (or no-arg, for short) constructor. 8. Constructor arguments can be used to initialize the fields in the object.The syntax for a constructor is as follows.A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations‚Äîexcept that they use the name of the class and have no return type. For example, Bicycle has one constructor:To create a new Bicycle object called myBike, a constructor is called by the new operator:Bicycle myBike = new Bicycle(30, 0, 8);new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.Although Bicycle only has one constructor, it could have others, including a no-argument constructor:Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.You can use a superclass constructor yourself. The MountainBike class at the beginning of this lesson did just that. This will be discussed later, in the lesson on interfaces and inheritance.You can use access modifiers in a constructor's declaration to control which other classes can call the constructor. + + + + #ConstructorName + true + + + + #ConstructorSignature + true + + + + #ContinueStatement + true + + + + #ContinueStatement + The continue statement stops the execution of the current iteration and causes control to begin with the next iteration.The continue statement: skips all or part of a loop iterationThe continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.continue statement (interrupts current loop iteration)^^http://www.w3.org/2001/XMLSchema#string + + + + #DOM + true + + + + #Data + false + + + + #Data + Superconcept of everytrhing related to Data types, different kinds of variables, their values and operations with viriables + + + + #DataType + false + + + + #DataType + Data type + + + + #DefaultAccessSpecifier + true + + + + #DefaultAccessSpecifier + The default access is that a member can be accessed anywhere within the package that contains its declaration; other possibilities are public, protected, and private.if none of the access modifiers public, protected, or private are specified, a class member or constructor is accessible throughout the package that contains the declaration of the class in which the class member is declared, but the class member or constructor is not accessible in any other package.If a public class has a method or constructor with default access, then this method or constructor is not accessible to or inherited by a subclass declared outside this package.For example, if we have:then a subclass in another package may declare an unrelated move method, with the same signature (¬ß8.3.2) and return type. Because the original move method is not accessible from package morepoints, super may not be used: + + + + #DefaultClause + true + + + + #DefaultClause + The default section handles all values that aren't explicitly handled by one of the case sections.default clause - final option of the switch statement^^http://www.w3.org/2001/XMLSchema#string + + + + #DefinitionStatement + false + + + + #DivideAssignmentExpression + true + + + + #DivideAssignmentExpression + All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Divide the value of the varibale to the left by the value of the expression to the right and assigns the result to the variable to the left '=/'^^http://www.w3.org/2001/XMLSchema#string + + + + #DivideExpression + true + + + + #DivideExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. / division operatorThe binary / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor.Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (¬ß5.6.2) is an integer value q whose magnitude is as large as possible while satisfying ; moreover, q is positive when and n and d have the same sign, but q is negative when and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.Division operator '/'^^http://www.w3.org/2001/XMLSchema#string + + + + #DoStatement + true + + + + #DoStatement + The do-while statement is like the while statement, except that the associated block always gets executed at least once.Its syntax is as follows:Just like the while statement, you can omit the braces if there is only one statement within them. However, always use braces for the sake of clarity.The following do-while demonstrates that at least the code in the do block will be executed once even though the initial value of j used to test the expression j < 3 evaluates to false.he Java programming language also provides a do-while statement, which can be expressed as follows:do { statement(s)} while (expression);The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false. ‚Ä¢ DoStatement: ‚Ä¢ do Statement while ( Expression ) ; ‚Ä¢ The Expression must have type boolean, or a compile-time error occurs.A do statement is executed by first executing the Statement. Then there is a choice: ‚Ä¢ If execution of the Statement completes normally, then the Expression is evaluated. If evaluation of the Expression completes abruptly for some reason, the do statement completes abruptly for the same reason. Otherwise, there is a choice based on the resulting value: ‚ó¶ If the value is true, then the entire do statement is executed again. ‚ó¶ If the value is false, no further action is taken and the do statement completes normally. ‚Ä¢ If execution of the Statement completes abruptly, see ¬ß14.12.1 below.Executing a do statement always executes the contained Statement at least once.do-while loop (postcondition)^^http://www.w3.org/2001/XMLSchema#string + + + + #DoubleDataType + true + + + + #DoubleDataType + double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. double-precision folating-point type in Java for numbers from -10^308 to10^308 and up 15 significant deciamal digits (reserved word double)^^http://www.w3.org/2001/XMLSchema#string + + + + #DoubleValue + true + + + + #DoubleValue + A floating-point literal has the following parts: a whole-number part, a decimal point (represented by an ASCII period character), a fractional part, an exponent, and a type suffix. The exponent, if present, is indicated by the ASCII letter e or E followed by an optionally signed integer.At least one digit, in either the whole number or the fraction part, and either a decimal point, an exponent, or a float type suffix are required. All other parts are optional.A floating-point literal is of type double and it can optionally be suffixed with an ASCII letter D or d. + + + + #Encapsulation + true + + + + #Encapsulation + The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private. Other access modifiers will be discussed later. ‚Ä¢ private modifier‚Äîthe field is accessible only within its own class.In the spirit of encapsulation, it is common to make fields private. This means that they can only be directly accessed from the Bicycle class. We still need access to these values, however. This can be done indirectly by adding public methods that obtain the field values for us:Encapsulation is the hiding of the internal mechanisms and data structures of a class behind its public interface, in such a way that users of the component (other pieces of software) only need to know what the class does not and cannot make themselves dependent on the details of class implementation.^^http://www.w3.org/2001/XMLSchema#string + + + + #EqualExpression + true + + + + #EqualExpression + The equality operators are syntactically left-associative (they group left-to-right), but this fact is essentially never useful; for example, a==b==c parses as (a==b)==c. The result type of a==b is always boolean, and c must therefore be of type boolean or a compile-time error occurs. Thus, a==b==c does not test to see whether a, b, and c are all equal.The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, a<b==c<d is true whenever a<b and c<d have the same truth value.The equality operators may be used to compare two operands of numeric type, or two operands of type boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always boolean.In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative if the operand expressions have no side effects.Logical equality (equal-to operator) '=='^^http://www.w3.org/2001/XMLSchema#string + + + + #ExceptionClass + true + + + + #ExceptionClass + Every exception is represented by an instance of the class Throwable or one of its subclasses; such an object can be used to carry information from the point at which an exception occurs to the handler that catches it. The possible exceptions in a program are organized in a hierarchy of classes, rooted at class Throwable (¬ß11.5), a direct subclass of Object. The classes Exception and Error are direct subclasses of Throwable. The class RuntimeException is a direct subclass of Exception.Programs can use the pre-existing exception classes in throw statements, or define additional exception classes, as subclasses of Throwable or of any of its subclasses, as appropriate. To take advantage of the Java platform's compile-time checking for exception handlers, it is typical to define most new exception classes as checked exception classes, specifically as subclasses of Exception that are not subclasses of RuntimeException.The class Exception is the superclass of all the exceptions that ordinary programs may wish to recover from. The class RuntimeException is a subclass of class Exception. The subclasses of RuntimeException are unchecked exception classes. The subclasses of Exception other than RuntimeException are all checked exception classes.The class Error and its subclasses are exceptions from which ordinary programs are not ordinarily expected to recover. See the Java API specification for a detailed description of the exception hierarchy.The class Error is a separate subclass of Throwable, distinct from Exception in the class hierarchy, to allow programs to use the idiom.to catch all exceptions from which recovery may be possible without catching errors from which recovery is typically not possible. + + + + #ExceptionHandlingStatement + false + + + + #ExplicitTypeCasting + true + + + + #ExplicitTypeCasting + Casting conversion is applied to the operand of a cast operator (¬ß15.16): the type of the operand expression must be converted to the type explicitly named by the cast operator. Casting contexts allow the use of an identity conversion (¬ß5.1.1), a widening primitive conversion (¬ß5.1.2), a narrowing primitive conversion (¬ß5.1.3), a widening reference conversion (¬ß5.1.4), or a narrowing reference conversion (¬ß5.1.5). Thus casting conversions are more inclusive than assignment or method invocation conversions: a cast can do any permitted conversion other than a string conversion.Some casts can be proven incorrect at compile time; such casts result in a compile-time error.A value of a primitive type can be cast to another primitive type by identity conversion, if the types are the same, or by a widening primitive conversion or a narrowing primitive conversion.A value of a primitive type cannot be cast to a reference type by casting conversion, nor can a value of a reference type be cast to a primitive type.A cast expression converts, at run time, a value of one numeric type to a similar value of another numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type. ‚Ä¢ CastExpression: ‚Ä¢ ( PrimitiveType Dimsopt ) UnaryExpression ‚Ä¢ ( ReferenceType ) UnaryExpressionNotPlusMinus ‚Ä¢ See ¬ß15.15 for a discussion of the distinction between UnaryExpression and UnaryExpressionNotPlusMinus.The type of a cast expression is the type whose name appears within the parentheses. (The parentheses and the type they contain are sometimes called the cast operator.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.A cast operator has no effect on the choice of value set (¬ß4.2.3) for a value of type float or type double. Consequently, a cast to type float within an expression that is not FP-strict (¬ß15.4) does not necessarily cause its value to be converted to an element of the float value set, and a cast to type double within an expression that is not FP-strict does not necessarily cause its value to be converted to an element of the double value set.At run time, the operand value is converted by casting conversion (¬ß5.5) to the type specified by the cast operator.Not all casts are permitted by the language. Some casts result in an error at compile time. For example, a primitive value may not be cast to a reference type. Some casts can be proven, at compile time, always to be correct at run time. For example, it is always correct to convert a value of a class type to the type of its superclass; such a cast should require no special action at run time. Finally, some casts cannot be proven to be either always correct or always incorrect at compile time. Such casts require a test at run time. + + + + #Expression + false + + + + #Expression + An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. + + + + #ExpressionStatement + true + + + + #ExpressionStatement + Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).Such statements are called expression statements. Here are some examples of expression statements.In addition to expression statements, there are two other kinds of statements:Some expressions can be made statements by terminating them with a semicolon. For example, x++ is an expression. However, this is a statement:x++;Certain kinds of expressions may be used as statements by following them with semicolons:An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.Expression statement consits of an assignement expression or relational operator expression or incremenet/decremenet expassion and a semicolon^^http://www.w3.org/2001/XMLSchema#string + + + + #ExtendsSpecification + true + + + + #ExtendsSpecification + Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:A diagram of classes in a hierarchy.A hierarchy of bicycle classes.The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here}This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.You extend a class by using the extends keyword in a class declaration,The Parent classThe Child class + + + + #False + true + + + + #False + The boolean type has two values, represented by literals 'false' and ...The following code declares a boolean variable includeSign and assigns it the value of false.The boolean type has two values, represented by the literals true and false, formed from ASCII letters.A boolean literal is always of type boolean.Logical false value (reserved word "false")^^http://www.w3.org/2001/XMLSchema#string + + + + #Field + false + + + + #FieldDefinition + true + + + + #FieldDefinition + The variables of a class type are introduced by field declarations:The FieldModifiers are described in ¬ß8.3.1. The Identifier in a FieldDeclarator may be used in a name to refer to the field. Fields are members; the scope (¬ß6.3) of a field declaration is specified in ¬ß8.1.5. More than one field may be declared in a single field declaration by using more than one declarator; the FieldModifiers and Type apply to all the declarators in the declaration. Variable declarations involving array types are discussed in ¬ß10.2.The access modifiers public, protected, and private are discussed in ¬ß6.6. A compile-time error occurs if the same modifier appears more than once in a field declaration, or if a field declaration has more than one of the access modifiers public, protected, and private.If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.Initialization expressions for instance variables may use the simple name of any static variable declared in or inherited by the class, even one whose declaration occurs textually later.Thus the example:compiles without error; it initializes j to 1 when class Test is initialized, and initializes f to the current value of j every time an instance of class Test is created.Initialization expressions for instance variables are permitted to refer to the current object this (¬ß15.8.3) and to use the keyword super (¬ß15.11.2, ¬ß15.12).Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. See ¬ß8.3.2.3 for the precise rules governing forward reference to instance variables. + + + + #FieldDefinitionStatement + false + + + + #FieldDefinitionStatement + variable declaration (including variable type and variable name) +it is a part of the declaration statement + + + + #FieldInheritance + true + + + + #FieldInheritance + If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class. The field declaration also shadows (¬ß6.3.1) declarations of any accessible fields in enclosing classes or interfaces, and any local variables, formal method parameters, and exception handler parameters with the same name in any enclosing blocks.If a field declaration hides the declaration of another field, the two fields need not have the same type.A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.Note that a private field of a superclass might be accessible to a subclass (for example, if both classes are members of the same class). Nevertheless, a private field is never inherited by a subclass.It is possible for a class to inherit more than one field with the same name (¬ß8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.A class may inherit two or more fields with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited field by its simple name. A qualified name or a field access expression that contains the keyword super (¬ß15.11.2) may be used to access such fields unambiguously. In the example:Subclass inherits all instance fields and class fields of the superclass. ^^http://www.w3.org/2001/XMLSchema#string + + + + #FinalClass + false + + + + #FinalClass + You can prevent others from extending your class by making it final using the keyword final in the class declaration.Note that you can also declare an entire class final ‚Äî this prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class. + + + + #FinalClass + + + + + #FinalClassDefinition + true + + + + #FinalClassDefinition + You can prevent others from extending your class by making it final using the keyword final in the class declaration.Note that you can also declare an entire class final ‚Äî this prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class. + + + + #FinalInstanceFieldInitializationStatement + true + + + + #FinalInstanceFieldInitializationStatement + If a field declarator contains a variable initializer, then it has the semantics of an assignment (¬ß15.26) to the declared variable, and: ‚Ä¢ If the declarator is for a class variable (that is, a static field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized One subtlety here is that, at run time, static variables that are final and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (¬ß9.3.1). These variables are "constants" that will never be observed to have their default initial values (¬ß4.5.5), even by devious programs. See ¬ß12.4.2 and ¬ß13.4.8 for more discussion. Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See ¬ß8.3.2.3 for the precise rules governing forward reference to class variables. + + + + #FinalMethod + false + + + + #FinalMethod + You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this‚Äîa number of its methods are final.You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. + + + + #FinalMethodDefintion + true + + + + #FinalMethodDefintion + You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this‚Äîa number of its methods are final.You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. + + + + #FinalModifier + true + + + + #FinalModifier + You can prevent others from extending your class by making it final using the keyword final in the class declaration.Note that you can also declare an entire class final ‚Äî this prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class.You can prefix a variable declaration with the keyword final to make its value unchangeable. You can make both local variables and class fields final. 1. Once assigned a value, the final value cannot change. 2. Attempting to change it will result in a compile error.The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):static final double PI = 3.141592653589793;Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).Note:¬†If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this‚Äîa number of its methods are final.You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. + + + + #FloatDataType + true + + + + #FloatDataType + float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform. single-precision floating-point type in Java for number form -10^38 to 10^38 and up to 7 significant deciam digits (reserved word "float")^^http://www.w3.org/2001/XMLSchema#string + + + + #FloatValue + true + + + + #FloatValue + A floating-point literal has the following parts: a whole-number part, a decimal point (represented by an ASCII period character), a fractional part, an exponent, and a type suffix. The exponent, if present, is indicated by the ASCII letter e or E followed by an optionally signed integer.At least one digit, in either the whole number or the fraction part, and either a decimal point, an exponent, or a float type suffix are required. All other parts are optional.A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; + + + + #ForEachStatement + true + + + + #ForEachStatement + The general form of the for-each version of the for is shown here:for(type itr-var : iterableObj) statement-blockThe object referred to by iterableObj must be an array or an object that implements the new Iterable interface.The for-each loop is essentially read-onlyUsing the For-Each Loop with CollectionsUsing 'for each' to loop through arrayThe for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:int[] numbers = {1,2,3,4,5,6,7,8,9,10};The following program, EnhancedForDemo, uses the enhanced for to loop through the array:for-each loop (enhanced for loop) available starting from Java 5.0^^http://www.w3.org/2001/XMLSchema#string + + + + #ForStatement + true + + + + #ForStatement + The for statement is like the while statement, i.e. you use it to create loop. The for statement has following syntax: 1. init is an initialization that will be performed before the first iteration. 2. booleanExpression is a boolean expression which will cause the execution of statement(s) if it evaluates to true. 3. update is a statement that will be executed after the execution of the statement block. 4. init, expression, and update are optional.The for statement will stop only if one of the following conditions is met: 1. booleanExpression evaluates to false 2. A break or continue statement is executed 3. A runtime error occurs. It is common to declare a variable and assign a value to it in the initialization part. The variable declared will be visible to the expression and update parts as well as to the statement block.For example, the following for statement loops five times and each time prints the value of i. Note that the variable i is not visible anywhere else since it is declared within the for loop.The initialization part of the for statement is optional.The update statement is optional.You can even omit the booleanExpression part.If you compare for and while, you'll see that you can always replace the while statement with for. This is to say thatThe for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:for (initialization; termination; increment) { statement(s)}When using this version of the for statement, keep in mind that: ‚Ä¢ The initialization expression initializes the loop; it's executed once, as the loop begins. ‚Ä¢ When the termination expression evaluates to false, the loop terminates. ‚Ä¢ The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.The three expressions of the for loop are optional; an infinite loop can be created as follows:for ( ; ; ) { // infinite loop // your code goes here}The for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.A for statement is executed by first executing the ForInit code: ‚Ä¢ If the ForInit code is a list of statement expressions (¬ß14.8), the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the for statement completes abruptly for the same reason; any ForInit statement expressions to the right of the one that completed abruptly are not evaluated.If the ForInit code is a local variable declaration, it is executed as if it were a local variable declaration statement (¬ß14.4) appearing in a block. The scope of a local variable declared in the ForInit part of a for statement (¬ß14.13) includes all of the following: ‚Ä¢ Its own initializer ‚Ä¢ Any further declarators to the right in the ForInit part of the for statement ‚Ä¢ The Expression and ForUpdate parts of the for statement ‚Ä¢ The contained StatementIf execution of the local variable declaration completes abruptly for any reason, the for statement completes abruptly for the same reason. ‚Ä¢ If the ForInit part is not present, no action is taken. Next, a for iteration step is performed, as follows: ‚Ä¢ If the Expression is present, it is evaluated, and if evaluation of the Expression completes abruptly, the for statement completes abruptly for the same reason. Otherwise, there is then a choice based on the presence or absence of the Expression and the resulting value if the Expression is present: ‚ó¶ If the Expression is not present, or it is present and the value resulting from its evaluation is true, then the contained Statement is executed. Then there is a choice: ‚ñ™ If execution of the Statement completes normally, then the following two steps are performed in sequence: ‚ñ™ First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the for statement completes abruptly for the same reason; any ForUpdate statement expressions to the right of the one that completed abruptly are not evaluated. If the ForUpdate part is not present, no action is taken. ‚ñ™ Second, another for iteration step is performed. ‚ñ™ If execution of the Statement completes abruptly, see ¬ß14.13.3 below. ‚ó¶ If the Expression is present and the value resulting from its evaluation is false, no further action is taken and the for statement completes normally.If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement.for loop (counter)^^http://www.w3.org/2001/XMLSchema#string + + + + #FormalMethodParameter + true + + + + #FormalMethodParameter + Parameters You've already seen examples of parameters, both in the Bicycle class and in the main method of the "Hello World!" application. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the tutorial. Primitive variables are passed by value.# When you pass a primitive variable, the JVM will copy the value of the passed-in variable to a new local variable.# If you change the value of the local variable, the change will not affect the passed in primitive variable.reference variables are passed by reference.# If you pass a reference variable, the local variable will refer to the same object as the passed in reference variable.# If you change the object referenced within your method, the change will also be reflected in the calling code.The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.Note:¬†Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and arrays.Here's an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y coordinate):When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor.A parameter can have the same name as one of the class's fields. If this is the case, the parameter is said to shadow the field. Shadowing fields can make your code difficult to read and is conventionally used only within constructors and methods that set a particular field. For example, consider the following Circle class and its setOrigin method: + + + + #GenericClass + false + + + + #GenericClass + Let's update our Box class to use generics. We'll first create a generic type declaration by changing the code "public class Box" to "public class Box<T>"; this introduces one type variable, named T, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There's nothing particularly complex about this concept. In fact, it's quite similar to what you already know about variables in general. Just think of T as a special kind of variable, whose "value" will be whatever type you pass in; this can be any class type, any interface type, or even another type variable. It just can't be any of the primitive data types. In this context, we also say that T is a formal type parameter of the Box class.As you can see, we've replaced all occurrences of Object with T. To reference this generic class from within your own code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:It's important to understand that type variables are not actually types themselves. In the above examples, you won't find T.java or T.class anywhere on the filesystem. Furthermore, T is not a part of the Box class name. In fact during compilation, all generic information will be removed entirely, leaving only Box.class on the filesystem. We'll discuss this later in the section on Type ErasureAlso note that a generic type may have multiple type parameters, but each parameter must be unique within its declaring class or interface. A declaration of Box<T,T>, for example, would generate an error on the second occurrence of T, but Box<T,U>, however, would be allowed.Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared.Here we've added one generic method, named inspect, that defines one type parameter, named U. This method accepts an object and prints its type to standard output. For comparison, it also prints out the type of T. For convenience, this class now also has a main method so that it can be run as an application.A more realistic use of generic methods might be something like the following, which defines a static method that stuffs references to a single item into multiple boxes:To use this method, your code would look something like the following:The complete syntax for invoking this method is:Here we've explicitly provided the type to be used as U, but more often than not, this can be left out and the compiler will infer the type that's needed:This feature, known as type inference, allows you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets. + + + + #GenericClassDefinition + true + + + + #GenericClassDefinition + Let's update our Box class to use generics. We'll first create a generic type declaration by changing the code "public class Box" to "public class Box<T>"; this introduces one type variable, named T, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There's nothing particularly complex about this concept. In fact, it's quite similar to what you already know about variables in general. Just think of T as a special kind of variable, whose "value" will be whatever type you pass in; this can be any class type, any interface type, or even another type variable. It just can't be any of the primitive data types. In this context, we also say that T is a formal type parameter of the Box class.As you can see, we've replaced all occurrences of Object with T. To reference this generic class from within your own code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:It's important to understand that type variables are not actually types themselves. In the above examples, you won't find T.java or T.class anywhere on the filesystem. Furthermore, T is not a part of the Box class name. In fact during compilation, all generic information will be removed entirely, leaving only Box.class on the filesystem. We'll discuss this later in the section on Type ErasureAlso note that a generic type may have multiple type parameters, but each parameter must be unique within its declaring class or interface. A declaration of Box<T,T>, for example, would generate an error on the second occurrence of T, but Box<T,U>, however, would be allowed.Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared.Here we've added one generic method, named inspect, that defines one type parameter, named U. This method accepts an object and prints its type to standard output. For comparison, it also prints out the type of T. For convenience, this class now also has a main method so that it can be run as an application.A more realistic use of generic methods might be something like the following, which defines a static method that stuffs references to a single item into multiple boxes:To use this method, your code would look something like the following:The complete syntax for invoking this method is:Here we've explicitly provided the type to be used as U, but more often than not, this can be left out and the compiler will infer the type that's needed:This feature, known as type inference, allows you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets. + + + + #GenericObjectCreationStatement + true + + + + #GenericObjectCreationStatement + You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you're passing a type argument ‚Äî Integer in this case ‚Äî to the Box class itself. Like any other variable declaration, this code does not actually create a new Box object. It simply declares that integerBox will hold a reference to a "Box of Integer", which is how Box<Integer> is read.An invocation of a generic type is generally known as a parameterized type.To instantiate this class, use the new keyword, as usual, but place <Integer> between the class name and the parenthesis:Or, you can put the entire statement on one line, such as:Box<Integer> integerBox = new Box<Integer>();Once integerBox is initialized, you're free to invoke its get method without providing a cast, as in BoxDemo3:Furthermore, if you try adding an incompatible type to the box, such as String, compilation will fail, alerting you to what previously would have been a runtime bug: + + + + #GotoStatement + true + + + + #GotoStatement + go-to statement (the most hated programming statement) + + + + #GreaterEqualExpression + true + + + + #GreaterEqualExpression + The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.The type of a relational expression is always boolean.Numerical Comparison Operators <, <=, >, and >= ‚Ä¢ The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.Greater than or equal to '>='^^http://www.w3.org/2001/XMLSchema#string + + + + #GreaterExpression + true + + + + #GreaterExpression + The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.The type of a relational expression is always boolean.Numerical Comparison Operators <, <=, >, and >= ‚Ä¢ The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.Greater than '>'^^http://www.w3.org/2001/XMLSchema#string + + + + #Identifier + false + + + + #IfElseIfStatement + true + + + + #IfElseIfStatement + if-else-if statement (conditional statement with many options - switch substitute) + + + + #IfElseStatement + true + + + + #IfElseStatement + The if statement is a conditional branch statement. The syntax of the if statement is either one of these twoIn the following example, the if block will be executed if a is greater than 3. Otherwise, the else block will be executed.The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.An if-then-else statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, then the if-then-else statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value: ‚Ä¢ If the value is true, then the first contained Statement (the one before the else keyword) is executed; the if-then-else statement completes normally if and only if execution of that statement completes normally. ‚Ä¢ If the value is false, then the second contained Statement (the one after the else keyword) is executed; the if-then-else statement completes normally if and only if execution of that statement completes normally.if-else statement (conditional statement with two options)^^http://www.w3.org/2001/XMLSchema#string + + + + #IfStatement + true + + + + #IfStatement + The if statement is a conditional branch statement. The syntax of the if statement is either one of these twoFor example, in the following if statement, the if block will be executed if x is greater than 4.The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion.f this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.An if-then statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the if-then statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value: ‚Ä¢ If the value is true, then the contained Statement is executed; the if-then statement completes normally if and only if execution of the Statement completes normally. ‚Ä¢ If the value is false, no further action is taken and the if-then statement completes normally.simple if statement (conditional statement with one option)^^http://www.w3.org/2001/XMLSchema#string + + + + #ImplementsSpecification + true + + + + #ImplementsSpecification + As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. An implementation class has to override all methods in the interface. 2. A class can implement multiple interfaces. + + + + #ImplicitTypeCasting + true + + + + #ImplicitTypeCasting + Every expression written in the Java programming language has a type that can be deduced from the structure of the expression and the types of the literals, variables, and methods mentioned in the expression. It is possible, however, to write an expression in a context where the type of the expression is not appropriate. In some cases, this leads to an error at compile time; for example, if the expression in an if statement (¬ß14.9) has any type other than boolean, a compile-time error occurs. In other cases, the context may be able to accept a type that is related to the type of the expression; as a convenience, rather than requiring the programmer to indicate a type conversion explicitly, the language performs an implicit conversion from the type of the expression to a type acceptable for its surrounding context.Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of an identity conversion (¬ß5.1.1) or a widening primitive conversion (¬ß5.1.2).Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. The two kinds of numeric promotion are unary numeric promotion (¬ß5.6.1) and binary numeric promotion (¬ß5.6.2). The analogous conversions in C are called "the usual unary conversions" and "the usual binary conversions."Numeric promotion is not a general feature of the Java programming language, but rather a property of the specific definitions of the built-in operations. + + + + #ImportStatement + true + + + + #ImportStatement + Java provides the keyword import to indicate that you want to use a package or a class from a package. For example, to use the java.io.File class, you must have the following import statement: 1. 'import' statements must come after the package statement but before the class declaration. 2. The import keyword can appear multiple times in a class. You can import all classes in the same package by using the wild character *. For example, the following code imports all members of the java.io package. However, to make your code more readable, it is recommended that you import a package member one at a time. Members of the java.lang package are imported automatically. Thus, to use the java.lang.String, for example, you do not need to explicitly import the class.The only way to use classes that belong to other packages without importing them is to use the fully qualified names of the classes in your code. For example, the following code declares the java.io.File class using its fully qualified name.If you class import identically-named classes from different packages, you must use the fully qualified names when declaring the classes. For example, the Java core libraries contain the classes java.sql.Date and java.util.Date. In this case, you must write the fully qualified names of java.sql.Date and java.util.Date to use them.The types that comprise a package are known as the package members.To use a public package member from outside its package, you must do one of the following: ‚Ä¢ Refer to the member by its fully qualified name ‚Ä¢ Import the package member ‚Ä¢ Import the member's entire packageEach is appropriate for different situations, as explained in the sections that follow.So far, most of the examples in this tutorial have referred to types by their simple names, such as Rectangle and StackOfInts. You can use a package member's simple name if the code you are writing is in the same package as that member or if that member has been imported.However, if you are trying to use a member from a different package and that package has not been imported, you must use the member's fully qualified name, which includes the package name. Here is the fully qualified name for the Rectangle class declared in the graphics package in the previous example.You could use this qualified name to create an instance of graphics.Rectangle:Qualified names are all right for infrequent use. When a name is used repetitively, however, typing the name repeatedly becomes tedious and the code becomes difficult to read. As an alternative, you can import the member or its package and then use its simple name.To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here's how you would import the Rectangle class from the graphics package created in the previous section.import graphics.Rectangle;Now you can refer to the Rectangle class by its simple name.Rectangle myRectangle = new Rectangle();This approach works well if you use just a few members from the graphics package. But if you use many types from a package, you should import the entire package.To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character.import graphics.*;Now you can refer to any class or interface in the graphics package by its simple name.The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the graphics package that begin with A.Instead, it generates a compiler error. With the import statement, you generally import only a single package member or an entire package.Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its nested classes by using the following two statements.For convenience, the Java compiler automatically imports three entire packages for each source file: (1) the package with no name, (2) the java.lang package, and (3) the current package (the package for the current file). + + + + #IncrementDecrementExpression + false + + + + #IncrementDecrementExpression + Incremenet and decrement operators + + + + #Inheritance + true + + + + #Inheritance + Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:A diagram of classes in a hierarchy.A hierarchy of bicycle classes.The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here}This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass. 1. You extend a class by creating a new class. 2. The former and the latter will then have a parent-child relationship. 3. The original class is the parent class or the base class or the superclass. 4. The new class is called a child class or a subclass or a derived class of the parent. 5. The process of extending a class in object-oriented programming is called inheritance. 6. In a subclass you can add new methods and new fields as well as override existing methods in the parent class to change their behaviors. 7. Inheritance gives you the opportunity to add some functionality that does not exist in the original class. 8. Inheritance can also change the behaviors of the existing class to better suit your needs. 9. The subclass and the superclass has an "is-a" relationship. Within a subclass you can access its superclass's public and protected methods and fields , but not the superclass's private methods. If the subclass and the superclass are in the same package, you can also access the superclass's default methods and fields.In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.Inheritance is a way to form new classes using classes that have already been defined. +It provides a mechanism for organizing and structuring classes into hierarchies.^^http://www.w3.org/2001/XMLSchema#string + + + + #InheritanceBasedPolymorphism + true + + + + #InheritanceBasedPolymorphism + It means the ability of a single variable of a given type to be used to reference objects of different types and to automatically call the method that is specific to the type of object the variable references.polymorphism works with derived class objects.When a subclasses overrride methods of a superclass, a variable declared as asuperclass will invoke differnt methods depending on the actual sublcass type of the obejct referred by the variable^^http://www.w3.org/2001/XMLSchema#string + + + + #InnerClass + false + + + + #InnerClassDefinition + true + + + + #InnerClassDefinition + An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (¬ß8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (¬ß15.28).To illustrate these rules, consider the example below:Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language. Member interfaces (¬ß8.5) are always implicitly static so they are never considered to be inner classes. + + + + #InstanceField + true + + + + #InstanceField + Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another. 1. Fields are variables. 2. They can be primitives or references to objects.For example, the Employee class has two fields, age and salary. 1. Field names should follow the camel naming convention. 2. The initial of each word in the field, except for the first word, is written with a capital letter. 3. For example: age, maxAge, address, validAddress, numberOfRows. Member variables in a class‚Äîthese are called fields. The Bicycle class uses the following lines of code to define its fields:public int cadence;public int gear;public int speed;Field declarations are composed of three components, in order: 1. Zero or more modifiers, such as public or private. 2. The field's type. 3. The field's name.The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class.Objects store their individual states in the fields declared without the static keyword. Instance fields are also known as instance variables because their values are unique to each instance of a class (to each object).^^http://www.w3.org/2001/XMLSchema#string + + + + #InstanceFieldDefinitionStatement + true + + + + #InstanceFieldDefinitionStatement + 1. Fields are variables. 2. They can be primitives or references to objects.For example, the Employee class has two fields, age and salary. 1. Field names should follow the camel naming convention. 2. The initial of each word in the field, except for the first word, is written with a capital letter. 3. For example: age, maxAge, address, validAddress, numberOfRows. Member variables in a class‚Äîthese are called fields. The Bicycle class uses the following lines of code to define its fields:public int cadence;public int gear;public int speed;Field declarations are composed of three components, in order: 1. Zero or more modifiers, such as public or private. 2. The field's type. 3. The field's name.The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class. + + + + #InstanceFieldInitializationStatement + true + + + + #InstanceFieldInvocation + true + + + + #InstanceOfExpression + true + + + + #InstanceOfExpression + The Type Comparison Operator instanceofThe instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface. The type of a RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The ReferenceType mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs.At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (¬ß15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.Checks whether the object is an instance of a class +(More spesifically, whether the object/interface variable stores a reference to the object of this particular class or one one of its subclasses)^^http://www.w3.org/2001/XMLSchema#string + + + + #IntDataType + true + + + + #IntDataType + int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead. integer data type for numbers between -2,147,483,648 and 2,147,483,647 (reserved word "int")^^http://www.w3.org/2001/XMLSchema#string + + + + #IntValue + true + + + + #IntValue + The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.The values of the integral types are integers in the following ranges: ‚Ä¢ For byte, from -128 to 127, inclusive ‚Ä¢ For short, from -32768 to 32767, inclusive ‚Ä¢ For int, from -2147483648 to 2147483647, inclusive ‚Ä¢ For long, from -9223372036854775808 to 9223372036854775807, inclusive ‚Ä¢ For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535 + + + + #Interface + false + + + + #InterfaceBasedPolymorphism + true + + + + #InterfaceBasedPolymorphism + The compile time type of a variable is always declared, and the compile time type of an expression can be deduced at compile time. The compile time type limits the possible values that the variable can hold or the expression can produce at run time. If a run-time value is a reference that is not null, it refers to an object or array that has a class, and that class will necessarily be compatible with the compile-time type.Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements (¬ß8.1.4) that interface.An object varibale declared using an interface type will invoke differnt methods depending on the actual class of the object reffered by the variable ^^http://www.w3.org/2001/XMLSchema#string + + + + #InterfaceBody + true + + + + #InterfaceClassConversion + true + + + + #InterfaceDataType + true + + + + #InterfaceDataType + Interface as a data type + + + + #InterfaceDefinition + true + + + + #InterfaceDefinition + As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. The interface should be regarded as a contract between a service provider and its clients. 4. In Java, the interface is a type.Follow this format to write an interface:1. Fields in an interface must be initialized and are implicitly public, static, and final. 2. You declare methods in an interface just as you would in a class. 3. Methods in an interface do not have a body. 4. All methods are implicitly public and abstractThere are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile‚Äîstop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated‚Äîthey can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.Defining an interface is similar to creating a new class:Note that the method signatures have no braces and are terminated with a semicolon.An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body. For example:The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.The interface body contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon, but no braces, because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public, so the public modifier can be omitted.An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted. + + + + #InterfaceImplementation + false + + + + #InterfaceImplementation + As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. An implementation class has to override all methods in the interface. 2. A class can implement multiple interfaces.To use an interface, you write a class that implements the interface. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. For example,To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.By convention, the implements clause follows the extends clause, if there is one.If you want to be able to compare the size of similar objects, no matter what they are, the class that instantiates them should implement Relatable.Any class can implement Relatable if there is some way to compare the relative "size" of objects instantiated from the class. For strings, it could be number of characters; for books, it could be number of pages; for students, it could be weight; and so forth. For planar geometric objects, area would be a good choice (see the RectanglePlus class that follows), while volume would work for three-dimensional geometric objects. All such classes can implement the isLargerThan() method.If you know that a class implements Relatable, then you know that you can compare the size of the objects instantiated from that class.Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable.Because RectanglePlus implements Relatable, the size of any two RectanglePlus objects can be compared + + + + #InterfaceName + true + + + + #InterfaceSignature + true + + + + #Interfacing + false + + + + #Interfacing + As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. The interface should be regarded as a contract between a service provider and its clients. 4. In Java, the interface is a type.Follow this format to write an interface:1. Fields in an interface must be initialized and are implicitly public, static, and final. 2. You declare methods in an interface just as you would in a class. 3. Methods in an interface do not have a body. 4. All methods are implicitly public and abstractThere are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile‚Äîstop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated‚Äîthey can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.Defining an interface is similar to creating a new class:Note that the method signatures have no braces and are terminated with a semicolon.^^http://www.w3.org/2001/XMLSchema#string + + + + #IterationStatement + false + + + + #IterationStatement + Java itereation (loop) statements + + + + #Java + false + + + + #Java + Abstract superconcept of Java + + + + #JavaDatabaseAccess + true + + + + #JavaDatabaseAccess + Java and Relational Databases + + + + #JavaLanguage + false + + + + #JavaLanguage + false + + + + #JavaLanguage + Superconcept of Java Programming Language. It combines Java syntax, data processing, structure of java programs, etc + + + + #JavaNetworking + true + + + + #JavaNetworking + Programming networking applications iin Java + + + + #JavaOOP + false + + + + #JavaOOP + Object-oriented programming iin Java + + + + #JavaPortability + true + + + + #JavaPortability + Portability issues of Java + + + + #JavaSequirity + true + + + + #JavaSequirity + Sequirity issues in Java + + + + #JavaStandardLibrary + false + + + + #JavaStandardLibrary + Java Standard Edition API Specification, Java SDK + + + + #JavaStandardLibraryClass + true + + + + #JavaStandardLibraryInterface + true + + + + #JavaStandardLibraryMethod + true + + + + #JavaStandardLibraryObject + true + + + + #JavaStandardLibraryPackage + true + + + + #JavaStandardLibraryPackage + A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. + + + + #JavaTechnology + false + + + + #JavaTechnology + Spesific aspects of Java tehcnology + + + + #JavaXMLProcessing + true + + + + #JavaXMLProcessing + XML parsing, genenration and processing in Java + + + + #JumpStatement + false + + + + #JumpStatement + Java jump statements + + + + #LessEqualExpression + true + + + + #LessEqualExpression + The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.The type of a relational expression is always boolean.Numerical Comparison Operators <, <=, >, and >= ‚Ä¢ The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.Less than or equal to '<='^^http://www.w3.org/2001/XMLSchema#string + + + + #LessExpression + true + + + + #LessExpression + The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.The type of a relational expression is always boolean.Numerical Comparison Operators <, <=, >, and >= ‚Ä¢ The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false. ‚Ä¢ The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.Less than '<'^^http://www.w3.org/2001/XMLSchema#string + + + + #LogicalExpression + false + + + + #LogicalExpression + Logical operators. The result of logical expressions have type boolean + + + + #LongDataType + true + + + + #LongDataType + long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. integer data type for numbers between -9,223.372,036,854,808 and 9,223.372,036,854,807 (reserved word "long")^^http://www.w3.org/2001/XMLSchema#string + + + + #LongValue + true + + + + #LongValue + The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.The values of the integral types are integers in the following ranges: ‚Ä¢ For byte, from -128 to 127, inclusive ‚Ä¢ For short, from -32768 to 32767, inclusive ‚Ä¢ For int, from -2147483648 to 2147483647, inclusive ‚Ä¢ For long, from -9223372036854775808 to 9223372036854775807, inclusive ‚Ä¢ For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535 + + + + #MainMethod + false + + + + #MainMethodDefintion + true + + + + #MainMethodDefintion + 1. A special method called main provides the entry point to an application. 2. An application can have many classes and only one of the classes needs to have the method main. 3. This method allows the class containing it to be invoked. + + + + #Method + false + + + + #MethodBody + true + + + + #MethodDefinition + true + + + + #MethodDefinition + 1. ethods define actions that a class's objects (or instances) can do. 2. A method has a declaration part and a body. 3. The declaration part consists of a return value, the method name, and a list of arguments. 4. The body contains code that perform the action. 5. The return type of a method can be a primitive, an object, or void. 6. The return type void means that the method returns nothing. 7. The declaration part of a method is also called the signature of the method.For example, here is the getSalary method that returns a double.Here is an example of a typical method declaration:public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) { //do the calculation here}The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}.More generally, method declarations have six components, in order: 1. Modifiers‚Äîsuch as public, private, and others you will learn about later. 2. The return type‚Äîthe data type of the value returned by the method, or void if the method does not return a value. 3. The method name‚Äîthe rules for field names apply to method names as well, but the convention is a little different. 4. The parameter list in parenthesis‚Äîa comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. 5. An exception list‚Äîto be discussed later. 6. The method body, enclosed between braces‚Äîthe method's code, including the declaration of local variables, goes here.Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.Definition:¬†Two of the components of a method declaration comprise the method signature‚Äîthe method's name and the parameter types.The signature of the method declared above is:calculateAnswer(double, int, double, double) + + + + #MethodImplementation + true + + + + #MethodInheritance + true + + + + #MethodInheritance + In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, with four fields and five methods. However, you didn't have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:The inherited fields can be used directly, just like any other fields.The inherited methods can be used directly as they are.Subclass inherits all methods of the superclass. ^^http://www.w3.org/2001/XMLSchema#string + + + + #MethodInvocation + false + + + + #MethodInvocationStatement + true + + + + #MethodInvocationStatement + You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:The first statement invokes rectOne's getArea() method and displays the results. The second line moves rectTwo because the move() method assigns new values to the object's origin.x and origin.y.As with instance fields, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. The new operator returns an object reference, so you can use the value returned from new to invoke a new object's methods:The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As shown, you can use the dot notation to invoke the new Rectangle's getArea() method to compute the area of the new rectangle.Some methods, such as getArea(), return a value. For methods that return a value, you can use the method invocation in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle:Remember, invoking a method on a particular object is the same as sending a message to that object. In this case, the object that getArea() is invoked on is the rectangle returned by the constructor.You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:The first statement invokes rectOne's getArea() method and displays the results. The second line moves rectTwo because the move() method assigns new values to the object's origin.x and origin.y.As with instance fields, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. The new operator returns an object reference, so you can use the value returned from new to invoke a new object's methods:The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As shown, you can use the dot notation to invoke the new Rectangle's getArea() method to compute the area of the new rectangle.Some methods, such as getArea(), return a value. For methods that return a value, you can use the method invocation in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle:Remember, invoking a method on a particular object is the same as sending a message to that object. In this case, the object that getArea() is invoked on is the rectangle returned by the constructor. + + + + #MethodName + true + + + + #MethodName + Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples: + + + + #MethodOverloading + Java allows you to have multiple methods having the same name, as long as each method accept different sets of argument types. In other words, in our example, it is legal to have these two methods in the same class.This technique is called method overloading. The return value of the method is not taken into consideration. As such, these two methods must not exist in the same class:A method's name with the types and sequence of the parameters form the method's signatureTypically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method‚Äîfor example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list.Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type. + + + + #MethodOverriding + true + + + + #MethodOverriding + 1. When you extends a class, you can change the behavior of a method in the parent class. 2. This is called method overriding. 3. This happens when you write in a subclass a method that has the same signature as a method in the parent class. 4. If only the name is the same but the list of arguments is not, then it is method overloading.An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error.Subclass can override methods of the superclass if these methods should behave differently for the objects fot eh subclass.^^http://www.w3.org/2001/XMLSchema#string + + + + #MethodSignature + true + + + + #Modifier + false + + + + #ModulusAssignmentExpression + true + + + + #ModulusAssignmentExpression + All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Find the reminder of the division of the value of the varibale to the left by the value of the expression to the right and assigns the result to the variable to the left '=%'^^http://www.w3.org/2001/XMLSchema#string + + + + #ModulusExpression + true + + + + #ModulusExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result. % remainder operatorThe binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.In Java programming language, it also accepts floating-point operands.The remainder operation for operands that are integers after binary numeric promotion (¬ß5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor. If the value of the divisor for an integer remainder operator is 0, then an ArithmeticException is thrown.The result of a floating-point remainder operation as computed by the % operator is not the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding division, not a truncating division, and so its behavior is not analogous to that of the usual integer remainder operator. Instead, the Java programming language defines % on floating-point operations to behave in a manner analogous to that of the integer remainder operator; this may be compared with the C library function fmod.Division reminder operator '%'^^http://www.w3.org/2001/XMLSchema#string + + + + #MultiplicativeExpression + false + + + + #MultiplicativeExpression + Multiplicative operators '*' '/' '%' + + + + #MultiplyAssignmentExpression + true + + + + #MultiplyAssignmentExpression + All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Multiply the value of the varibale to the left by the value of the expression to the right and assigns the result to the variable to the left '=*'^^http://www.w3.org/2001/XMLSchema#string + + + + #MultiplyExpression + true + + + + #MultiplyExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. * multiplication operatorThe binary * operator performs multiplication, producing the product of its operands. Multiplication is a commutative operation if the operand expressions have no side effects. While integer multiplication is associative when the operands are all of the same type, floating-point multiplication is not associative.If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.Multiplication Operator '-'^^http://www.w3.org/2001/XMLSchema#string + + + + #NestedStatement + true + + + + #NestedStatement + nested statement (statement inside another statement) + + + + #NotEqualExpression + true + + + + #NotEqualExpression + The equality operators are syntactically left-associative (they group left-to-right), but this fact is essentially never useful; for example, a==b==c parses as (a==b)==c. The result type of a==b is always boolean, and c must therefore be of type boolean or a compile-time error occurs. Thus, a==b==c does not test to see whether a, b, and c are all equal.The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, a<b==c<d is true whenever a<b and c<d have the same truth value.The equality operators may be used to compare two operands of numeric type, or two operands of type boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always boolean.In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative if the operand expressions have no side effects.Logical inequality (not-equal-to operator) '!='^^http://www.w3.org/2001/XMLSchema#string + + + + #NotExpression + true + + + + #NotExpression + The type of the operand expression of the unary ! operator must be boolean, or a compile-time error occurs. The type of the unary logical complement expression is boolean.At run time, the value of the unary logical complement expression is true if the operand value is false and false if the operand value is true.Boolean (Logical) NOT '!'^^http://www.w3.org/2001/XMLSchema#string + + + + #OOPPrinciple + false + + + + #Object + false + + + + #Object + Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.A circle with an inner circle filled with items, surrounded by gray wedges representing methods that allow access to the inner circle.A software object.Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation ‚Äî a fundamental principle of object-oriented programming.Consider a bicycle, for example:A picture of an object, with bibycle methods and instance variables.A bicycle modeled as a software object.By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.Bundling code into individual software objects provides a number of benefits, including: 1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. 2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. 3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code. 4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine. As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.Each of these statements has three parts (discussed in detail below): 1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. 2. Instantiation: The new keyword is a Java operator that creates the object. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life.^^http://www.w3.org/2001/XMLSchema#string + + + + #ObjectCreationStatement + true + + + + #ObjectCreationStatement + 1. Using the new keyword. 2. new is always followed by the constructor of the class.For example, to create an Employee object, you write:Here, 'employee' is an object reference of type Employee. 1. Once you have an object, you can call its methods and access its fields, by using the object reference. 2. You use a period (.) to call a method or a field.The following code, for instance, creates an Employee object and assigns values to its age and salary fields:When an object is created, the JVM also performs initialization that assign default values to fields.As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.Each of these statements has three parts (discussed in detail below): 1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. 2. Instantiation: The new keyword is a Java operator that creates the object. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object. The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.Note:¬†The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:This statement will be discussed in the next section.This class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as declared by the code (int a, int b). The following statement provides 23 and 94 as values for those arguments:A class instance creation expression is used to create new objects that are instances of classes.Class instance creation expressions have two forms:Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (¬ß15.9.5) and creates an instance of it.We say that a class is instantiated when an instance of the class is created by a class instance creation expression. Class instantiation involves determining what class is to be instantiated, what the enclosing instances (if any) of the newly created instance are, what constructor should be invoked to create the new instance and what arguments should be passed to that constructor.If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class.The type of the class instance creation expression is the class type being instantiated.At run time, evaluation of a class instance creation expression is as follows.First, if the class instance creation expression is a qualified class instance creation expression, the qualifying primary expression is evaluated. If the qualifying expression evaluates to null, a NullPointerException is raised, and the class instance creation expression completes abruptly. If the qualifying expression completes abruptly, the class instance creation expression completes abruptly for the same reason.Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError (¬ß15.9.6).The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (¬ß4.5.5).Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (¬ß8.8) and is described in detail in ¬ß12.5.The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.Object creation consists of object creation and a semicolon^^http://www.w3.org/2001/XMLSchema#string + + + + #ObjectEquality + true + + + + #ObjectEquality + If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (¬ß5.5). The run-time values of the two operands would necessarily be unequal.At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters. The contents of two strings s and t can be tested for equality by the method invocation s.equals(t)The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal‚Äîthat is, if the objects compared are the exact same object. + + + + #ObjectMethodInvocation + true + + + + #ObjectMethodInvocation + To call a method for a certain object you need to spesify the object and a the method separated by "." This operation calls to invoke a method. The method will operate on the data stored in object's fields and the parameters passed to the method. + + + + #ObjectReference + true + + + + #ObjectReference + An object is a class instance or an array.The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.A new class instance is implicitly created when the string concatenation operator + (¬ß15.18.1) is used in an expression, resulting in a new object of type String (¬ß4.3.3). A new array object is implicitly created when an array initializer expression (¬ß10.6) is evaluated; this can occur when a class or interface is initialized (¬ß12.4), when a new instance of a class is created (¬ß15.9), or when a local variable declaration statement is executed (¬ß14.4).There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable. + + + + #ObjectVariable + true + + + + #ObjectVariable + Variables are data placeholders. There are two data types in Java: 1. Reference types provides a reference to an object.Object varaibale storing a reference to the object representation in memory^^http://www.w3.org/2001/XMLSchema#string + + + + #Operator + false + + + + #Operator + Every expression in Java must have at least one operator + + + + #OperatorAssociativity + true + + + + #OperatorAssociativity + Associativity of operators (left to right or right to left) + + + + #OperatorPrecedence + true + + + + #OperatorPrecedence + As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left. If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated firstPrecedence of operators^^http://www.w3.org/2001/XMLSchema#string + + + + #OrExpression + true + + + + #OrExpression + The || operator is like | (¬ß15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)||(b))||(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)||((b)||(c)).Each operand of || must be of type boolean, or a compile-time error occurs. The type of a conditional-or expression is always boolean.At run time, the left-hand operand expression is evaluated first; if its value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated and its value becomes the value of the conditional-or expression.Thus, || computes the same result as | on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.Boolean (Logical) OR '||'^^http://www.w3.org/2001/XMLSchema#string + + + + #OverridingClone + true + + + + #OverridingClone + If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method to create a copy from an existing object. To create a clone, you write:aCloneableObject.clone();Object's implementation of this method checks to see whether the object on which clone() was invoked implements the Cloneable interface. If the object does not, the method throws a CloneNotSupportedException exception. Exception handling will be covered in a later lesson. For the moment, you need to know that clone() must be declared asprotected Object clone() throws CloneNotSupportedException -- or --public Object clone() throws CloneNotSupportedExceptionif you are going to write a clone() method to override the one in Object.If the object on which clone() was invoked does implement the Cloneable interface, Object's implementation of the clone() method creates an object of the same class as the original object and initializes the new object's member variables to have the same values as the original object's corresponding member variables.The simplest way to make your class cloneable is to add implements Cloneable to your class's declaration. then your objects can invoke the clone() method.For some classes, the default behavior of Object's clone() method works just fine. If, however, an object contains a reference to an external object, say ObjExternal, you may need to override clone() to get correct behavior. Otherwise, a change in ObjExternal made by one object will be visible in its clone also. This means that the original object and its clone are not independent‚Äîto decouple them, you must override clone() so that it clones the object and ObjExternal. Then the original object references ObjExternal and the clone references a clone of ObjExternal, so that the object and its clone are truly independent.clone() is one of the four basic methods of the Object class that should be overriden by any good-style class to avoid incorect clonning by inherited Object.clone()^^http://www.w3.org/2001/XMLSchema#string + + + + #OverridingEquals + true + + + + #OverridingEquals + The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal‚Äîthat is, if the objects compared are the exact same object.To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method. Here is an example of a Book class that overrides equals():Consider this code that tests two instances of the Book class for equality:This program displays objects are equal even though firstBook and secondBook reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number.You should always override the equals() method if the identity operator is not appropriate for your class.Note:¬†If you override equals(), you must override hashCode() as well.equals() is one of the four basic methods of the Object class that should be overriden by any good-style class to avoid incorect objecte comparison by inherited Object.equals()^^http://www.w3.org/2001/XMLSchema#string + + + + #OverridingHashCode + true + + + + #OverridingHashCode + The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.hashCode() is one of the four basic methods of the Object class that should be overriden by any good-style class to avoid incorect hash code computation by inherited Object.hashCode()^^http://www.w3.org/2001/XMLSchema#string + + + + #OverridingToString + true + + + + #OverridingToString + You should always consider overriding the toString() method in your classes.The Object's toString() method returns a String representation of the object, which is very useful for debugging. The String representation for an object depends entirely on the object, which is why you need to override toString() in your classes.You can use toString() along with System.out.println() to display a text representation of an object, such as an instance of Book:System.out.println(firstBook.toString());which would, for a properly overridden toString() method, print something useful, like this:toString() is one of the four basic methods of the Object class that should be overriden by any good-style class to avoid incorect printing of objects by inherited Object.toString()^^http://www.w3.org/2001/XMLSchema#string + + + + #Package + false + + + + #Package + A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. Java provides the keyword import to indicate that you want to use a package or a class from a package. For example, to use the java.io.File class, you must have the following import statement: 1. 'import' statements must come after the package statement but before the class declaration. 2. The import keyword can appear multiple times in a class. You can import all classes in the same package by using the wild character *. For example, the following code imports all members of the java.io package. However, to make your code more readable, it is recommended that you import a package member one at a time. Members of the java.lang package are imported automatically. Thus, to use the java.lang.String, for example, you do not need to explicitly import the class.The only way to use classes that belong to other packages without importing them is to use the fully qualified names of the classes in your code. For example, the following code declares the java.io.File class using its fully qualified name.If you class import identically-named classes from different packages, you must use the fully qualified names when declaring the classes. For example, the Java core libraries contain the classes java.sql.Date and java.util.Date. In this case, you must write the fully qualified names of java.sql.Date and java.util.Date to use them.To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages.A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.The types that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on. You can put your types in packages too.You should bundle these classes and the interface in a package for several reasons, including the following: ‚Ä¢ You and other programmers can easily determine that these types are related. ‚Ä¢ You and other programmers know where to find types that can provide graphics-related functions. ‚Ä¢ The names of your types won't conflict with the type names in other packages because the package creates a new namespace. ‚Ä¢ You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package. To create a package, you choose a name for the package (naming conventions are discussed in the next section) and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package. If you do not use a package statement, your type ends up in an unnamed package. Generally speaking, an unnamed package is only for small or temporary applications or when you are just beginning the development process. Otherwise, classes and interfaces belong in named packages. Package names are written in all lowercase to avoid conflict with the names of classes or interfaces.Companies use their reversed Internet domain name to begin their package names‚Äîfor example, com.example.orion for a package named orion created by a programmer at example.com.Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.company.region.package).Packages in the Java language itself begin with java. or javax.In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example: + + + + #PackageSpecificationStatement + true + + + + #PackageSpecificationStatement + A package declaration appears within a compilation unit to indicate the package to which the compilation unit belongs.A package declaration in a compilation unit specifies the name (¬ß6.2) of the package to which the compilation unit belongs. ‚Ä¢ PackageDeclaration: ‚Ä¢ package PackageName ; ‚Ä¢ The package name mentioned in a package declaration must be the fully qualified name (¬ß6.7) of the package. + + + + #Parenthesis + true + + + + #Parenthesis + Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence. An implementation may not take advantage of algebraic identities such as the associative law to rewrite expressions into a more convenient computational order unless it can be proven that the replacement expression is equivalent in value and in its observable side effects, even in the presence of multiple threads of execution (using the thread execution model in ¬ß17), for all possible computational values that might be involved.Parenthesis '(' ')' to change the default presedence of operators^^http://www.w3.org/2001/XMLSchema#string + + + + #PolymorphicObjectCreationStatement + true + + + + #Polymorphism + false + + + + #Polymorphism + Polymorphism assumes different behavior of an invoked method depending on the actual type of an object, which is determined at a run time + + + + #PostDecrementExpression + true + + + + #PostDecrementExpression + A postfix expression followed by a -- operator is a postfix decrement expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix decrement expression is the type of the variable. The result of the postfix decrement expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, then the postfix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (¬ß5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (¬ß5.1.3) to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable before the new value is stored.Post-decrement '--' decreases the value of the operand by one after the entire expression has been evaluated^^http://www.w3.org/2001/XMLSchema#string + + + + #PostIncrementExpression + true + + + + #PostIncrementExpression + The unary operators require only one operand; they perform various operations such as incrementing ++ Increment operator; increments a value by 1The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference. A postfix expression followed by a ++ operator is a postfix increment expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (¬ß5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (¬ß5.1.3) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.Post-increment '++' increases the value of the operand by one after the entire expression has been evaluated^^http://www.w3.org/2001/XMLSchema#string + + + + #PreDecrementExpression + true + + + + #PreDecrementExpression + A unary expression preceded by a -- operator is a prefix decrement expression. The result of the unary expression must be a variable of a numeric type, or a compile-time error occurs. The type of the prefix decrement expression is the type of the variable. The result of the prefix decrement expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, then the prefix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (¬ß5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (¬ß5.1.3) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.Pre-decrement '--' decreases the value of the operand by one before the rest of the expression has been evaluated^^http://www.w3.org/2001/XMLSchema#string + + + + #PreIncrementExpression + true + + + + #PreIncrementExpression + The unary operators require only one operand; they perform various operations such as incrementing ++ Increment operator; increments a value by 1The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference. A unary expression preceded by a ++ operator is a prefix increment expression. The result of the unary expression must be a variable of a numeric type, or a compile-time error occurs. The type of the prefix increment expression is the type of the variable. The result of the prefix increment expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (¬ß5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (¬ß5.1.3) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored.Pre-increment '++' increases the value of the operand by one before the rest of the expression has been evaluated^^http://www.w3.org/2001/XMLSchema#string + + + + #PrivateAccessSpecifier + true + + + + #PrivateAccessSpecifier + The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private. Other access modifiers will be discussed later. ‚Ä¢ private modifier‚Äîthe field is accessible only within its own class.In the spirit of encapsulation, it is common to make fields private. This means that they can only be directly accessed from the Bicycle class. We still need access to these values, however. This can be done indirectly by adding public methods that obtain the field values for us: + + + + #ProgramElementBody + false + + + + #ProgramElementDefinition + false + + + + #ProgramElementSignature + false + + + + #ProgramStructure + false + + + + #ProtectedAccessSpecifier + true + + + + #ProtectedAccessSpecifier + A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of CLet C be the class in which a protected constructor is declared and let S be the innermost class in whose declaration the use of the protected constructor occurs. + + + + #PublicAccessSpecifier + true + + + + #PublicAccessSpecifier + The first (left-most) modifier used lets you control what other classes have access to a member field.public modifier‚Äîthe field is accessible from all classes. + + + + #RelationalExpression + false + + + + #RelationalExpression + Relational operators compare the values of their operands + + + + #ReturnStatement + true + + + + #ReturnStatement + The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword. return ++count;The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value.A method returns to the code that invoked it when it ‚Ä¢ completes all the statements in the method, ‚Ä¢ reaches a return statement, or ‚Ä¢ throws an exception (covered later),whichever occurs first.You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: return; If you try to return a value from a method that is declared void, you will get a compiler error.Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.This method returns the integer that the expression width*height evaluates to.The area method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:A return statement returns control to the invoker of a method (¬ß8.4, ¬ß15.12) or constructor (¬ß8.8, ¬ß15.9). ‚Ä¢ ReturnStatement: ‚Ä¢ return Expressionopt ; ‚Ä¢ A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (¬ß8.4), or in the body of a constructor (¬ß8.8). A compile-time error occurs if a return statement appears within an instance initializer or a static initializer (¬ß8.7). A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it.To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value.A return statement with an Expression must be contained in a method declaration that is declared to return a value (¬ß8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable (¬ß5.2) to the declared result type of the method, or a compile-time error occurs.A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V. If the expression is of type float and is not FP-strict (¬ß15.4), then the value may be an element of either the float value set or the float-extended-exponent value set (¬ß4.2.3). If the expression is of type double and is not FP-strict, then the value may be an element of either the double value set or the double-extended-exponent value set.It can be seen, then, that a return statement always completes abruptly.The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (¬ß14.19) within the method or constructor whose try blocks contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.return statement (ends the method execution and returns (optionally) the result of the method)^^http://www.w3.org/2001/XMLSchema#string + + + + #ReturnedType + true + + + + #ReturnedType + A method returns to the code that invoked it when it ‚Ä¢ completes all the statements in the method, ‚Ä¢ reaches a return statement, or ‚Ä¢ throws an exception (covered later),whichever occurs first.You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: return; If you try to return a value from a method that is declared void, you will get a compiler error.Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.This method returns the integer that the expression width*height evaluates to.The area method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this: + + + + #ReturnedValue + false + + + + #ReturnedValue + A method returns to the code that invoked it when it ‚Ä¢ completes all the statements in the method, ‚Ä¢ reaches a return statement, or ‚Ä¢ throws an exception (covered later),whichever occurs first.You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: return; If you try to return a value from a method that is declared void, you will get a compiler error.Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.This method returns the integer that the expression width*height evaluates to.The area method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:the method returned value (the result of the method)^^http://www.w3.org/2001/XMLSchema#string + + + + #SAX + true + + + + #SelectionStatement + false + + + + #SelectionStatement + Java selection (decision, conditional) statements + + + + #ShortDataType + true + + + + #ShortDataType + short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. integer data type for numbers between -32,768 and 32,767 (reserved word "short")^^http://www.w3.org/2001/XMLSchema#string + + + + #ShortValue + true + + + + #SignedLeftShiftAssignmentExpression + true + + + + #SignedLeftShiftExpression + true + + + + #SignedRightShiftAssignmentExpression + true + + + + #SignedRightShiftExpression + true + + + + #SimpleAssignmentExpression + true + + + + #SimpleAssignmentExpression + One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:This operator can also be used on objects to assign object references, as discussed in Creating Objects. Simple (default, traditional) assignment '='^^http://www.w3.org/2001/XMLSchema#string + + + + #SimpleDataType + false + + + + #SimpleDataType + The Java programming language is staticaly-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen: int gear = 1;Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are: Java has eight primitive types of data: byte, short, int, long, char, float, double, and boolean.These can be put in four groups: 1. Integers includes byte, short, int, and long 2. Floating-point numbers includes float and double 3. Characters includes char, like letters and numbers. 4. Boolean includes boolean representing true/false values.Simple (fundamental, basic) data types^^http://www.w3.org/2001/XMLSchema#string + + + + #SimpleDataTypeValue + false + + + + #SimpleVariable + true + + + + #SimpleVariable + Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared ‚Äî which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Variables are data placeholders. There are two data types in Java: Primitive types hold a primitive.A local variable storing a value of a simple data type. Local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.^^http://www.w3.org/2001/XMLSchema#string + + + + #Specification + false + + + + #StandardIdentifier + true + + + + #Statement + false + + + + #Statement + 1. In programming, a statement is an instruction to do something. 2. It controls the sequence of execution of a program. 3. In Java, a statement is terminated with a semicolon and multiple statements can be written on a single line. Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution.Java programming statements (or instructions)^^http://www.w3.org/2001/XMLSchema#string + + + + #StatementBlock + true + + + + #StatementBlock + 1. You can have a block of statements enclosed between braces. 2. If the value of expression is true, all the statements enclosed in the block will be executed. 3. Without the braces, the code no longer has a statement block. A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.A block is a sequence of statements, local class declarations and local variable declaration statements within braces.A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.The scope of a local variable declaration in a block (¬ß14.2) is the rest of the block in which the declaration appears, starting with its own initializer (¬ß14.4) and including any further declarators to the right in the local variable declaration statement.The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. The name of a local variable v may not be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. However, a local variable of a method or initializer block may be shadowed (¬ß6.3.1) anywhere inside a class declaration nested within the scope of the local variable.A local variable cannot be referred to using a qualified name (¬ß6.6), only a simple name.A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.^^http://www.w3.org/2001/XMLSchema#string + + + + #StaticMethod + false + + + + #StaticMethod + 1. Static members are not tied to class instances. 2. Static members can be called without having an instance.The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as inA common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:Not all combinations of instance and class variables and methods are allowed: + + + + #StaticMethodDefinition + true + + + + #StaticMethodDefinition + 1. You can use the keyword static in front of a method declaration. 2. The static keyword may come before or after the access modifier. # From inside a static method, you cannot call instance methods or instance fields because they only exist after you create an object.# You can access other static methods or fields from a static method.The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as inA common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:Not all combinations of instance and class variables and methods are allowed: + + + + #StaticMethodInvocation + true + + + + #StaticMethodInvocation + If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified.The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in + + + + #StaticModifier + true + + + + #StaticModifier + 1. Static members are not tied to class instances. 2. Static members can be called without having an instance. 1. You can use the keyword static in front of a method declaration. 2. The static keyword may come before or after the access modifier. # From inside a static method, you cannot call instance methods or instance fields because they only exist after you create an object.# You can access other static methods or fields from a static method.In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles, as follows:Class variables are referenced by the class name itself, as inThis makes it clear that they are class variables.The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as inA common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:Not all combinations of instance and class variables and methods are allowed:The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):static final double PI = 3.141592653589793;Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).Note:¬†If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value. + + + + #StringAddition + true + + + + #StringAddition + The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program: class ConcatDemo { public static void main(String[] args){ String firstString = "This is"; String secondString = " a concatenated string."; String thirdString = firstString+secondString; System.out.println(thirdString); } }By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output. 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.Strings are more commonly concatenated with the +(addition) operator, as in"Hello," + " world" + "!"which results in"Hello, world!"The + operator is widely used in print statements. For example:Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.The Java programming language does not permit literal strings to span lines in source files, so you must use the + concatenation operator at the end of each line in a multi-line string. For example,Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a newly created String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.Any type may be converted to type String by string conversion.A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.Arithmetic addition of strings results in string concatenation. If only one of the arguments is string, it will be concatenated with the string representation of the second argument^^http://www.w3.org/2001/XMLSchema#string + + + + #StringDataType + true + + + + #StringDataType + In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Simple Data ObjectsStrings, 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.The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.The most direct way to create a string is to write:String greeting = "Hello world!";In this case, "Hello world!" is a string literal‚Äîa series of characters in your code that is enclosed in double quotes. 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 thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters: + + + + #StringInitializationStatement + true + + + + #StringInitializationStatement + The most direct way to create a string is to write:String greeting = "Hello world!";In this case, "Hello world!" is a string literal‚Äîa series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value‚Äîin this case, Hello world!Initialization of a String object by a string literal +String Initialization is a kind of variable initialialization^^http://www.w3.org/2001/XMLSchema#string + + + + #StringLiteral + true + + + + #StringLiteral + A string literal consists of zero or more characters enclosed in double quotes. Each character may be represented by an escape sequence.A string literal is always of type String (¬ß4.3.3. A string literal always refers to the same instance (¬ß4.3.1) of class String. + + + + #StringLiteralMethodInvocation + true + + + + #StringVariable + true + + + + #StringVariable + a variable of class String, storing a reference to the String representation in memory + + + + #Subclass + false + + + + #Subclass + Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:A diagram of classes in a hierarchy.A hierarchy of bicycle classes.The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here}This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, with four fields and five methods. However, you didn't have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members: ‚Ä¢ The inherited fields can be used directly, just like any other fields. ‚Ä¢ You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). ‚Ä¢ You can declare new fields in the subclass that are not in the superclass. ‚Ä¢ The inherited methods can be used directly as they are. ‚Ä¢ You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. ‚Ä¢ You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. ‚Ä¢ You can declare new methods in the subclass that are not in the superclass. ‚Ä¢ You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.The following sections in this lesson will expand on these topics. + + + + #SubtractAssignmentExpression + true + + + + #SubtractAssignmentExpression + All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required: ‚Ä¢ First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. ‚Ä¢ Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see ¬ß15.17.2), then the assignment expression completes abruptly for the same reason and no assignment occurs. ‚Ä¢ Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (¬ß5.1.8) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.Subtract the value of the expression to the right from the value of the varibale to the left and assigns the result to the variable to the left '=-"^^http://www.w3.org/2001/XMLSchema#string + + + + #SubtractExpression + true + + + + #SubtractExpression + The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. - subtraction operatorSubtraction Operator '-'^^http://www.w3.org/2001/XMLSchema#string + + + + #SuperReference + true + + + + #SuperReference + If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:Here is a subclass, called Subclass, that overrides printMethod():Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following: + + + + #Superclass + false + + + + #Superclass + Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:A diagram of classes in a hierarchy.A hierarchy of bicycle classes.The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here}This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass. + + + + #SuperclassConstructor + false + + + + #SuperclassConstructor + 1. You can explicitly call the parent's constructor from a subclass's constructor by using the super keyword. 2. 'super' must be the first statement in the constructor.^^http://www.w3.org/2001/XMLSchema#string + + + + #SuperclassConstructorCall + true + + + + #SuperclassConstructorCall + 1. You can explicitly call the parent's constructor from a subclass's constructor by using the super keyword. 2. 'super' must be the first statement in the constructor.The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example that MountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own:nvocation of a superclass constructor must be the first line in the subclass constructor.The syntax for calling a superclass constructor issuper(); --or--super(parameter list);With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.Note:¬†If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.Constructors of the subclasses must call the super constructor first to initialize inherited fields and then initialize new added fields of the subclass. To call the super constructor one shoudl use "super()"^^http://www.w3.org/2001/XMLSchema#string + + + + #SuperclassMethod + false + + + + #SuperclassMethod + to call methods of the superclass, if they are not overriden, one call them the way, the are implemented in the subclass, If a method has been overriden, then inside the sublcass one should use super refference. + + + + #SuperclassMethodCall + true + + + + #SuperclassMethodCall + The special forms using the keyword super are valid only in an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class; these are exactly the same situations in which the keyword this may be used (¬ß15.8.3). The forms involving super may not be used anywhere in the class Object, since Object has no superclass; if super appears in class Object, then a compile-time error results.Suppose that a field access expression super.name appears within class C, and the immediate superclass of C is class S. Then super.name is treated exactly as if it had been the expression ((S)this).name; thus, it refers to the field named name of the current object, but with the current object viewed as an instance of the superclass. Thus it can access the field named name that is visible in class S, even if that field is hidden by a declaration of a field named name in class C. + + + + #SuperclassSubclassConversion + true + + + + #SuperclassSubclassConversion + 1. With objects, you can cast an instance of a subclass to its parent class. 2. Casting an object to a parent class is called upcasting. To upcast a Child object, all you need to do is assign the object to a reference variable of type Parent. The parent reference variable cannot access the members that are only available in Child.Because parent references an object of type Child, you can cast it back to Child. It is called downcasting because you are casting an object to a class down the inheritance hierarchy. Downcasting requires that you write the child type in brackets. For example:We have seen that an object is of the data type of the class from which it was instantiated. For example, if we writepublic MountainBike myBike = new MountainBike();then myBike is of type MountainBike.MountainBike is descended from Bicycle and Object. Therefore, a MountainBike is a Bicycle and is also an Object, and it can be used wherever Bicycle or Object objects are called for.The reverse is not necessarily true: a Bicycle may be a MountainBike, but it isn't necessarily. Similarly, an Object may be a Bicycle or a MountainBike, but it isn't necessarily.Casting shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations. For example, if we writeObject obj = new MountainBike();then obj is both an Object and a Mountainbike (until such time as obj is assigned another object that is not a Mountainbike). This is called implicit casting.If, on the other hand, we writeMountainBike myBike = obj;we would get a compile-time error because obj is not known to the compiler to be a MountainBike. However, we can tell the compiler that we promise to assign a MountainBike to obj by explicit casting:MountainBike myBike = (MountainBike)obj;This cast inserts a runtime check that obj is assigned a MountainBike so that the compiler can safely assume that obj is a MountainBike. If obj is not a Mountainbike at runtime, an exception will be thrown.Note:¬†You can make a logical test as to the type of a particular object using the instanceof operator. This can save you from a runtime error owing to an improper cast. For example:if (obj instanceof MountainBike) { MountainBike myBike = (MountainBike)obj;}Here the instanceof operator verifies that obj refers to a MountainBike so that we can make the cast with knowledge that there will be no runtime exception thrown. + + + + #SwitchStatement + true + + + + #SwitchStatement + 1. An alternative to a series of else if is the switch statement. 2. The switch statement allows you to choose a block of statements to run from a selection of code, based on the return value of an expression. 3. The expression used in the switch statement must return an int or an enumerated value.The syntax of the switch statement is as follows.Failure to add a break statement after a case will not generate a compile error but may have more serious consequences because the statements on the next case will be executed.Here is an example of the switch statement:Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).The following program, SwitchDemo, declares an int named month whose value represents a month out of the year. The program displays the name of the month, based on the value of month, using the switch statement.The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case.The switch statement transfers control to one of several statements depending on the value of an expression.The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. These labels are said to be associated with the switch statement, as are the values of the constant expressions (¬ß15.28) in the case labels.All of the following must be true, or a compile-time error will result: ‚Ä¢ Every case constant expression associated with a switch statement must be assignable (¬ß5.2) to the type of the switch Expression. ‚Ä¢ No two of the case constant expressions associated with a switch statement may have the same value. ‚Ä¢ At most one default label may be associated with the same switch statement.switch statement (selector, multiple selection statement)^^http://www.w3.org/2001/XMLSchema#string + + + + #ThisReference + true + + + + #ThisReference + You use the this keyword from any method or constructor to refer to the current object.Within an instance method or a constructor, this is a reference to the current object ‚Äî the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.Each argument to the constructor shadows one of the object's fields ‚Äî inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.If present, the invocation of another constructor must be the first line in the constructor.The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.When used as a primary expression, the keyword this denotes a value, that is a reference to the object for which the instance method was invoked (¬ß15.12), or to the object being constructed.The keyword this is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body + + + + #ThrowStatement + true + + + + #ThrowStatement + A throw statement causes an exception (¬ß11) to be thrown. The result is an immediate transfer of control (¬ß11.3) that may exit multiple statements and multiple constructor, instance initializer, static initializer and field initializer evaluations, and method invocations until a try statement (¬ß14.19) is found that catches the thrown value. If no such try statement is found, then execution of the thread (¬ß17) that executed the throw is terminated (¬ß11.3) after invocation of the uncaughtException method for the thread group to which the thread belongs. ‚Ä¢ ThrowStatement: ‚Ä¢ throw Expression ; ‚Ä¢ The Expression in a throw statement must denote a variable or value of a reference type which is assignable (¬ß5.2) to the type Throwable, or a compile-time error occurs. Moreover, at least one of the following three conditions must be true, or a compile-time error occurs: ‚Ä¢ The exception is not a checked exception (¬ß11.2)-specifically, one of the following situations is true: ‚ó¶ The type of the Expression is the class RuntimeException or a subclass of RuntimeException. ‚ó¶ The type of the Expression is the class Error or a subclass of Error. ‚Ä¢ The throw statement is contained in the try block of a try statement (¬ß14.19) and the type of the Expression is assignable (¬ß5.2) to the type of the parameter of at least one catch clause of the try statement. (In this case we say the thrown value is caught by the try statement.) ‚Ä¢ The throw statement is contained in a method or constructor declaration and the type of the Expression is assignable (¬ß5.2) to at least one type listed in the throws clause (¬ß8.4.4, ¬ß8.8.4) of the declaration.A throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a non-null value V, then the throw statement completes abruptly, the reason being a throw with value V. If evaluation of the Expression completes normally, producing a null value, then an instance V' of class NullPointerException is created and thrown instead of null. The throw statement then completes abruptly, the reason being a throw with value V'.It can be seen, then, that a throw statement always completes abruptly.If there are any enclosing try statements (¬ß14.19) whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.If a throw statement is contained in a method declaration, but its value is not caught by some try statement that contains it, then the invocation of the method completes abruptly because of the throw.If a throw statement is contained in a constructor declaration, but its value is not caught by some try statement that contains it, then the class instance creation expression that invoked the constructor will complete abruptly because of the throw.If a throw statement is contained in a static initializer (¬ß8.7), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it. If at run-time, despite this check, the value is not caught by some try statement that contains the throw statement, then the value is rethrown if it is an instance of class Error or one of its subclasses; otherwise, it is wrapped in an ExceptionInInitializerError object, which is then thrown (¬ß12.4.2).If a throw statement is contained in an instance initializer (¬ß8.6), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it, or the type of the thrown exception (or one of its superclasses) occurs in the throws clause of every constructor of the class.By convention, user-declared throwable types should usually be declared to be subclasses of class Exception, which is a subclass of class Throwable (¬ß11.5).All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.throw someThrowableObject;Let's look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes. For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur. + + + + #ThrowsSpecification + true + + + + #ThrowsSpecification + A throws clause is used to declare any checked exceptions (¬ß11.2) that can result from the execution of a method or constructor:A compile-time error occurs if any ClassType mentioned in a throws clause is not the class Throwable or a subclass of Throwable. It is permitted but not required to mention other (unchecked) exceptions in a throws clause.For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a superclass of that exception type is mentioned in a throws clause in the declaration of the method or constructor.The requirement to declare checked exceptions allows the compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions will normally result in a compile-time error because of the lack of a proper exception type in a throws clause. The Java programming language thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.The previous section showed how to write an exception handler for the writeList method in the ListOfNumbers class. Sometimes, it's appropriate for code to catch exceptions that can occur within it. In other cases, however, it's better to let a method further up the call stack handle the exception. For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it.If the writeList method doesn't catch the checked exceptions that can occur within it, the writeList method must specify that it can throw these exceptions. Let's modify the original writeList method to specify the exceptions it can throw instead of catching them. To remind you, here's the original version of the writeList method that won't compile.To specify that writeList can throw two exceptions, add a throws clause to the method declaration for the writeList method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method; here's an example.Remember that ArrayIndexOutOfBoundsException is an unchecked exception; including it in the throws clause is not mandatory. You could just write the following. + + + + #True + true + + + + #True + The boolean type has two values, represented by literals 'true' and ...The following code declares a boolean variable includeSign and assigns it the value of true.The boolean type has two values, represented by the literals true and false, formed from ASCII letters.A boolean literal is always of type boolean.logical true values (reserved word "true")^^http://www.w3.org/2001/XMLSchema#string + + + + #TryCatchFinallyStatement + true + + + + #TryCatchFinallyStatement + If the try statement has a finally clause, then another block of code is executed, no matter whether the try block completes normally or abruptly, and no matter whether a catch clause is first given control.TryStatement: try Block Catches try Block Catchesopt FinallyCatches: CatchClause Catches CatchClauseCatchClause: catch ( FormalParameter ) BlockFinally: finally Block A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.Handling of the finally block is rather complex, so the two cases of a try statement with and without a finally block are described separately. + + + + #TryCatchStatement + true + + + + #TryCatchStatement + A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause.TryStatement: try Block Catches try Block Catchesopt FinallyCatches: CatchClause Catches CatchClauseCatchClause: catch ( FormalParameter ) Block The Block immediately after the keyword try is called the try block of the try statement. The Block immediately after the keyword finally is called the finally block of the try statement.A try statement may have catch clauses (also called exception handlers). A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass of Throwable, or a compile-time error occurs. The scope of the parameter variable is the Block of the catch clause.An exception parameter of a catch clause must not have the same name as a local variable or parameter of the method or initializer block immediately enclosing the catch clause, or a compile-time error occurs.The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (¬ß14.19) is the entire block associated with the catch.Within the Block of the catch clause, the name of the parameter may not be redeclared as a local variable of the directly enclosing method or initializer block, nor may it be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method or initializer block, or a compile-time error occurs. However, an exception parameter may be shadowed (¬ß6.3.1) anywhere inside a class declaration nested within the Block of the catch clause.It is a compile-time error if an exception parameter that is declared final is assigned to within the body of the catch clause.Exception parameters cannot be referred to using qualified names (¬ß6.6), only by simple names.Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its actual argument the thrown exception object. + + + + #TypeCasting + false + + + + #TypeCasting + Typecasting, datatype withing brackets '(datatype)' +Necessary for casting with potential information loss (e.g. double to int or long to int or double to float), for casting from the interface to the class implementing it, and for casting from the superclass to the subclass + + + + #UnaryMinusOperator + true + + + + #UnaryMinusOperator + The type of the operand expression of the unary - operator must be a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (¬ß5.6.1) is performed on the operand. The type of the unary minus expression is the promoted type of the operand.At run time, the value of the unary minus expression is the arithmetic negation of the promoted value of the operand.For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0. Unary minus merely inverts the sign of a floating-point number.Unary minus,'-' to change the sign of the expression result^^http://www.w3.org/2001/XMLSchema#string + + + + #UnsignedRightShiftAssignmentExpression + true + + + + #UnsignedRightShiftExpression + true + + + + #Value + false + + + + #Variable + false + + + + #Variable + General concept of a variable in Java +Variables have DataTypes +Variable serve as operands in Expressions + + + + #VariableDeclarationStatement + true + + + + #VariableDeclarationStatement + A local variable declaration statement declares one or more local variable names.A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable. If a declarator does not have an initialization expression, then a Java compiler must prove, using exactly the algorithm given in ¬ß16, that every reference to the variable is necessarily preceded by execution of an assignment to the variable. If this is not the case, then a compile-time error occurs.Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.A local variable declaration can also appear in the header of a for statement (¬ß14.13). In this case it is executed in the same manner as if it were part of a local variable declaration statement.Each declarator in a local variable declaration declares one local variable, whose name is the Identifier that appears in the declarator.If the optional keyword final appears at the start of the declarator, the variable being declared is a final variable(¬ß4.5.4).The type of the variable is denoted by the Type that appears in the local variable declaration, followed by any bracket pairs that follow the Identifier in the declarator.Thus, the local variable declaration: is equivalent to the series of declarations:A local variable of type float always contains a value that is an element of the float value set (¬ß4.2.3); similarly, a local variable of type double always contains a value that is an element of the double value set. It is not permitted for a local variable of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a local variable of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.Declaration statement consists of the variable declaration and a semicolon^^http://www.w3.org/2001/XMLSchema#string + + + + #VariableInitializationStatement + true + + + + #VariableInitializationStatement + Initialization statement consists of the variable initialization and a semicolon.Both simple variables and object variables. + + + + #VariableName + true + + + + #VariableName + Variable names are case-sensitive. A variable's name can be any legal identifier ‚Äî an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted. Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word. All variables, whether they are fields, local variables, or parameters, follow the same naming rules and conventions that were covered in the Language Basics lesson, Variables‚ÄîNaming .In this lesson, be aware that the same naming rules and conventions are used for method and class names, except that ‚Ä¢ the first letter of a class name should be capitalized, and ‚Ä¢ the first (or only) word in a method name should be a verb. + + + + #VoidDataType + true + + + + #WhileStatement + true + + + + #WhileStatement + 1. One way to create a loop is by using the while statement. 2. Another way is to use the for statementThe while statement has the following syntax. 1. statement(s) will be executed as long as booleanExpression evaluates to true. 2. If there is only a single statement inside the braces, you may omit the braces. 3. For clarity, you should always use braces even when there is only one statement.As an example of the while statement, the following code prints integer numbers that are less than three.The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:while (expression) { statement(s)}The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false. ‚Ä¢ WhileStatement: ‚Ä¢ while ( Expression ) Statement ‚Ä¢ ‚Ä¢ WhileStatementNoShortIf: ‚Ä¢ while ( Expression ) StatementNoShortIf ‚Ä¢ The Expression must have type boolean, or a compile-time error occurs.A while statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the while statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value: ‚Ä¢ If the value is true, then the contained Statement is executed. Then there is a choice: ‚ó¶ If execution of the Statement completes normally, then the entire while statement is executed again, beginning by re-evaluating the Expression. ‚ó¶ If execution of the Statement completes abruptly, see ¬ß14.11.1 below. ‚Ä¢ If the value of the Expression is false, no further action is taken and the while statement completes normally.If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.while loop (precondition)^^http://www.w3.org/2001/XMLSchema#string + + + + #WrapperClass + false + + + + #XPath + true + + + + #XSLT + true + + + + #indexing + This property specifies whether the class can be used for content indexing + + + + #java.lang + true + + + + #java.lang + Provides classes that are fundamental to the design of the Java programming language. The most important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time.Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose. An object of type Double, for example, contains a field whose type is double, representing that value in such a way that a reference to it can be stored in a variable of reference type. These classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode. The Void class is a non-instantiable class that holds a reference to a Class object represening the primitive type void.The class Math provides commonly used mathematical functions such as sine, cosine, and square root. The classes String and StringBuffer similarly provide commonly used operations on character strings.Classes ClassLoader, Process, Runtime, SecurityManager, and System provide "system operations" that manage the dynamic loading of classes, creation of external processes, host environment inquiries such as the time of day, and enforcement of security policies.Class Throwable encompasses objects that may be thrown by the throw statement (¬ß14.16). Subclasses of Throwable represent errors and exceptions.java.lang package^^http://www.w3.org/2001/XMLSchema#string + + + + #java.lang.Boolean + true + + + + #java.lang.Boolean + The java.lang.Boolean class wraps a boolean. You can construct a Boolean object from a boolean or a String, using one of these constructors.public Boolean (boolean value) public Boolean (String value)For example:Boolean b1 = new Boolean (false); Boolean b2 = new Boolean ("true");To convert a Boolean to a boolean, use its booleanValue method: public boolean booleanValue() + + + + #java.lang.Byte + true + + + + #java.lang.Byte + The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.In addition, this class provides several methods for converting a byte to a String and a String to a byte, as well as other constants and methods useful when dealing with a byte. + + + + #java.lang.Character + true + + + + #java.lang.Character + The Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char.In addition, this class provides several methods for determining a character's category (lowercase letter, digit, etc.) and for converting characters from uppercase to lowercase and vice versa.Character information is based on the Unicode Standard, version 4.0.The methods and data of class Character are defined by the information in the UnicodeData file that is part of the Unicode Character Database maintained by the Unicode Consortium. This file specifies various properties including name and general category for every defined Unicode code point or character range. + + + + #java.lang.Class + true + + + + #java.lang.Class + nstances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader. + + + + #java.lang.Class.forName + true + + + + #java.lang.Class.forName + Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to: Class.forName(className, true, currentLoader) where currentLoader denotes the defining class loader of the current class.For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread: Class¬†t¬†= Class.forName("java.lang.Thread") A call to forName("X") causes the class named X to be initialized.Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName) this method attempts to locate, load, and link the class or interface. The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.If name denotes a primitive type or void, an attempt will be made to locate a user-defined class in the unnamed package whose name is name. Therefore, this method cannot be used to obtain any of the Class objects representing primitive types or void.If name denotes an array class, the component type of the array class is loaded but not initialized.For example, in an instance method the expression: Class.forName("Foo") is equivalent to: Class.forName("Foo", true, this.getClass().getClassLoader()) Note that this method throws errors related to loading, linking or initializing as specified in Sections 12.2, 12.3 and 12.4 of The Java Language Specification. Note that this method does not check whether the requested class is accessible to its caller.If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader.^^http://www.w3.org/2001/XMLSchema#string + + + + #java.lang.Double + true + + + + #java.lang.Double + The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double. + + + + #java.lang.Double.parseDouble + true + + + + #java.lang.Double.parseDouble + Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double. + + + + #java.lang.Exception + true + + + + #java.lang.Exception + The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.When a program violates the semantic constraints of the Java programming language, the Java virtual machine signals this error to the program as an exception. An example of such a violation is an attempt to index outside the bounds of an array. Some programming languages and their implementations react to such errors by peremptorily terminating the program; other programming languages allow an implementation to react in an arbitrary or unpredictable way. Neither of these approaches is compatible with the design goals of the Java platform: to provide portability and robustness. Instead, the Java programming language specifies that an exception will be thrown when semantic constraints are violated and will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer. An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.The Java programming language uses exceptions to handle errors and other exceptional events. This lesson describes when and how to use exceptions.When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates. + + + + #java.lang.Float + true + + + + #java.lang.Float + The Float class wraps a value of primitive type float in an object. An object of type Float contains a single field whose type is float.In addition, this class provides several methods for converting a float to a String and a String to a float, as well as other constants and methods useful when dealing with a float. + + + + #java.lang.Integer + true + + + + #java.lang.Integer + The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int. + + + + #java.lang.Integer.parseInt + true + + + + #java.lang.Integer.parseInt + Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned.An exception of type NumberFormatException is thrown if any of the following situations occurs: ‚Ä¢ The first argument is null or is a string of length zero. ‚Ä¢ The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX. ‚Ä¢ Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1. ‚Ä¢ The value represented by the string is not a value of type int. + + + + #java.lang.Long + true + + + + #java.lang.Long + The Long class wraps a value of the primitive type long in an object. An object of type Long contains a single field whose type is long.In addition, this class provides several methods for converting a long to a String and a String to a long, as well as other constants and methods useful when dealing with a long. + + + + #java.lang.Math + true + + + + #java.lang.Math + The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.Unlike some of the numeric methods of class StrictMath, all implementations of the equivalent functions of class Math are not defined to return the bit-for-bit same results. This relaxation permits better-performing implementations where strict reproducibility is not required.By default many of the Math methods simply call the equivalent method in StrictMath for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math. + + + + #java.lang.Math.abs + true + + + + #java.lang.Math.ceil + true + + + + #java.lang.Math.ceil + Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases: ‚Ä¢ If the argument value is already equal to a mathematical integer, then the result is the same as the argument. ‚Ä¢ If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. ‚Ä¢ If the argument value is less than zero but greater than -1.0, then the result is negative zero.Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x). + + + + #java.lang.Math.cos + true + + + + #java.lang.Math.cos + Returns the trigonometric cosine of an angle. Special cases: ‚Ä¢ If the argument is NaN or an infinity, then the result is NaN.The computed result must be within 1 ulp of the exact result. Results must be semi-monotonic. + + + + #java.lang.Math.exp + true + + + + #java.lang.Math.exp + Returns Euler's number e raised to the power of a double value. Special cases: ‚Ä¢ If the argument is NaN, the result is NaN. ‚Ä¢ If the argument is positive infinity, then the result is positive infinity. ‚Ä¢ If the argument is negative infinity, then the result is positive zero.The computed result must be within 1 ulp of the exact result. Results must be semi-monotonic. + + + + #java.lang.Math.floor + true + + + + #java.lang.Math.floor + Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. Special cases: ‚Ä¢ If the argument value is already equal to a mathematical integer, then the result is the same as the argument. ‚Ä¢ If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. + + + + #java.lang.Math.log + true + + + + #java.lang.Math.max + true + + + + #java.lang.Math.min + true + + + + #java.lang.Math.min + Returns the smaller of two double values. That is, the result is the value closer to negative infinity. If the arguments have the same value, the result is that same value. If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. If one argument is positive zero and the other is negative zero, the result is negative zero. + + + + #java.lang.Math.pow + true + + + + #java.lang.Math.pow + Returns the value of the first argument raised to the power of the second argument. + + + + #java.lang.Math.round + true + + + + #java.lang.Math.round + Returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. In other words, the result is equal to the value of the expression: + + + + #java.lang.Math.sin + true + + + + #java.lang.Math.sqrt + true + + + + #java.lang.Math.tan + true + + + + #java.lang.Object + true + + + + #java.lang.Object + The Object class, defined in the java.lang package, defines and implements behavior common to all classes‚Äîincluding the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of the hierarchy provide more specialized behavior. + + + + #java.lang.Object.clone + true + + + + #java.lang.Object.clone + If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method to create a copy from an existing object. To create a clone, you write:aCloneableObject.clone();Object's implementation of this method checks to see whether the object on which clone() was invoked implements the Cloneable interface. If the object does not, the method throws a CloneNotSupportedException exception. Exception handling will be covered in a later lesson. For the moment, you need to know that clone() must be declared asprotected Object clone() throws CloneNotSupportedException -- or --public Object clone() throws CloneNotSupportedExceptionif you are going to write a clone() method to override the one in Object.If the object on which clone() was invoked does implement the Cloneable interface, Object's implementation of the clone() method creates an object of the same class as the original object and initializes the new object's member variables to have the same values as the original object's corresponding member variables.The simplest way to make your class cloneable is to add implements Cloneable to your class's declaration. then your objects can invoke the clone() method.For some classes, the default behavior of Object's clone() method works just fine. If, however, an object contains a reference to an external object, say ObjExternal, you may need to override clone() to get correct behavior. Otherwise, a change in ObjExternal made by one object will be visible in its clone also. This means that the original object and its clone are not independent‚Äîto decouple them, you must override clone() so that it clones the object and ObjExternal. Then the original object references ObjExternal and the clone references a clone of ObjExternal, so that the object and its clone are truly independent. + + + + #java.lang.Object.equals + true + + + + #java.lang.Object.equals + The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal‚Äîthat is, if the objects compared are the exact same object.To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method. Here is an example of a Book class that overrides equals():Consider this code that tests two instances of the Book class for equality:This program displays objects are equal even though firstBook and secondBook reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number.You should always override the equals() method if the identity operator is not appropriate for your class.Note:¬†If you override equals(), you must override hashCode() as well. + + + + #java.lang.Object.hashCode + true + + + + #java.lang.Object.hashCode + The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well. + + + + #java.lang.Object.toString + true + + + + #java.lang.Object.toString + You should always consider overriding the toString() method in your classes.The Object's toString() method returns a String representation of the object, which is very useful for debugging. The String representation for an object depends entirely on the object, which is why you need to override toString() in your classes.You can use toString() along with System.out.println() to display a text representation of an object, such as an instance of Book:System.out.println(firstBook.toString());which would, for a properly overridden toString() method, print something useful, like this: + + + + #java.lang.Short + true + + + + #java.lang.Short + The Short class wraps a value of primitive type short in an object. An object of type Short contains a single field whose type is short.In addition, this class provides several methods for converting a short to a String and a String to a short, as well as other constants and methods useful when dealing with a short. + + + + #java.lang.String + true + + + + #java.lang.String + The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.The Java language provides special support for the string concatenation operator (¬†+¬†), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values). + + + + #java.lang.String.charAt + true + + + + #java.lang.String.charAt + Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. + + + + #java.lang.String.compareTo + true + + + + #java.lang.String.compareTo + Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true. + + + + #java.lang.String.compareToIgnoreCase + true + + + + #java.lang.String.compareToIgnoreCase + Compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character.Note that this method does not take locale into account, and will result in an unsatisfactory ordering for certain locales. The java.text package provides collators to allow locale-sensitive ordering. + + + + #java.lang.String.concat + true + + + + #java.lang.String.concat + Concatenates the specified string to the end of this string.If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. + + + + #java.lang.String.equals + true + + + + #java.lang.String.equals + Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. + + + + #java.lang.String.equalsIgnoreCase + true + + + + #java.lang.String.equalsIgnoreCase + Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.Two characters c1 and c2 are considered the same ignoring case if at least one of the following is true: ‚Ä¢ The two characters are the same (as compared by the == operator) ‚Ä¢ Applying the method Character.toUpperCase(char) to each character produces the same result ‚Ä¢ Applying the method Character.toLowerCase(char) to each character produces the same result + + + + #java.lang.String.indexOf + true + + + + #java.lang.String.indexOf + Returns the index within this string of the first occurrence of the specified character. If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned. + + + + #java.lang.String.length + true + + + + #java.lang.String.length + One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.public int length()Returns the length of this string. The length is equal to the number of Unicode code units in the string. + + + + #java.lang.String.replace + true + + + + #java.lang.String.replace + Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar. + + + + #java.lang.String.substring + true + + + + #java.lang.String.substring + Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. + + + + #java.lang.String.toLowerCase + true + + + + #java.lang.String.toLowerCase + Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. + + + + #java.lang.String.toUpperCase + true + + + + #java.lang.String.toUpperCase + Returns a copy of the string, with leading and trailing whitespace omitted.If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k,¬†m+1).This method may be used to trim whitespace (as defined above) from the beginning and end of a string. + + + + #java.lang.System + true + + + + #java.lang.System + The System class contains several useful class fields and methods. It cannot be instantiated.Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array. + + + + #java.lang.System.err + true + + + + #java.lang.System.err + The "standard" error output stream. This stream is already open and ready to accept output data.Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored. + + + + #java.lang.System.in + true + + + + #java.lang.System.in + The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user. + + + + #java.lang.System.out + true + + + + #java.lang.System.out + The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. + + + + #java.lang.System.out.print + true + + + + #java.lang.System.out.print + Prints its argument to the standard output stream. + + + + #java.lang.System.out.println + true + + + + #java.lang.System.out.println + Prints its argument to the standard output stream and then terminates the line. + + + + #java.lang.Thread + true + + + + #java.lang.Thread + A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs: ‚Ä¢ The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. ‚Ä¢ All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method. + + + + #java.lang.Throwable + true + + + + #java.lang.Throwable + The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Finally, it can contain a cause: another throwable that caused this throwable to get thrown. The cause facility is new in release 1.4. It is also known as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another. + + + + #java.lang.Void + true + + + + #java.lang.Void + The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void. + + + + #java.util + true + + + + #java.util + Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array). + + + + #java.util.ArrayList + true + + + + #java.util.ArrayList + Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. + + + + #java.util.ArrayList.add + true + + + + #java.util.ArrayList.add + Appends the specified element to the end of this list.Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). + + + + #java.util.ArrayList.get + true + + + + #java.util.ArrayList.get + Returns the element at the specified position in this list. + + + + #java.util.ArrayList.indexOf + true + + + + #java.util.ArrayList.indexOf + Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null¬†?¬†get(i)==null¬†:¬†o.equals(get(i))), or -1 if there is no such index. + + + + #java.util.ArrayList.remove + true + + + + #java.util.ArrayList.remove + Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null¬†?¬†get(i)==null¬†:¬†o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call). + + + + #java.util.ArrayList.set + true + + + + #java.util.ArrayList.set + Replaces the element at the specified position in this list with the specified element. + + + + #java.util.ArrayList.size + true + + + + #java.util.ArrayList.size + Returns the number of elements in this list. + + + + #java.util.List + true + + + + #java.util.List + An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list. + + + + #java.util.Random + true + + + + #java.util.Random + An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 3, Section 3.2.1.)If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits. + + + + #java.util.Random.nextDouble + true + + + + #java.util.Random.nextDouble + Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.The general contract of nextDouble is that one double value, chosen (approximately) uniformly from the range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated and returned.The method nextDouble is implemented by class Random as if by:The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose double values from the stated range with perfect uniformity. + + + + #java.util.Random.nextInt + true + + + + #java.util.Random.nextInt + Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability. The method nextInt(int n) is implemented by class Random as if by:The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose int values from the stated range with perfect uniformity. + + + + #java.util.Scanner + true + + + + #java.util.Scanner + A simple text scanner which can parse primitive types and strings using regular expressions.A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace. The reset() method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed.A scanning operation may block waiting for input.The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.The findInLine(java.lang.String), findWithinHorizon(java.lang.String, int), and skip(java.util.regex.Pattern) methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\\s" could return empty tokens since it only passes one space at a time.A scanner can read text from any object which implements the Readable interface. If an invocation of the underlying readable's Readable.read(java.nio.CharBuffer) method throws an IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the ioException() method.When a Scanner is closed, it will close its input source if the source implements the Closeable interface.A Scanner is not safe for multithreaded use without external synchronization.Unless otherwise mentioned, passing a null parameter into any method of a Scanner will cause a NullPointerException to be thrown.A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the useRadix(int) method. The reset() method will reset the value of the scanner's radix to 10 regardless of whether it was previously changed. + + + + #java.util.Scanner.next + true + + + + #java.util.Scanner.next + Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.Returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.Returns the next token if it matches the pattern constructed from the specified string. If the match is successful, the scanner advances past the input that matched the pattern.An invocation of this method of the form next(pattern) behaves in exactly the same way as the invocation next(Pattern.compile(pattern)). + + + + #java.util.Scanner.nextDouble + true + + + + #java.util.Scanner.nextInt + true + + + + #java.util.Scanner.nextInt + Scans the next token of the input as an int.An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.If the next token matches the Integer regular expression defined above then the token is converted into an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Integer.parseInt with the specified radix. + + + + #java.util.Scanner.nextLine + true + + + + #java.util.Scanner.nextLine + Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present. + + + + #null + true + + + + #null + You can test if a reference variable is null by using the == operator. For instance. + + + \ No newline at end of file diff --git a/static/um2_python_concept_ids.json b/static/um2_python_concept_ids.json new file mode 100644 index 0000000..9011054 --- /dev/null +++ b/static/um2_python_concept_ids.json @@ -0,0 +1,67 @@ +{ + "3046": "Pow", + "3045": "Not", + "3044": "FloorDiv", + "3043": "Continue", + "3042": "While", + "3041": "USub", + "3040": "Tuple", + "3039": "TryExcept", + "3038": "Try", + "3037": "TRUE", + "3036": "Sub", + "3035": "Str", + "3034": "Slice", + "3033": "Return", + "3032": "Raise", + "3031": "Or", + "3030": "NotEq", + "3028": "Mult", + "3027": "Mod", + "3026": "LtE", + "3025": "Lt", + "3024": "List", + "3023": "Int", + "3022": "Index", + "3021": "In", + "3020": "ImportFrom", + "3019": "If", + "3018": "GtE", + "3017": "Gt", + "3016": "FunctionDef", + "3015": "For", + "3014": "Float", + "3013": "FALSE", + "3012": "ExceptHandler", + "3011": "Eq", + "3010": "Div", + "3009": "Dict", + "3008": "ClassDef", + "3007": "Call", + "3006": "AugAssign", + "3005": "Attribute", + "3004": "Assign", + "3003": "arg", + "3002": "And", + "3001": "alias", + "3000": "Add", + "3065": "ListComp", + "3064": "Assert", + "3063": "IsNot", + "3062": "Import", + "3061": "Break", + "3060": "Is", + "3059": "Constant", + "3058": "File", + "3057": "Pass", + "3056": "Queue", + "3067": "BitAnd", + "3068": "keyword", + "3069": "bitOR", + "3070": "lower", + "3071": "print", + "3066": "JoinedStr", + "3072": "FormattedValue", + "3073": "NotIn", + "3074": "Bool" +} \ No newline at end of file diff --git a/streamlit_main.py b/streamlit_main.py new file mode 100644 index 0000000..ca2581d --- /dev/null +++ b/streamlit_main.py @@ -0,0 +1,59 @@ +import requests +from io import BytesIO +import streamlit as st +from streamlit_ace import st_ace +from concepts_parser import main, post_process_parser +import os +import pandas as pd + +# option = st.selectbox("Select Programming Language",("python","java")) + +pitt_url = 'https://www.pitt.edu/sites/default/files/assets/pitt_shield_white-home.png' +img_a = requests.get(pitt_url) +pitt_img = BytesIO(img_a.content).read() + +url = 'http://adapt2.sis.pitt.edu/w/images/1/19/PAWS_logo.png' +img_b = requests.get(url) +favicon = BytesIO(img_b.content).read() + +st.set_page_config(page_title="PCCP", + page_icon=favicon) +st.image(pitt_img,output_format='png') +st.image(favicon,output_format='png') + +st.title("Python Code Concepts Parser") + +code_string = """ +### enter code here + +""" \ +# if option == 'python' else \ +# """ +# // enter code here +# """ + +with st.form("code_form"): + + code = st_ace(value=code_string, + language="python", + min_lines= 50, + max_lines=500, + auto_update=True, + theme="dracula") + + content_name = st.text_input(label='Please Provide Aggregate2 Content Name:',placeholder='tmp1',value='tmp1',key='kc_content_component_name', disabled = not code) + activity_id = st.text_input(label='Please Provide um2 Activity Id:', key='um2_activity_id', placeholder='111111',value='111111',disabled = not code) + + submitted = st.form_submit_button("Submit Code") + + if submitted: + if not(os.path.exists('./py-files')): os.mkdir('py-files') + with open(f'./py-files/tmp1.py','w+') as f: + f.write(code) + + response = main(filename='py-files/tmp1.py') + smart_concepts_sections = pd.DataFrame.from_records(post_process_parser(response,content_name,activity_id)) + st.dataframe(smart_concepts_sections) + + os.remove('./py-files/tmp1.py') + os.rmdir('./py-files') diff --git a/test_docker.sh b/test_docker.sh new file mode 100644 index 0000000..c2ea9be --- /dev/null +++ b/test_docker.sh @@ -0,0 +1,11 @@ + +curl -X POST http://127.0.0.1:13456/extract_concepts -H "Content-Type: application/json" -d '{"code_str":"import txt"}' +echo '' +curl -X POST http://127.0.0.1:13456/extract_concepts -H "Content-Type: application/json" -d '{"code_str":"import txt\ntest=1"}' +echo '' +curl -X POST http://127.0.0.1:13456/extract_concepts -H "Content-Type: application/json" -d '{"code_str":"s='hola'"}' +echo '' +curl -X POST http://127.0.0.1:13456/extract_concepts -H "Content-Type: application/json" -d '{"code_str":"s='hola'\ns[0:2]"}' +echo '' +curl --fail http://localhost:13457/_stcore/health +echo '' diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..3fab9a1 --- /dev/null +++ b/utils.py @@ -0,0 +1,301 @@ +import ast, json, sys, re, os +from ast import Load,Store, For, If, While, Call, Add, Sub +from os import path +from webbrowser import get +from tqdm import tqdm +import pandas as pd +from ply.lex import lex +from version import __developer__ + +# These nodes will be ignored and are not added to the node list. +# +# For example, the operators are skipped b ecause the actual operator +# will be added to the list instead of the operator family. +nodesToSkip = {'Store', 'Load', 'Name', 'Expr', 'arg', 'arguments','Subscript', 'BoolOp', 'BinOp', 'Compare', 'UnaryOp'} ## we skip these because this data can be parsed with other nodes +tokensToSkip = {} +associated_py_concepts = json.load(open(path.join(path.dirname(__file__), './static/py_keyword_functions.json'))) ## function keywords associated concepts +op_py_concepts = json.load(open(path.join(path.dirname(__file__), './static/py_ops.json'))) + + +# ***************************************************************************** +# Special handlers for some nodes + +def handleNameConstant(node, line): + """ Converts the NameConstant node to represent the type of the value (True, False, None). """ + return str(node.value) + +def handleNum(node, line): + """ Converts the Num node to represent the type of the value (Int, Float). """ + return node.n.__class__.__name__.capitalize() + +handlers = {'Num' : handleNum, 'NameConstant' : handleNameConstant} + +def get_name_from_ast_object(node,type_name): + if type_name == 'Name': + + name = node.__dict__['id'] if 'id' in node.__dict__ else \ + ','.join([x.__dict__['id'] for x in node.__dict__['elts']]) if 'elts' in node.__dict__ else '' + + if name.endswith('Error'): return 'Exception-Types' + + if name in associated_py_concepts: return associated_py_concepts[name].capitalize() + if type(node.__dict__['ctx']) == Store: return 'Variable-decl-or-assign' + if type(node.__dict__['ctx']) == Load: return "Variable-usage" + + if type_name == 'Attribute': + # pass + name = node.__dict__['attr'] + if name.endswith('Try') or name.endswith('ExceptHandler'): return 'Exception-Handler' + if name in associated_py_concepts: return associated_py_concepts[name].capitalize() + return name + + if type_name == 'Call': + + CallObjectDict = node.__dict__['func'].__dict__ + CallObjectNode = node.__dict__['func'] + + lineno = CallObjectDict['lineno'] + + if False: print(CallObjectNode.__class__.name, + CallObjectDict, + CallObjectDict['id'] if 'id' in CallObjectDict['id'] else CallObjectDict['value'], + CallObjectDict['ctx'] + ) + + if 'id' in CallObjectDict: + return f"{associated_py_concepts[CallObjectDict['id']].capitalize()}" if CallObjectDict['id'] in associated_py_concepts else 'Class-Obj-Instantiate' + + elif 'attr' in CallObjectDict: + return f"{associated_py_concepts[CallObjectDict['attr']].capitalize()}" if CallObjectDict['attr'] in associated_py_concepts else 'ClassMethod-or-Function-Call' + + else: f"Parsed Concept {type_name}: this should not happen -- email {__developer__}" + + else: + + if type_name in op_py_concepts: + # print(type) + return op_py_concepts[type_name].capitalize() + + return type_name.capitalize() + + +def handle_nested_if(node_dict_body_or_else,name): + if len(node_dict_body_or_else) == 0: return name + + + if len(node_dict_body_or_else) > 0: + count_expr = 0 + for elements in node_dict_body_or_else: + if type(elements) == If: return f'Nested-{name}' + if not(type(elements) == If): count_expr += 1 + if count_expr == len(node_dict_body_or_else): return 'if-else' + + + + +# ***************************************************************************** + +def simpleTraverse(node, line, nodes,prev_node = None): + + name = node.__class__.__name__ + lineno = node.__dict__['lineno'] if 'lineno' in node.__dict__ else 0#node.__dict__[''].__dict__['lineno'] + # if name == 'Constant': print(re.split(r'[<,\s,>,\']',str(type(node.__dict__['value'])))) + # if name == 'Call': print(node.__dict__['func'].__dict__['id']) + # print(prev_node) + name = 'if-elif' if name.lower() == 'if' and not(prev_node == None) and type(prev_node) == If else name + + prev_node = node.__dict__['orelse'][0] if name.lower() == 'if' and \ + len(node.__dict__['orelse']) > 0 and\ + type(node.__dict__['orelse'][0]) == If \ + else node if prev_node == None else prev_node + + if name.lower() == 'if' or name.lower() == 'if-elif': + # print(node.__dict__) + name1 = f"{handle_nested_if(node.__dict__['body'],name.lower())}" + name2 = f"{handle_nested_if(node.__dict__['orelse'], name.lower())}" + name = name1 if name1.startswith("Nested") else name2 + + + if (name.lower() =='for' or name.lower() == 'while'): + name = name + # print(node.__dict__) + if name.lower() == 'while' and len(node.__dict__['orelse']) > 0: name = f'{name}-else'.capitalize() + if name.lower() == 'while': f"{name}-{get_name_from_ast_object(node.__dict__['test'],'')}".capitalize() + if name.lower() == 'for' and type(node.__dict__['iter']) == Call: name = f"{name}-{get_name_from_ast_object(node.__dict__['iter'],'Call')}-{get_name_from_ast_object(node.__dict__['target'],'Name')}".capitalize() + + for elements in node.__dict__['body']: + if type(elements) == For or type(elements) == While: name = f'Nested-{name}'.capitalize() + + # if type(elements) == Expr: + # print(elements) + # simpleTraverse(elements,node.__dict__['lineno'],nodes) + + if name.lower() == 'keyword': + name = f"keyword-args:{node.__dict__['arg']}" + + if name.lower() == 'augassign': + if type(node.__dict__['op']) == Add: name = "Assignment-with-Add" + if type(node.__dict__['op']) == Sub: name = "Assignment-with-Sub" + + if name == 'Name': + # print(name,node.__dict__) + # print(name, prev_node.__dict__) + + name = get_name_from_ast_object(node,'Name') + + + if name == 'Attribute': + # print(name, node.__dict__['attr'].capitalize(), node.__dict__['value'].__dict__['id'],prev_node.__dict__) + + name = get_name_from_ast_object(node,'Attribute') + + + if name == 'Constant': + # print(name, node.__dict__) + name = re.split(r'[<,\s,>,\']',str(type(node.__dict__['value'])))[3].capitalize() + + + if name == 'Call': + + name = get_name_from_ast_object(node,'Call') + + else: + if name not in nodesToSkip: + + name = get_name_from_ast_object(node,name) + + + if name not in nodesToSkip: + if line not in nodes['lines']: + nodes['lines'][line] = set() + if name not in handlers: + + nodes['lines'][line].add(name) + else: + nodes['lines'][line].add(handlers[name](node, line)) + + for child in ast.iter_child_nodes(node): + simpleTraverse(child, line, nodes, prev_node) + +def complexTraverse(node, line, nodes): + + name = node.__class__.__name__ + + # Only some nodes contain line number + if hasattr(node, 'lineno'): + line = node.lineno + + endLine = line + + current = {'name': name, 'startLine': line} + + if name not in nodesToSkip: + if line not in nodes['lines']: + nodes['lines'][line] = [] + if name not in handlers: + nodes['lines'][line].append(current) + else: + current['name'] = handlers[name](node, line) + nodes['lines'][line].append(current) + + maxLine = endLine + for child in ast.iter_child_nodes(node): + maxLine = max(maxLine, complexTraverse(child, line, nodes)) + + if maxLine != line: + current['endLine'] = maxLine + + return maxLine + +def hierarchicalTraverse(node, line, currentNode): + + name = node.__class__.__name__ + + # Only some nodes contain line number + if hasattr(node, 'lineno'): + line = node.lineno + + endLine = line + + current = {'name': name, 'startLine': line, 'children': []} + + if name not in nodesToSkip: + if name not in handlers: + currentNode['children'].append(current) + else: + current['name'] = handlers[name](node, line) + currentNode['children'].append(current) + else: + current = currentNode + + maxLine = endLine + for child in ast.iter_child_nodes(node): + maxLine = max(maxLine, hierarchicalTraverse(child, line, current)) + + if maxLine != line: + current['endLine'] = maxLine + + return maxLine + + +def read_input_files(local=True,filename='./py-files/chap2/sec_2_1.py',format="simple"): + if not(local): + data = input() + parsed = json.loads(data) + code = parsed['code'] + mode = parsed.get('mode', 'simple') + return code,mode + + if local: + with open(filename) as f: + code = f.read() + codelines = code.split('\n') + return code,codelines, format + +def merge_lines_nodes(nodes): + conceptset = [] + for lineno,conceptlist in nodes['lines'].items(): + conceptset.extend(set(conceptlist)) + return set(conceptset) + + +def lexer_tokens(code): + tokens = ( + 'NAME','NUMBER', + 'PLUS','MINUS','TIMES','DIVIDE','EQUALS', + 'LPAREN','RPAREN', + ) + + # Tokens + + t_PLUS = r'\+' + t_MINUS = r'-' + t_TIMES = r'\*' + t_DIVIDE = r'/' + t_EQUALS = r'=' + t_LPAREN = r'\(' + t_RPAREN = r'\)' + t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' + + lexer = lex() + + # Parsing rules + + precedence = ( + ('left','PLUS','MINUS'), + ('left','TIMES','DIVIDE'), + ('right','UMINUS'), + ) + + lexer.input(code) + ret_tokens = [] + while True: + tok = lexer.token() + if not tok: + break + + if not(tok in tokensToSkip): + ret_tokens.append(tok) + + return set(ret_tokens) + diff --git a/version.py b/version.py new file mode 100644 index 0000000..3c564f2 --- /dev/null +++ b/version.py @@ -0,0 +1,2 @@ +__version__ = 0.3 +__developer__ = 'arl122@pitt.edu' \ No newline at end of file