《java语言程序设计》初步学习——各种小Demo
发现现在的天下几乎都是java的天下啊,虽然我个人对java没什么好感,但是迫于生活压力,还是学一下吧,我关注的应该主要还是web方面,所以应该学的是
java server page(JSP),所以先把javase的内容先复习复习一下吧。
我觉得通过一些demo来记语言中的一些特性和概念是比较好的,所以我总结了以下的Demo:(这只是对我个人而言比较薄弱的部分,并不能代表大部分人的看法,谢谢!)
1.一维数组与多维数组
package Demo;
public class Array {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//新建一个10元素的数组
int[] a = new int[10];
for(int i = 0;i < 10;i++){
a[i] = i;
}
System.out.println("改变前:" );
for(int i = 0;i < 10;i++){
System.out.print(a[i]+" ");
}
System.out.printf("\n");
a = reserve1(a);
System.out.println("reserve1后:");
for(int i = 0;i < 10;i++){
System.out.print(a[i]+" ");
}
System.out.printf("\n");
reserve2(a);
System.out.println("reserve2后:");
printArray(a);
//二维数组的特性
int[][] a2 = {
{1,2,3},
{2,3},
{1,2,3}
};
int i;
System.out.println("a2 is " + a2.length);
for(i = 0;i < a2.length;i++){
System.out.println(i+" is "+a2[i].length);
}
}
//从方法中返回数组
public static int[] reserve1(int[] list){
int[] result = new int[list.length];
for(int i = 0,j = result.length-1;i < list.length;i++,j--){
result[j] = list[i];
}
return result;
}
//直接处理:引用传递
public static void reserve2(int[] list){
int temp;
for(int i = 0,j = list.length - 1;i < list.length / 2;i++,j--){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
//可变长的参数列表
public static void printArray(int... num){
if(num.length == 0){
System.out.println("No 参数!");
}
else{
for(int i = 0;i < num.length;i++){
System.out.print(num[i] + " ");
}
System.out.print("\n");
}
}
}
2.对象与类
注意:包内访问与包外访问(包外访问加上:import packet.class_name):
/*TTV.java*/
package Home;
import Home2.STV;
import Home2.Date; public class TTV { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
STV tv1 = new STV();
tv1.turnOn();
tv1.setChannel(30);
tv1.setVolume(3); STV tv2 = new STV();
tv2.turnOn();
tv2.channelUp();
tv2.channelUp();
tv2.volumeUp(); System.out.println("tv1's channel is" + tv1.channel
+ " and volume level is " + tv1.volumeLevel);
System.out.println("tv2's channel is" + tv2.channel
+ " and volume level is " + tv2.volumeLevel);
System.out.println("count1 = " + tv1.numplus());
System.out.println("count2 = " + tv1.numplus());
System.out.println("count3 = " + tv2.numplus()); } } /*STV.java*/
package Home2; public class STV {
public int channel = 1;
public int volumeLevel = 1;
public boolean on = false;
public static int num = 0;
public STV(){ }
public static int numplus(){
num++;
return num;
}
public void turnOn(){
on = true;
} public void turnOff(){
on = false;
} public void setChannel(int newChannel){
if(on && newChannel >= 1 && newChannel <= 120)
channel = newChannel;
} public void setVolume(int newVolumeLevel){
if(on && newVolumeLevel >= 1 && newVolumeLevel <= 7){
volumeLevel = newVolumeLevel;
}
} public void channelUp(){
if(on && channel < 120)
channel++;
} public void channelDown(){
if(on && channel >1){
channel--;
}
} public void volumeUp(){
if(on && volumeLevel < 7){
volumeLevel++;
}
} public void volumeDown(){
if(on && volumeLevel > 1){
volumeLevel--;
}
}
}
this引用:指向调用对象本身得引用名。
静态方法才能修改静态变量。
package Demo;
public class Foo {
int i = 5;
static double k = 0;
public static void main(String[] args){
Foo f = new Foo();
f.setK(2.0);
System.out.println("k = " + k);
}
void setI(int i){
this.i = i;
}
public static void setK(double k){
Foo.k = k;
}
}
3.继承与多态
在继承关系中,构造函数无法覆盖,类只能单一继承。注意下面例子:
注意动态绑定:
package Home2;
public class Date extends Date1{
public static void main(String[] args){
Date d1 = new Date("1");
System.out.println(d1.getNum(3));
//下面上动态绑定的结果
System.out.println("动态绑定: ");
Date1 d2 = new Date();
}
public Date(){
System.out.println("(1)");
}
public Date(String s){
super("4");
System.out.println(s);
}
//终极函数,意味着不能再被扩展
public final int getNum(int a){
return super.getNum(a);
}
}
class Date1{
public Date1(){
System.out.println("(2)");
}
public Date1(String s){
System.out.println(s);
}
public int getNum(int a){
return 2*a;
}
}
class Date2{
public Date2(){
System.out.println("(5)");
}
}
数据和方法的可见性
| 类中成员的修饰符 | 在同一类内访问 | 在同一包内访问 | 在子类内可访问 | 在不同包可访问 |
| public | Y | Y | Y | Y |
| protected | Y | Y | Y | - |
| default(不用填也不能填的默认属性 | Y | Y | - | - |
| private | Y | - | - | - |
防止扩展和覆盖:final
终极类:public final class
终极方法:public final void m()
常量:static final PI = 3.1415926;
4.抽象类和接口
抽象类:类的设计应该确保父类包含它的子类的共同特征。有时候,一个父类设计得非常抽象,以至于它都没有任何具体的实例。抽象类的构造函数的默认属性是protected。
接口:为了定义多个类(特别是不相关的类)的共同行为。
接口与抽象类
| 变量 | 构造方法 | 方法 | |
| 抽象类 | 无限制 |
子类通过构造方法链调用构造方法, 抽象类不能用new操作符实例化 |
无限制 |
| 接口 |
所有的变量必须是 public static final |
没有构造方法。 接口不能用new操作符实例化。 |
所有方法必须是公共的抽象实例方法 |
Java只允许为类的扩展做单一继承,但是允许使用接口做多重扩展。
抽象类Demo:
package Demo;
public class TestAnimal {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal animal = new Chicken();
eat(animal);
animal = new Duck();
eat(animal);
}
public static void eat(Animal animal){
System.out.println(animal.howToEat());
}
}
abstract class Animal{
public abstract String howToEat();
}
class Chicken extends Animal{
public String howToEat(){
return "Chicken";
}
}
class Duck extends Animal{
public String howToEat(){
return "Duck";
}
}
接口Demo:
package Demo;
public class TestInterface {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Edible stuff = new Chicken();
Edible1 stuff1 = new Broccoli();
eat(stuff);
stuff = new Duck();
eat(stuff);
stuff = new Broccoli();
eat(stuff);
sleep(stuff1);
}
public static void eat(Edible stuff){
System.out.println(stuff.howToEat());
}
public static void sleep(Edible1 stuff1){
System.out.println(stuff1.howToSleep());
}
}
interface Edible{
public String howToEat();
}
interface Edible1{
public String howToSleep();
}
class Chicken implements Edible{
public String howToEat(){
return "Chicken";
}
}
class Duck implements Edible{
public String howToEat(){
return "Duck";
}
}
class Broccoli implements Edible,Edible1{
public String howToEat(){
return "Broccoli";
}
public String howToSleep() {
// TODO Auto-generated method stub
return "Sleep";
}
}
5.文本I/O
一.File类的基本函数
package Demo;
public class TestFileClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
java。io.File file = new java.io.File("image/gif");
System.out.println("Does it exist? "+file.exists());
System.out.println("The file has " + file.length() + " bytes");
System.out.println("can it be read? " + file.canRead());
System.out.println("can it be written? " + file.canWrite());
System.out.println("Is it a directory? " + file.isDirectory());
System.out.println("Is it a file? " + file.isFile());
System.out.println("Is it absolute? " + file.isAbsolute());
System.out.println("Is it a Hidden? " + file.isHidden());
System.out.println("Absolute path is " + file.getAbsolutePath());
System.out.println("Last modified on " + new java.util.Date(file.lastModified()));
}
}
二.使用PrintWriter写数据
package Demo;
public class WriteData {
/**
* @param args
*/
public static void main(String[] args) throws Exception { //抛出异常
// TODO Auto-generated method stub
java.io.File file = new java.io.File("score.txt"); //建立文件对象
if(file.exists()){
System.out.println("File already exist");
System.exit(0);
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.print("Hello!My id is ");
output.print(11365020);
output.println("!");
//close
output.close();
}
}
三.使用Scanner读数据
package Demo;
import java.util.Scanner;
public class ReadData {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
java.io.File file = new java.io.File("score.txt");
Scanner input = new Scanner(file);
while(input.hasNext()){
String firname = input.next();
String mi = input.next();
int score = input.nextInt();
System.out.println(firname + mi + score);
}
input.close();
}
}
注意:方法next()和nextLine()都会读取一个字符串,next()方法读取一个由分隔符分隔的字符串,但是nextLine()读取一个以行分隔符结束的行。
6.泛型
一.定义泛型类和接口
//GenericStack.java
package Demo; public class GenericStack { private java.util.ArrayList<E> list = new java.util.ArrayList<E>(); public int getSize(){
return list.size();
} public E peek(){
return list.get(getSize() - 1);
} public void push(E o){
list.add(o);
} public E pop(){
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
} public boolean isEmpty(){
return list.isEmpty();
}
}
7.Java集合框架
关于java的集合框架,建议还是查一下文档,其实和C++的STL库差不多,只是功能上可能丰富了一点。下面介绍几个常用的:
一.Collection接口
二.Set接口
Set接口扩展了Collection接口。它没有引入新的方法或常量,只是规定Set实例不包含重复的元素。
(1).散列集HashSet
package Demo;
import java.util.*;
public class TestHashSet {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> set = new HashSet<String>();
//添加元素
set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Franciso");
set.add("New York");
System.out.println(set);
//迭代器迭代
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next().toUpperCase() + " ");
}
}
}
(2).链式散列集LinkedHashSet
LinkedHashSet用一个链表实现来扩展HashSet类,它支持对规则集内的元素排序。
package Demo;
import java.util.*;
public class TestLinkedHashSet {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> set = new LinkedHashSet<String>();
//添加元素
set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Franciso");
set.add("Beijing");
set.add("New York");
System.out.println(set);
//使用for-each循环
for(Object element:set)
System.out.println(element.toString().toLowerCase() + " ");
}
}
(3).树形集TreeSet
package Demo;
import java.util.*;
public class TestTreeSet {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> set = new HashSet<String>();
set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Francisco");
TreeSet<String> treeSet = new TreeSet<String>(set);
System.out.println("Sorted tree set: " + treeSet);
System.out.println("first()" + treeSet.first());
System.out.println("last()" + treeSet.last());
System.out.println("headSet(): " + treeSet.headSet("New York"));
System.out.println("tailSet(): " + treeSet.tailSet("New York"));
System.out.println("lower(\"P\"): " + treeSet.lower("P"));
System.out.println("higher(\"P\"): " + treeSet.higher("P"));
System.out.println("floor(\"P\"): " + treeSet.floor("P"));
System.out.println("ceiling(\"P\"): " + treeSet.ceiling("P"));
System.out.println("pollFirst(): " + treeSet.pollFirst());
System.out.println("pollLast() : " + treeSet.pollLast());
System.out.println("New tree set: " + treeSet);
}
}
三.List接口
List接口增加了面向位置的操作,并且增加了一个能够双向遍历线性表的新列表迭代器。
(1).数组线性表ArrayList和链表类LinkedList
package Demo;
import java.util.*;
public class TestArrayAndLinkedList {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(1);
arrayList.add(4);
arrayList.add(0,10);
arrayList.add(3,30);
System.out.println("A list of integers in the array list:");
System.out.println(arrayList);
LinkedList<Object> linkedList = new LinkedList<Object>(arrayList);
linkedList.add(1,"red");
linkedList.removeLast();
linkedList.addFirst("green");
System.out.println("Display the linked list forward:");
ListIterator<Object> listIterator = linkedList.listIterator();
while(listIterator.hasNext()){
System.out.print(listIterator.next() + " ");
}
System.out.println("Display the linked list backward:");
listIterator = linkedList.listIterator(linkedList.size());
while(listIterator.hasPrevious()){
System.out.print(listIterator.previous() + " ");
}
}
}
四.向量类Vector与栈类Stack
五.队列与优先队列
Queue扩展的是Collection:
package Demo;
public class TestQueue {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
java.util.Queue<String> queue = new java.util.LinkedList<String>();
queue.offer("Oklahoma");
queue.offer("Indiana");
queue.offer("Georgia");
queue.offer("Texas");
while(queue.size() > 0)
System.out.print(queue.remove() + " ");
}
}
优先队列:PriorityQueueDemo
package Demo;
import java.util.*;
public class PriorityQueueDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PriorityQueue<String> queue1 = new PriorityQueue<String>();
queue1.offer("Oklahoma");
queue1.offer("Indiana");
queue1.offer("Georgia");
queue1.offer("Texas");
System.out.println("Priority queue using Comparable:");
while(queue1.size() > 0){
System.out.print(queue1.remove() + " ");
}
PriorityQueue<String> queue2 = new PriorityQueue<String>(4,Collections.reverseOrder());
queue2.offer("Oklahoma");
queue2.offer("Indiana");
queue2.offer("Georgia");
queue2.offer("Texas");
System.out.println("\nPriority queue using Comparable:");
while(queue2.size() > 0){
System.out.print(queue2.remove() + " ");
}
}
}
六.图
图分三种,见以下代码:
package Demo;
import java.util.*;
public class TestMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,Integer> hashMap = new HashMap<String,Integer>();
hashMap.put("Smith", 30);
hashMap.put("Anderson", 31);
hashMap.put("Lewis", 29);
hashMap.put("Cook", 29);
System.out.println("Display entries in HashMap");
System.out.println(hashMap + "\n");
Map<String,Integer> treeMap = new TreeMap<String,Integer>(hashMap);
System.out.println("Display entries in ascending order of key");
System.out.println(treeMap);
Map<String,Integer> linkedHashMap = new LinkedHashMap<String,Integer>(16,0.75f,true);
linkedHashMap.put("Smith", 30);
linkedHashMap.put("Anderson",31);
linkedHashMap.put("Lewis", 29);
linkedHashMap.put("Cook", 29);
System.out.println("The age for " + "Lewis is " + linkedHashMap.get("Lewis").intValue());
System.out.println("\nDisplay entries in LinkedHashMap");
System.out.println(linkedHashMap);
}
}
《java语言程序设计》初步学习——各种小Demo的更多相关文章
- Java语言程序设计-助教篇
1. 给第一次上课(软件工程)的老师与助教 现代软件工程讲义 0 课程概述 给学生:看里面的第0个作业要求 2. 助教心得 美国视界(1):第一流的本科课堂该是什么样?(看里面的助教部分) 助教工作看 ...
- 0031 Java学习笔记-梁勇著《Java语言程序设计-基础篇 第十版》英语单词
第01章 计算机.程序和Java概述 CPU(Central Processing Unit) * 中央处理器 Control Unit * 控制单元 arithmetic/logic unit /ə ...
- 《JAVA语言程序设计》上课笔记
教学目标:1.使学生了解JAVA课程的性质.定位.作用:为什么要学习JAVA?让学生知道如何学好JAVA: 教学内容: 一. 问几个问题 1. 你们到这里来干什么 ...
- C语言程序设计入门学习五步曲(转发)
笔者在从事教学的过程中,听到同学抱怨最多的一句话是:老师,上课我也能听懂,书上的例题也能看明白,可是到自己动手做编程时,却不知道如何下手.发生这种现象的原因有三个: 一.所谓的看懂听明白,只是很肤浅的 ...
- java线程间通信:一个小Demo完全搞懂
版权声明:本文出自汪磊的博客,转载请务必注明出处. Java线程系列文章只是自己知识的总结梳理,都是最基础的玩意,已经掌握熟练的可以绕过. 一.从一个小Demo说起 上篇我们聊到了Java多线程的同步 ...
- Java语言特点与学习
Java语言是一款面向对象的一款高级语言是由Sun Microsystems公司(现已被oracle公司收购).由James Gosling和同事们共同研发,并在1995年正式推出,据oracle官方 ...
- 全国计算机等级考试二级笔试样卷Java语言程序设计
一.选择题((1)-(35)每小题2分,共70分) 下列各题A).B).C).D)四个选项中,只有一个选项是正确的,请将正确选项涂写在答题卡相应位置上,答在试卷上不得分. (1)下列选项中不符合良好程 ...
- Java语言程序设计(基础篇)第一章
第一章 计算机.程序和Java概述 1.1 引言 什么是程序设计呢? 程序设计就是创建(或者开发)软件,软件也称为程序. 1.2 什么是计算机 计算机是存储和处理数据的电子设备,计算机包括硬件(har ...
- 【任务】Python语言程序设计.MOOC学习
[博客导航] [Python导航] 任务 18年11月29日开始,通过9周时间跨度,投入约50小时时间,在19年1月25日之前,完成中国大学MOOC平台上的<Python语言程序设计>课程 ...
随机推荐
- 深入理解JAVA I/O系列一:File
I/O简介 I/O问题可以说是当今web应用中所面临的的主要问题之一,大部分的web应用系统的瓶颈都是I/O瓶颈.这个系列主要介绍JAVA的I/O类库基本架构.磁盘I/O工作机制.网络I/O工作机制以 ...
- 使用docker inspect获取数据卷信息时返回地址为空
使用 docker inspect 命令查看容器挂载的volume的目录 $ sudo docker inspect --format "{{.Volumes}}" redis-m ...
- jQ 小球碰撞检测
<!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...
- Window下Neo4j安装教程
一.neo4j 介绍 Neo4j是一个高性能的,NOSQL图形数据库,它将结构化数据存储在网络上而不是表中.它是一个嵌入式的.基于磁盘的.具备完全的事务特性的Java持久化引擎,但是它将结构化数据存储 ...
- [Cnbeta]BAT财报对比
https://www.cnbeta.com/articles/tech/789123.htm 随着腾讯上周公布财报,BAT三家2018年第三季度的数据均已公布,曾经与腾讯.阿里齐名的百度正被拉开越来 ...
- 【百度】大型网站的HTTPS实践(三)——HTTPS对性能的影响
HTTPS在保护用户隐私,防止流量劫持方面发挥着非常关键的作用,但与此同时,HTTPS也会降低用户访问速度,增加网站服务器的计算资源消耗.本文主要介绍HTTPS对性能的影响. HTTPS对访问速度的影 ...
- 2012r2 以及 2012r2 withupdate 已经安装更新的差异
0. 2012r2 不管带不带 update 1 他的版本号 都是 6.3.9600 如图示 2012r2的发布时间是 2013年 2012r2withupdate的发布时间是 2014年. 查看补丁 ...
- elasticsearch6 学习之安装
安装环境:centos6.5 64位 jdk1.8 elasticsearch6.1.1 一.启动 [root@localhost bin]# ./elasticsearch - ...
- UVALive6443_Alien Abduction Again
题意为给你若干个三次函数,以及每一个函数所分布的区间,由于每个函数的所有的系数都是整数,所以最后的函数在整数点处的值也是整数. 现在每次可以插入函数或者询问区间,现在要求每次询问区间后,所有的函数在这 ...
- 对HashMap的理解(一):HashMap的实现
一.HashMap介绍 1. 定义HashMap实现了Map接口,继承AbstractMap类.其中Map接口定义了键映射到值的规则,而AbstractMap类提供 Map 接口的骨干实现,以最大限度 ...